Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: List view and sorting of projects in dashboard (#5467)

Oleg Isonenb7356e0c37e3
diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsx
index 28ab6aaffc..dcb7050bf7 100644
--- a/apps/builder/app/dashboard/dashboard.tsx
+++ b/apps/builder/app/dashboard/dashboard.tsx
@@ -174,6 +174,7 @@ export const Dashboard = () => {
as="aside"
align="stretch"
direction="column"
+ shrink={false}
css={{
width: theme.sizes.sidebarWidth,
borderRight: `1px solid ${theme.colors.borderMain}`,
diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsx
index 9cf71af6d2..ddd5a89d88 100644
--- a/apps/builder/app/dashboard/projects/project-card.tsx
+++ b/apps/builder/app/dashboard/projects/project-card.tsx
@@ -1,10 +1,5 @@
import { useEffect, useState } from "react";
import {
- DropdownMenu,
- DropdownMenuTrigger,
- DropdownMenuContent,
- DropdownMenuItem,
- IconButton,
css,
Flex,
Text,
@@ -15,7 +10,7 @@ import {
Link,
Box,
} from "@webstudio-is/design-system";
-import { InfoCircleIcon, EllipsesIcon } from "@webstudio-is/icons";
+import { InfoCircleIcon, UploadIcon } from "@webstudio-is/icons";
import type { DashboardProject } from "@webstudio-is/dashboard";
import { builderUrl } from "~/shared/router-utils";
import {
@@ -32,6 +27,8 @@ import { Spinner } from "../shared/spinner";
import { Card, CardContent, CardFooter } from "../shared/card";
import type { User } from "~/shared/db/user.server";
import { TagsDialog } from "./tags";
+import { ProjectMenu } from "./project-menu";
+import { formatDate } from "./utils";
const infoIconStyle = css({ flexShrink: 0 });
@@ -58,52 +55,6 @@ const PublishedLink = ({
);
};
-const Menu = ({
- tabIndex,
- onDelete,
- onRename,
- onDuplicate,
- onShare,
- onUpdateTags,
-}: {
- tabIndex: number;
- onDelete: () => void;
- onRename: () => void;
- onDuplicate: () => void;
- onShare: () => void;
- onUpdateTags: () => void;
-}) => {
- const [isOpen, setIsOpen] = useState(false);
- return (
- <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="Menu Button"
- tabIndex={tabIndex}
- css={{ alignSelf: "center" }}
- >
- <EllipsesIcon width={15} height={15} />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" css={{ width: theme.spacing[24] }}>
- <DropdownMenuItem onSelect={onDuplicate}>Duplicate</DropdownMenuItem>
- <DropdownMenuItem onSelect={onRename}>Rename</DropdownMenuItem>
- <DropdownMenuItem onSelect={onShare}>Share</DropdownMenuItem>
- <DropdownMenuItem onSelect={onUpdateTags}>Tags</DropdownMenuItem>
- <DropdownMenuItem onSelect={onDelete}>Delete</DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-};
-
-const formatDate = (date: string) => {
- return new Date(date).toLocaleDateString("en-US", {
- year: "numeric",
- month: "short",
- day: "numeric",
- });
-};
-
type ProjectCardProps = {
project: DashboardProject;
hasProPlan: boolean;
@@ -196,6 +147,24 @@ export const ProjectCard = ({
opacity: 0,
}}
/>
+ {isPublished && (
+ <Box
+ css={{
+ position: "absolute",
+ top: theme.spacing[5],
+ left: theme.spacing[5],
+ zIndex: 1,
+ backgroundColor: "oklch(0 0 0 / 0.3)",
+ borderRadius: theme.borderRadius[3],
+ padding: theme.spacing[2],
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <UploadIcon color={rawTheme.colors.foregroundContrastMain} />
+ </Box>
+ )}
<Flex
wrap="wrap"
gap={1}
@@ -245,13 +214,19 @@ export const ProjectCard = ({
variant="wrapped"
content={
<Text variant="small">
- Created on {formatDate(createdAt)}
- {latestBuildVirtual?.publishStatus === "PUBLISHED" && (
+ Created: {formatDate(createdAt)}
+ {latestBuildVirtual?.updatedAt && (
<>
<br />
- Published on {formatDate(latestBuildVirtual.createdAt)}
+ Last modified: {formatDate(latestBuildVirtual.updatedAt)}
</>
)}
+ <br />
+ {latestBuildVirtual?.publishStatus === "PUBLISHED" ? (
+ <>Published: {formatDate(latestBuildVirtual.createdAt)}</>
+ ) : (
+ <>Not published</>
+ )}
</Text>
}
>
@@ -268,8 +243,7 @@ export const ProjectCard = ({
<Text color="subtle">Not Published</Text>
)}
</Flex>
- <Menu
- tabIndex={-1}
+ <ProjectMenu
onDelete={() => setIsDeleteDialogOpen(true)}
onRename={() => setIsRenameDialogOpen(true)}
onShare={() => setIsShareDialogOpen(true)}
diff --git a/apps/builder/app/dashboard/projects/project-menu.tsx b/apps/builder/app/dashboard/projects/project-menu.tsx
new file mode 100644
index 0000000000..2cff5b5cbe
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/project-menu.tsx
@@ -0,0 +1,48 @@
+import { useState } from "react";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ IconButton,
+ theme,
+} from "@webstudio-is/design-system";
+import { EllipsesIcon } from "@webstudio-is/icons";
+
+type ProjectMenuProps = {
+ onDelete: () => void;
+ onRename: () => void;
+ onDuplicate: () => void;
+ onShare: () => void;
+ onUpdateTags: () => void;
+};
+
+export const ProjectMenu = ({
+ onDelete,
+ onRename,
+ onDuplicate,
+ onShare,
+ onUpdateTags,
+}: ProjectMenuProps) => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Menu Button"
+ tabIndex={-1}
+ css={{ alignSelf: "center", position: "relative", zIndex: 1 }}
+ >
+ <EllipsesIcon width={15} height={15} />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" css={{ width: theme.spacing[24] }}>
+ <DropdownMenuItem onSelect={onDuplicate}>Duplicate</DropdownMenuItem>
+ <DropdownMenuItem onSelect={onRename}>Rename</DropdownMenuItem>
+ <DropdownMenuItem onSelect={onShare}>Share</DropdownMenuItem>
+ <DropdownMenuItem onSelect={onUpdateTags}>Tags</DropdownMenuItem>
+ <DropdownMenuItem onSelect={onDelete}>Delete</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/apps/builder/app/dashboard/projects/projects-list.tsx b/apps/builder/app/dashboard/projects/projects-list.tsx
new file mode 100644
index 0000000000..1d36b5991e
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/projects-list.tsx
@@ -0,0 +1,301 @@
+import { useState } from "react";
+import {
+ Flex,
+ Text,
+ theme,
+ Link,
+ css,
+ List,
+ ListItem,
+ IconButton,
+} from "@webstudio-is/design-system";
+import { ChevronUpIcon, ChevronDownIcon } from "@webstudio-is/icons";
+import type { DashboardProject } from "@webstudio-is/dashboard";
+import { builderUrl } from "~/shared/router-utils";
+import {
+ RenameProjectDialog,
+ DeleteProjectDialog,
+ useCloneProject,
+ ShareProjectDialog,
+} from "./project-dialogs";
+import type { User } from "~/shared/db/user.server";
+import { TagsDialog } from "./tags";
+import { ProjectMenu } from "./project-menu";
+import { formatDate } from "./utils";
+import type { SortField, SortOrder } from "./sort";
+
+const tableStyles = css({
+ display: "table",
+ width: "100%",
+ tableLayout: "fixed",
+ borderCollapse: "collapse",
+ marginBottom: theme.spacing[13],
+ minWidth: 550,
+ flexGrow: 1,
+
+ '& [role="rowgroup"]': {
+ display: "table-row-group",
+ },
+
+ '& [role="row"]': {
+ display: "table-row",
+ position: "relative",
+ "&:focus-visible": {
+ outline: `1px solid ${theme.colors.borderFocus}`,
+ },
+ '&:has([role="cell"]):hover': {
+ background: theme.colors.backgroundHover,
+ },
+ },
+
+ '& [role="columnheader"]': {
+ display: "table-cell",
+ padding: theme.spacing[5],
+ paddingBottom: theme.spacing[3],
+ textAlign: "left",
+ borderBottom: `1px solid ${theme.colors.borderMain}`,
+ "&:first-child": {
+ width: "35%",
+ },
+ "&:nth-child(2), &:nth-child(3), &:nth-child(4)": {
+ width: "20%",
+ },
+ "&:last-child": {
+ width: "5%",
+ },
+ },
+
+ '& [role="cell"]': {
+ display: "table-cell",
+ padding: theme.spacing[5],
+ verticalAlign: "middle",
+ },
+});
+
+type ProjectsListItemProps = {
+ project: DashboardProject;
+ hasProPlan: boolean;
+ publisherHost: string;
+ projectsTags: User["projectsTags"];
+};
+
+export const ProjectsListItem = ({
+ project: {
+ id,
+ title,
+ domain,
+ isPublished,
+ createdAt,
+ latestBuildVirtual,
+ tags,
+ domainsVirtual,
+ },
+ hasProPlan,
+ publisherHost,
+ projectsTags,
+}: ProjectsListItemProps) => {
+ const customDomain = domainsVirtual?.find(
+ (d: { domain: string; status: string; verified: boolean }) =>
+ d.status === "ACTIVE" && d.verified
+ )?.domain;
+ const displayDomain = customDomain ?? `${domain}.${publisherHost}`;
+ const [openDialog, setOpenDialog] = useState<
+ "rename" | "delete" | "share" | "tags" | undefined
+ >(undefined);
+ const [isHidden, setIsHidden] = useState(false);
+ const handleCloneProject = useCloneProject(id);
+
+ if (isHidden) {
+ return;
+ }
+
+ const projectTagsIds = (tags || [])
+ .map((tagId) => {
+ const tag = projectsTags.find((tag) => tag.id === tagId);
+ return tag ? tag.id : undefined;
+ })
+ .filter(Boolean) as string[];
+
+ const linkPath = builderUrl({ origin: window.origin, projectId: id });
+
+ return (
+ <>
+ <ListItem index={0} asChild>
+ <div role="row">
+ <div role="cell">
+ <Flex direction="column" gap="1">
+ <Link
+ href={linkPath}
+ color="inherit"
+ underline="none"
+ tabIndex={-1}
+ stretched
+ >
+ {title}
+ </Link>
+ {isPublished && (
+ <Link
+ href={`https://${displayDomain}`}
+ target="_blank"
+ rel="noreferrer"
+ color="subtle"
+ underline="hover"
+ tabIndex={-1}
+ aria-label={`Visit ${title} website at ${displayDomain}`}
+ css={{ zIndex: 1 }}
+ >
+ {displayDomain}
+ </Link>
+ )}
+ </Flex>
+ </div>
+
+ <div role="cell">
+ <Text color="subtle">
+ {latestBuildVirtual?.updatedAt
+ ? formatDate(latestBuildVirtual.updatedAt)
+ : formatDate(createdAt)}
+ </Text>
+ </div>
+
+ <div role="cell">
+ <Text color="subtle">
+ {isPublished && latestBuildVirtual
+ ? formatDate(latestBuildVirtual.createdAt)
+ : "Not published"}
+ </Text>
+ </div>
+
+ <div role="cell">
+ <Text color="subtle">{formatDate(createdAt)}</Text>
+ </div>
+
+ <div role="cell">
+ <ProjectMenu
+ onDelete={() => setOpenDialog("delete")}
+ onRename={() => setOpenDialog("rename")}
+ onShare={() => setOpenDialog("share")}
+ onDuplicate={handleCloneProject}
+ onUpdateTags={() => setOpenDialog("tags")}
+ />
+ </div>
+ </div>
+ </ListItem>
+
+ <RenameProjectDialog
+ isOpen={openDialog === "rename"}
+ onOpenChange={(open) => setOpenDialog(open ? "rename" : undefined)}
+ title={title}
+ projectId={id}
+ />
+ <DeleteProjectDialog
+ isOpen={openDialog === "delete"}
+ onOpenChange={(open) => setOpenDialog(open ? "delete" : undefined)}
+ onHiddenChange={setIsHidden}
+ title={title}
+ projectId={id}
+ />
+ <ShareProjectDialog
+ isOpen={openDialog === "share"}
+ onOpenChange={(open) => setOpenDialog(open ? "share" : undefined)}
+ projectId={id}
+ hasProPlan={hasProPlan}
+ />
+ <TagsDialog
+ projectId={id}
+ projectsTags={projectsTags}
+ projectTagsIds={projectTagsIds}
+ isOpen={openDialog === "tags"}
+ onOpenChange={(open) => setOpenDialog(open ? "tags" : undefined)}
+ />
+ </>
+ );
+};
+
+type ProjectsListProps = {
+ projects: Array<DashboardProject>;
+ hasProPlan: boolean;
+ publisherHost: string;
+ projectsTags: User["projectsTags"];
+ sortBy?: SortField;
+ sortOrder?: SortOrder;
+ onSortChange: (field: SortField) => void;
+};
+
+const columns: Array<{ field: SortField; label: string } | null> = [
+ { field: "title", label: "Name" },
+ { field: "updatedAt", label: "Last modified" },
+ { field: "publishedAt", label: "Last published" },
+ { field: "createdAt", label: "Date created" },
+ null, // Actions column (no sorting)
+];
+
+export const ProjectsList = ({
+ projects,
+ hasProPlan,
+ publisherHost,
+ projectsTags,
+ sortBy,
+ sortOrder,
+ onSortChange,
+}: ProjectsListProps) => {
+ return (
+ <div className={tableStyles()} role="table" aria-label="Projects list">
+ <List asChild>
+ <div role="rowgroup">
+ <ListItem index={0} asChild>
+ <div role="row">
+ {columns.map((column, index) => (
+ <div role="columnheader" key={index}>
+ {column ? (
+ <Flex gap="1" align="center">
+ <Text
+ variant="regularBold"
+ id={`sort-${column.field}-label`}
+ >
+ {column.label}
+ </Text>
+ <IconButton
+ onClick={() => onSortChange(column.field)}
+ css={{ opacity: sortBy === column.field ? 1 : 0.5 }}
+ aria-label={`Sort by ${column.label}${
+ sortBy === column.field
+ ? sortOrder === "asc"
+ ? ", sorted ascending"
+ : ", sorted descending"
+ : ", not sorted"
+ }`}
+ aria-describedby={`sort-${column.field}-label`}
+ tabIndex={-1}
+ >
+ {sortBy === column.field && sortOrder === "asc" ? (
+ <ChevronUpIcon />
+ ) : (
+ <ChevronDownIcon />
+ )}
+ </IconButton>
+ </Flex>
+ ) : undefined}
+ </div>
+ ))}
+ </div>
+ </ListItem>
+ </div>
+ </List>
+
+ <List asChild>
+ <div role="rowgroup">
+ {projects.map((project) => (
+ <ProjectsListItem
+ key={project.id}
+ project={project}
+ hasProPlan={hasProPlan}
+ publisherHost={publisherHost}
+ projectsTags={projectsTags}
+ />
+ ))}
+ </div>
+ </List>
+ </div>
+ );
+};
diff --git a/apps/builder/app/dashboard/projects/projects.tsx b/apps/builder/app/dashboard/projects/projects.tsx
index 8325660836..abe993b38a 100644
--- a/apps/builder/app/dashboard/projects/projects.tsx
+++ b/apps/builder/app/dashboard/projects/projects.tsx
@@ -1,5 +1,4 @@
import {
- Box,
Flex,
Grid,
List,
@@ -7,7 +6,10 @@ import {
Text,
rawTheme,
theme,
+ ToggleGroup,
+ ToggleGroupButton,
} from "@webstudio-is/design-system";
+import { RepeatGridIcon, ListViewIcon } from "@webstudio-is/icons";
import type { DashboardProject } from "@webstudio-is/dashboard";
import { ProjectCard } from "./project-card";
import { CreateProject } from "./project-dialogs";
@@ -16,6 +18,13 @@ import { useSearchParams } from "react-router-dom";
import { setIsSubsetOf } from "~/shared/shim";
import type { User } from "~/shared/db/user.server";
import { Tag } from "./tags";
+import {
+ SortSelect,
+ sortProjects,
+ type SortState,
+ type SortField,
+} from "./sort";
+import { ProjectsList } from "./projects-list";
export const ProjectsGrid = ({
projects,
@@ -30,6 +39,7 @@ export const ProjectsGrid = ({
css={{
gridTemplateColumns: `repeat(auto-fill, minmax(${rawTheme.spacing[31]}, 1fr))`,
paddingBottom: theme.spacing[13],
+ width: "100%",
}}
>
{projects.map((project) => {
@@ -57,14 +67,55 @@ type ProjectsProps = {
};
export const Projects = (props: ProjectsProps) => {
- const [searchParams] = useSearchParams();
+ const [searchParams, setSearchParams] = useSearchParams();
const selectedTags = searchParams.getAll("tag");
+ const viewMode = (searchParams.get("view") as "grid" | "list") ?? "grid";
+
+ const sortState: SortState = {
+ sortBy: searchParams.get("sortBy") as SortState["sortBy"],
+ order: searchParams.get("order") as SortState["order"],
+ };
+
+ const handleSortChange = (newSortState: Required<SortState>) => {
+ const newParams = new URLSearchParams(searchParams);
+ newParams.set("sortBy", newSortState.sortBy);
+ newParams.set("order", newSortState.order);
+ setSearchParams(newParams);
+ };
+
+ const handleTableSort = (field: SortField) => {
+ const currentSortBy = sortState.sortBy ?? "updatedAt";
+ const currentOrder = sortState.order ?? "desc";
+
+ // If clicking the same field, toggle the order
+ if (field === currentSortBy) {
+ const newOrder = currentOrder === "asc" ? "desc" : "asc";
+ handleSortChange({ sortBy: field, order: newOrder });
+ } else {
+ // When switching to a new field, use smart defaults
+ const newOrder = field === "title" ? "asc" : "desc";
+ handleSortChange({ sortBy: field, order: newOrder });
+ }
+ };
+
+ const handleViewChange = (value: string) => {
+ const newParams = new URLSearchParams(searchParams);
+ if (value === "grid") {
+ newParams.delete("view");
+ } else {
+ newParams.set("view", value);
+ }
+ setSearchParams(newParams);
+ };
+
+ // Filter by tags
let projects = props.projects;
if (selectedTags.length > 0) {
projects = projects.filter((project) =>
setIsSubsetOf(new Set(selectedTags), new Set(project.tags))
);
}
+ projects = sortProjects(projects, sortState);
return (
<Main>
@@ -73,47 +124,71 @@ export const Projects = (props: ProjectsProps) => {
Projects
</Text>
<Flex gap="2">
+ <ToggleGroup
+ type="single"
+ value={viewMode}
+ onValueChange={handleViewChange}
+ >
+ <ToggleGroupButton value="grid" aria-label="Grid view">
+ <RepeatGridIcon />
+ </ToggleGroupButton>
+ <ToggleGroupButton value="list" aria-label="List view">
+ <ListViewIcon />
+ </ToggleGroupButton>
+ </ToggleGroup>
+ <SortSelect value={sortState} onValueChange={handleSortChange} />
<CreateProject />
</Flex>
</Header>
<Flex
gap="2"
- wrap="wrap"
+ shrink={false}
+ justify="between"
css={{
- display: "none",
- flexShrink: 0,
paddingInline: theme.spacing[13],
paddingBlockStart: theme.spacing[2],
paddingBlockEnd: theme.spacing[10],
- "&:has(*:first-child)": {
- display: "flex",
- },
}}
>
- {props.projectsTags.map((tag, index) => {
- return (
- <Tag
- tag={tag}
- key={tag.id}
- index={index}
- state={selectedTags.includes(tag.id) ? "pressed" : "auto"}
- >
- {tag.label}
- </Tag>
- );
- })}
+ <Flex gap="2" wrap="wrap" align="center">
+ {props.projectsTags.map((tag, index) => {
+ return (
+ <Tag
+ tag={tag}
+ key={tag.id}
+ index={index}
+ state={selectedTags.includes(tag.id) ? "pressed" : "auto"}
+ >
+ {tag.label}
+ </Tag>
+ );
+ })}
+ </Flex>
</Flex>
- <Box css={{ paddingInline: theme.spacing[13] }}>
- {projects.length === 0 && (
+ <Flex css={{ paddingInline: theme.spacing[13] }}>
+ {projects.length === 0 ? (
<Text
variant="brandRegular"
- css={{ padding: theme.spacing[13], textAlign: "center" }}
+ css={{
+ paddingBlock: theme.spacing[20],
+ textAlign: "center",
+ flexGrow: 1,
+ }}
>
No projects found
</Text>
+ ) : viewMode === "grid" ? (
+ <ProjectsGrid {...props} projects={projects} />
+ ) : (
+ <ProjectsList
+ {...props}
+ projects={projects}
+ sortBy={sortState.sortBy}
+ sortOrder={sortState.order}
+ onSortChange={handleTableSort}
+ />
)}
- <ProjectsGrid {...props} projects={projects} />
- </Box>
+ </Flex>
</Main>
);
};
diff --git a/apps/builder/app/dashboard/projects/sort.test.ts b/apps/builder/app/dashboard/projects/sort.test.ts
new file mode 100644
index 0000000000..c4766aea42
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/sort.test.ts
@@ -0,0 +1,677 @@
+/**
+ * Tests for the sortProjects function and sort order semantics.
+ *
+ * This test suite covers:
+ * 1. All sort fields (title, createdAt, updatedAt, publishedAt)
+ * 2. Both sort orders (asc, desc)
+ * 3. Special cases (unpublished projects, fallback to createdAt)
+ * 4. Immutability guarantees
+ * 5. Edge cases (empty arrays, single items, identical values)
+ * 6. Order semantics:
+ * - Alphabetical: asc = A→Z, desc = Z→A
+ * - Dates: asc = Oldest first, desc = Newest first
+ */
+
+import { describe, test, expect } from "vitest";
+import { sortProjects } from "./sort";
+import type { DashboardProject } from "@webstudio-is/dashboard";
+
+type LatestBuildVirtual = NonNullable<DashboardProject["latestBuildVirtual"]>;
+
+const createMockProject = (
+ overrides: Partial<DashboardProject>
+): DashboardProject => {
+ return {
+ id: "project-1",
+ title: "Test Project",
+ domain: "test",
+ isDeleted: false,
+ createdAt: "2024-01-01T00:00:00.000Z",
+ marketplaceApprovalStatus: "UNLISTED",
+ latestBuildVirtual: null,
+ previewImageAsset: null,
+ tags: [],
+ isPublished: false,
+ ...overrides,
+ } as DashboardProject;
+};
+
+describe("sortProjects", () => {
+ describe("sort by title", () => {
+ test("sorts alphabetically in ascending order", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "Zebra" }),
+ createMockProject({ id: "2", title: "Apple" }),
+ createMockProject({ id: "3", title: "Mango" }),
+ ];
+
+ const sorted = sortProjects(projects, { sortBy: "title", order: "asc" });
+
+ expect(sorted.map((p) => p.title)).toEqual(["Apple", "Mango", "Zebra"]);
+ });
+
+ test("sorts alphabetically in descending order", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "Apple" }),
+ createMockProject({ id: "2", title: "Zebra" }),
+ createMockProject({ id: "3", title: "Mango" }),
+ ];
+
+ const sorted = sortProjects(projects, { sortBy: "title", order: "desc" });
+
+ expect(sorted.map((p) => p.title)).toEqual(["Zebra", "Mango", "Apple"]);
+ });
+
+ test("handles case-insensitive sorting", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "zebra" }),
+ createMockProject({ id: "2", title: "Apple" }),
+ createMockProject({ id: "3", title: "MANGO" }),
+ ];
+
+ const sorted = sortProjects(projects, { sortBy: "title", order: "asc" });
+
+ expect(sorted.map((p) => p.title)).toEqual(["Apple", "MANGO", "zebra"]);
+ });
+ });
+
+ describe("sort by createdAt", () => {
+ test("sorts by creation date in ascending order (oldest first)", () => {
+ const projects = [
+ createMockProject({ id: "1", createdAt: "2024-03-01T00:00:00.000Z" }),
+ createMockProject({ id: "2", createdAt: "2024-01-01T00:00:00.000Z" }),
+ createMockProject({ id: "3", createdAt: "2024-02-01T00:00:00.000Z" }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "createdAt",
+ order: "asc",
+ });
+
+ expect(sorted.map((p) => p.id)).toEqual(["2", "3", "1"]);
+ });
+
+ test("sorts by creation date in descending order (newest first)", () => {
+ const projects = [
+ createMockProject({ id: "1", createdAt: "2024-01-01T00:00:00.000Z" }),
+ createMockProject({ id: "2", createdAt: "2024-03-01T00:00:00.000Z" }),
+ createMockProject({ id: "3", createdAt: "2024-02-01T00:00:00.000Z" }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "createdAt",
+ order: "desc",
+ });
+
+ expect(sorted.map((p) => p.id)).toEqual(["2", "3", "1"]);
+ });
+ });
+
+ describe("sort by updatedAt (last modified)", () => {
+ test("sorts by latest build updatedAt when available", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ buildId: "build1",
+ projectId: "1",
+ domainsVirtualId: "",
+ domain: "test",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-03-01T00:00:00.000Z",
+ publishStatus: "PUBLISHED",
+ },
+ }),
+ createMockProject({
+ id: "2",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ buildId: "build2",
+ projectId: "2",
+ domainsVirtualId: "",
+ domain: "test",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-01-15T00:00:00.000Z",
+ publishStatus: "PUBLISHED",
+ },
+ }),
+ createMockProject({
+ id: "3",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ buildId: "build3",
+ projectId: "3",
+ domainsVirtualId: "",
+ domain: "test",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-02-01T00:00:00.000Z",
+ publishStatus: "PUBLISHED",
+ },
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "updatedAt",
+ order: "desc",
+ });
+
+ expect(sorted.map((p) => p.id)).toEqual(["1", "3", "2"]);
+ });
+
+ test("falls back to createdAt when latestBuildVirtual is null", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ createdAt: "2024-03-01T00:00:00.000Z",
+ latestBuildVirtual: null,
+ }),
+ createMockProject({
+ id: "2",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ buildId: "build2",
+ projectId: "2",
+ domainsVirtualId: "",
+ domain: "test",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-02-01T00:00:00.000Z",
+ publishStatus: "PUBLISHED",
+ },
+ }),
+ createMockProject({
+ id: "3",
+ createdAt: "2024-02-01T00:00:00.000Z",
+ latestBuildVirtual: null,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "updatedAt",
+ order: "desc",
+ });
+
+ // Project 1: March 1 (createdAt fallback)
+ // Project 2: Feb 1 (latestBuildVirtual.updatedAt)
+ // Project 3: Feb 1 (createdAt fallback)
+ expect(sorted.map((p) => p.id)).toEqual(["1", "2", "3"]);
+ });
+
+ test("sorts in ascending order (oldest first)", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ buildId: "build1",
+ projectId: "1",
+ domainsVirtualId: "",
+ domain: "test",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-03-01T00:00:00.000Z",
+ publishStatus: "PUBLISHED",
+ },
+ }),
+ createMockProject({
+ id: "2",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ buildId: "build2",
+ projectId: "2",
+ domainsVirtualId: "",
+ domain: "test",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-01-15T00:00:00.000Z",
+ publishStatus: "PUBLISHED",
+ },
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "updatedAt",
+ order: "asc",
+ });
+
+ expect(sorted.map((p) => p.id)).toEqual(["2", "1"]);
+ });
+ });
+
+ describe("sort by publishedAt (date published)", () => {
+ test("sorts published projects by publish date", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-03-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "3",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-02-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "publishedAt",
+ order: "desc",
+ });
+
+ expect(sorted.map((p) => p.id)).toEqual(["1", "3", "2"]);
+ });
+
+ test("puts unpublished projects at the end in descending order", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-02-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ isPublished: false,
+ latestBuildVirtual: null,
+ }),
+ createMockProject({
+ id: "3",
+ isPublished: false,
+ latestBuildVirtual: {
+ publishStatus: "PENDING",
+ createdAt: "2024-03-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "4",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "publishedAt",
+ order: "desc",
+ });
+
+ // Unpublished projects (isPublished: false) come at the end
+ // Published projects sorted by date descending
+ expect(sorted.map((p) => p.id)).toEqual(["1", "4", "2", "3"]);
+ });
+
+ test("puts unpublished projects at the end in ascending order", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-02-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ isPublished: false,
+ latestBuildVirtual: null,
+ }),
+ createMockProject({
+ id: "3",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "publishedAt",
+ order: "asc",
+ });
+
+ // Published projects first (sorted by date ascending), then unpublished
+ expect(sorted.map((p) => p.id)).toEqual(["3", "1", "2"]);
+ });
+
+ test("maintains order for multiple unpublished projects", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ isPublished: false,
+ latestBuildVirtual: null,
+ }),
+ createMockProject({
+ id: "2",
+ isPublished: false,
+ latestBuildVirtual: {
+ publishStatus: "PENDING",
+ } as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "3",
+ isPublished: false,
+ latestBuildVirtual: null,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "publishedAt",
+ order: "desc",
+ });
+
+ expect(sorted.map((p) => p.id)).toEqual(["1", "2", "3"]);
+ });
+ });
+
+ describe("immutability", () => {
+ test("does not mutate the original array", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "B" }),
+ createMockProject({ id: "2", title: "A" }),
+ ];
+
+ const originalOrder = projects.map((p) => p.id);
+ sortProjects(projects, { sortBy: "title", order: "asc" });
+
+ expect(projects.map((p) => p.id)).toEqual(originalOrder);
+ });
+
+ test("returns a new array", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "A" }),
+ createMockProject({ id: "2", title: "B" }),
+ ];
+
+ const sorted = sortProjects(projects, { sortBy: "title", order: "asc" });
+
+ expect(sorted).not.toBe(projects);
+ });
+ });
+
+ describe("edge cases", () => {
+ test("handles empty array", () => {
+ const sorted = sortProjects([], { sortBy: "title", order: "asc" });
+ expect(sorted).toEqual([]);
+ });
+
+ test("handles single project", () => {
+ const projects = [createMockProject({ id: "1", title: "Only" })];
+ const sorted = sortProjects(projects, { sortBy: "title", order: "asc" });
+ expect(sorted).toHaveLength(1);
+ expect(sorted[0].id).toBe("1");
+ });
+
+ test("handles projects with identical values", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ title: "Same",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ }),
+ createMockProject({
+ id: "2",
+ title: "Same",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ }),
+ createMockProject({
+ id: "3",
+ title: "Same",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ }),
+ ];
+
+ const sorted = sortProjects(projects, { sortBy: "title", order: "asc" });
+ expect(sorted).toHaveLength(3);
+ });
+ });
+
+ describe("default sort options", () => {
+ test("defaults to updatedAt desc when no sort state provided", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-01-15T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-03-01T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "3",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-02-01T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects);
+
+ // Default: updatedAt desc (newest first)
+ expect(sorted.map((p) => p.id)).toEqual(["2", "3", "1"]);
+ });
+
+ test("defaults to updatedAt when only order is provided", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-01-15T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-03-01T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, { order: "asc" });
+
+ // updatedAt asc (oldest first)
+ expect(sorted.map((p) => p.id)).toEqual(["1", "2"]);
+ });
+
+ test("defaults to desc order when only sortBy is provided", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "Apple" }),
+ createMockProject({ id: "2", title: "Zebra" }),
+ createMockProject({ id: "3", title: "Mango" }),
+ ];
+
+ const sorted = sortProjects(projects, { sortBy: "title" });
+
+ // title desc (Z→A)
+ expect(sorted.map((p) => p.title)).toEqual(["Zebra", "Mango", "Apple"]);
+ });
+
+ test("uses provided sortBy and order when both are specified", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "Zebra" }),
+ createMockProject({ id: "2", title: "Apple" }),
+ createMockProject({ id: "3", title: "Mango" }),
+ ];
+
+ const sorted = sortProjects(projects, { sortBy: "title", order: "asc" });
+
+ // title asc (A→Z)
+ expect(sorted.map((p) => p.title)).toEqual(["Apple", "Mango", "Zebra"]);
+ });
+
+ test("handles empty sort state object", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-01-15T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-03-01T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {});
+
+ // Default: updatedAt desc
+ expect(sorted.map((p) => p.id)).toEqual(["2", "1"]);
+ });
+ });
+
+ describe("order semantics", () => {
+ describe("alphabetical sorting", () => {
+ test("asc order produces A→Z sorting", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "Zebra" }),
+ createMockProject({ id: "2", title: "Apple" }),
+ createMockProject({ id: "3", title: "Mango" }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "title",
+ order: "asc",
+ });
+
+ // A→Z: Apple, Mango, Zebra
+ expect(sorted.map((p) => p.title)).toEqual(["Apple", "Mango", "Zebra"]);
+ });
+
+ test("desc order produces Z→A sorting", () => {
+ const projects = [
+ createMockProject({ id: "1", title: "Apple" }),
+ createMockProject({ id: "2", title: "Zebra" }),
+ createMockProject({ id: "3", title: "Mango" }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "title",
+ order: "desc",
+ });
+
+ // Z→A: Zebra, Mango, Apple
+ expect(sorted.map((p) => p.title)).toEqual(["Zebra", "Mango", "Apple"]);
+ });
+ });
+
+ describe("date sorting", () => {
+ test("desc order produces newest first for createdAt", () => {
+ const projects = [
+ createMockProject({ id: "1", createdAt: "2024-01-01T00:00:00.000Z" }),
+ createMockProject({ id: "2", createdAt: "2024-03-01T00:00:00.000Z" }),
+ createMockProject({ id: "3", createdAt: "2024-02-01T00:00:00.000Z" }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "createdAt",
+ order: "desc",
+ });
+
+ // Newest first: March, February, January
+ expect(sorted.map((p) => p.id)).toEqual(["2", "3", "1"]);
+ });
+
+ test("asc order produces oldest first for createdAt", () => {
+ const projects = [
+ createMockProject({ id: "1", createdAt: "2024-03-01T00:00:00.000Z" }),
+ createMockProject({ id: "2", createdAt: "2024-01-01T00:00:00.000Z" }),
+ createMockProject({ id: "3", createdAt: "2024-02-01T00:00:00.000Z" }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "createdAt",
+ order: "asc",
+ });
+
+ // Oldest first: January, February, March
+ expect(sorted.map((p) => p.id)).toEqual(["2", "3", "1"]);
+ });
+
+ test("desc order produces newest first for updatedAt", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-01-15T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ latestBuildVirtual: {
+ updatedAt: "2024-03-01T00:00:00.000Z",
+ } as unknown as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "updatedAt",
+ order: "desc",
+ });
+
+ // Newest first: March update, January update
+ expect(sorted.map((p) => p.id)).toEqual(["2", "1"]);
+ });
+
+ test("desc order produces newest first for publishedAt", () => {
+ const projects = [
+ createMockProject({
+ id: "1",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ createMockProject({
+ id: "2",
+ isPublished: true,
+ latestBuildVirtual: {
+ publishStatus: "PUBLISHED",
+ createdAt: "2024-03-01T00:00:00.000Z",
+ } as LatestBuildVirtual,
+ }),
+ ];
+
+ const sorted = sortProjects(projects, {
+ sortBy: "publishedAt",
+ order: "desc",
+ });
+
+ // Newest first: March publish, January publish
+ expect(sorted.map((p) => p.id)).toEqual(["2", "1"]);
+ });
+ });
+ });
+});
diff --git a/apps/builder/app/dashboard/projects/sort.tsx b/apps/builder/app/dashboard/projects/sort.tsx
new file mode 100644
index 0000000000..439c67b678
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/sort.tsx
@@ -0,0 +1,185 @@
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuLabel,
+ Button,
+ MenuCheckedIcon,
+} from "@webstudio-is/design-system";
+import {
+ ChevronDownIcon,
+ CalendarIcon,
+ UploadIcon,
+ ArrowDownAZIcon,
+} from "@webstudio-is/icons";
+import type { DashboardProject } from "@webstudio-is/dashboard";
+
+export type SortField = "createdAt" | "title" | "updatedAt" | "publishedAt";
+export type SortOrder = "asc" | "desc";
+
+export type SortState = {
+ sortBy?: SortField;
+ order?: SortOrder;
+};
+
+export const sortProjects = (
+ projects: Array<DashboardProject>,
+ sortState: SortState = {}
+) => {
+ const sortBy = sortState.sortBy ?? "updatedAt";
+ const order = sortState.order ?? "desc";
+
+ const sorted = [...projects];
+
+ sorted.sort((a, b) => {
+ let comparison = 0;
+
+ if (sortBy === "title") {
+ const aTitle = a.title ?? "";
+ const bTitle = b.title ?? "";
+ comparison = aTitle.localeCompare(bTitle);
+ } else if (sortBy === "createdAt") {
+ const aCreated = a.createdAt ?? "";
+ const bCreated = b.createdAt ?? "";
+ comparison = new Date(aCreated).getTime() - new Date(bCreated).getTime();
+ } else if (sortBy === "updatedAt") {
+ // Uses Build's updatedAt field from latestBuildVirtual view, falls back to project createdAt
+ const aUpdated = a.latestBuildVirtual?.updatedAt || a.createdAt || "";
+ const bUpdated = b.latestBuildVirtual?.updatedAt || b.createdAt || "";
+ comparison = new Date(aUpdated).getTime() - new Date(bUpdated).getTime();
+ } else if (sortBy === "publishedAt") {
+ // Sort by published date, putting unpublished projects at the end
+ const aPublished = a.isPublished
+ ? a.latestBuildVirtual?.createdAt
+ : undefined;
+ const bPublished = b.isPublished
+ ? b.latestBuildVirtual?.createdAt
+ : undefined;
+
+ // If both are published, compare dates normally (will be reversed by order)
+ if (aPublished && bPublished) {
+ comparison =
+ new Date(aPublished).getTime() - new Date(bPublished).getTime();
+ } else if (aPublished && !bPublished) {
+ // Published should always come before unpublished, regardless of order
+ // In asc: -1 means a before b (correct)
+ // In desc: we return -(-1) = 1, meaning a after b (wrong!)
+ // So we need to account for the order reversal
+ comparison = order === "asc" ? -1 : 1;
+ } else if (!aPublished && bPublished) {
+ // Unpublished should always come after published, regardless of order
+ comparison = order === "asc" ? 1 : -1;
+ } else {
+ comparison = 0; // both unpublished, maintain order
+ }
+ }
+
+ return order === "asc" ? comparison : -comparison;
+ });
+
+ return sorted;
+};
+
+type SortSelectProps = {
+ value: SortState;
+ onValueChange: (value: Required<SortState>) => void;
+};
+
+export const SortSelect = ({ value, onValueChange }: SortSelectProps) => {
+ const sortBy = value.sortBy ?? "updatedAt";
+ const order = value.order ?? "desc";
+
+ const sortLabel =
+ sortBy === "createdAt"
+ ? "Date created"
+ : sortBy === "title"
+ ? "Alphabetical"
+ : sortBy === "publishedAt"
+ ? "Date published"
+ : "Last modified";
+
+ const sortIcon =
+ sortBy === "createdAt" ? (
+ <CalendarIcon />
+ ) : sortBy === "title" ? (
+ <ArrowDownAZIcon />
+ ) : sortBy === "publishedAt" ? (
+ <UploadIcon />
+ ) : (
+ <CalendarIcon />
+ );
+
+ const handleSortChange = (newSortBy: SortField, newOrder: SortOrder) => {
+ // When switching to alphabetical sorting, default to A→Z (asc)
+ // When switching to date sorting, default to newest first (desc)
+ if (newSortBy !== sortBy) {
+ onValueChange({
+ sortBy: newSortBy,
+ order: newSortBy === "title" ? "asc" : "desc",
+ });
+ } else {
+ onValueChange({ sortBy: newSortBy, order: newOrder });
+ }
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button color="ghost" prefix={sortIcon} suffix={<ChevronDownIcon />}>
+ {sortLabel}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Sort</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={sortBy}
+ onValueChange={(value) => handleSortChange(value as SortField, order)}
+ >
+ <DropdownMenuRadioItem value="title" icon={<MenuCheckedIcon />}>
+ Alphabetical
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="createdAt" icon={<MenuCheckedIcon />}>
+ Date created
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="updatedAt" icon={<MenuCheckedIcon />}>
+ Last modified
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="publishedAt" icon={<MenuCheckedIcon />}>
+ Date published
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>Order</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={order}
+ onValueChange={(value) =>
+ handleSortChange(sortBy, value as SortOrder)
+ }
+ >
+ {sortBy === "title" ? (
+ <>
+ <DropdownMenuRadioItem value="asc" icon={<MenuCheckedIcon />}>
+ A→Z
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="desc" icon={<MenuCheckedIcon />}>
+ Z→A
+ </DropdownMenuRadioItem>
+ </>
+ ) : (
+ <>
+ <DropdownMenuRadioItem value="desc" icon={<MenuCheckedIcon />}>
+ Newest first
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="asc" icon={<MenuCheckedIcon />}>
+ Oldest first
+ </DropdownMenuRadioItem>
+ </>
+ )}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/apps/builder/app/dashboard/projects/utils.ts b/apps/builder/app/dashboard/projects/utils.ts
new file mode 100644
index 0000000000..ebbed9aa69
--- /dev/null
+++ b/apps/builder/app/dashboard/projects/utils.ts
@@ -0,0 +1,7 @@
+export const formatDate = (date: string) => {
+ return new Date(date).toLocaleDateString("en-US", {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
+};
diff --git a/packages/dashboard/src/db/projects.ts b/packages/dashboard/src/db/projects.ts
index 81ec1a6fff..6119b270db 100644
--- a/packages/dashboard/src/db/projects.ts
+++ b/packages/dashboard/src/db/projects.ts
@@ -1,4 +1,3 @@
-import type { SetNonNullable } from "type-fest";
import {
AuthorizationError,
type AppContext,
@@ -12,30 +11,19 @@ type DomainVirtual = {
const fetchAndMapDomains = async <
T extends {
- id: string | null;
- title: string | null;
- domain: string | null;
- isDeleted: boolean | null;
- createdAt: string | null;
- marketplaceApprovalStatus: string | null;
+ id: string;
+ title: string;
+ domain: string;
+ createdAt: string;
+ [key: string]: unknown;
},
>(
projects: T[],
context: AppContext
) => {
- const projectIds = projects
- .map((project) => project.id)
- .filter((id): id is string => id !== null);
+ const projectIds = projects.map((project) => project.id);
- type ProjectWithDomains = SetNonNullable<
- T,
- | "id"
- | "title"
- | "domain"
- | "isDeleted"
- | "createdAt"
- | "marketplaceApprovalStatus"
- > & {
+ type ProjectWithDomains = T & {
domainsVirtual: DomainVirtual[];
};
@@ -112,7 +100,18 @@ export const findMany = async (userId: string, context: AppContext) => {
throw data.error;
}
- return await fetchAndMapDomains(data.data, context);
+ // Type assertion: These fields are never null in practice (come from Project table which has them as required)
+ return await fetchAndMapDomains(
+ data.data as Array<
+ (typeof data.data)[number] & {
+ id: string;
+ title: string;
+ domain: string;
+ createdAt: string;
+ }
+ >,
+ context
+ );
};
export const findManyByIds = async (
@@ -133,5 +132,16 @@ export const findManyByIds = async (
throw data.error;
}
- return await fetchAndMapDomains(data.data, context);
+ // Type assertion: These fields are never null in practice (come from Project table which has them as required)
+ return await fetchAndMapDomains(
+ data.data as Array<
+ (typeof data.data)[number] & {
+ id: string;
+ title: string;
+ domain: string;
+ createdAt: string;
+ }
+ >,
+ context
+ );
};
diff --git a/packages/design-system/src/components/link.tsx b/packages/design-system/src/components/link.tsx
index 7178bb7bb1..ca1b389ce8 100644
--- a/packages/design-system/src/components/link.tsx
+++ b/packages/design-system/src/components/link.tsx
@@ -21,6 +21,9 @@ export const Link = styled("a", {
color: theme.colors.foregroundDisabled,
},
},
+ "&:focus-visible": {
+ outline: `1px solid ${theme.colors.borderFocus}`,
+ },
variants: {
variant: {
inherit: {
@@ -74,6 +77,15 @@ export const Link = styled("a", {
"&:hover": { textDecoration: "underline" },
},
},
+ stretched: {
+ true: {
+ "&::after": {
+ content: '""',
+ position: "absolute",
+ inset: 0,
+ },
+ },
+ },
},
defaultVariants: {
variant: "regular",
diff --git a/packages/icons/icons/arrow-down-a-z.svg b/packages/icons/icons/arrow-down-a-z.svg
new file mode 100644
index 0000000000..7c79dc4810
--- /dev/null
+++ b/packages/icons/icons/arrow-down-a-z.svg
@@ -0,0 +1,43 @@
+<svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+>
+ <path
+ d="M2 10.6667L4.66667 13.3333L7.33333 10.6667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M4.66669 13.3333V2.66667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M13.3333 5.33333H10"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M10 6.66667V4.33334C10 3.89131 10.1756 3.46739 10.4882 3.15483C10.8007 2.84227 11.2246 2.66667 11.6667 2.66667C12.1087 2.66667 12.5326 2.84227 12.8452 3.15483C13.1577 3.46739 13.3333 3.89131 13.3333 4.33334V6.66667"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ <path
+ d="M10 9.33333H13.3333L10 13.3333H13.3333"
+ stroke="black"
+ stroke-width="0.666667"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+</svg>
diff --git a/packages/icons/src/__generated__/components.tsx b/packages/icons/src/__generated__/components.tsx
index 7ab0e8eb57..16b7a8b582 100644
--- a/packages/icons/src/__generated__/components.tsx
+++ b/packages/icons/src/__generated__/components.tsx
@@ -770,6 +770,31 @@ export const AnimationGroupIcon: IconComponent = forwardRef(
);
AnimationGroupIcon.displayName = "AnimationGroupIcon";
+export const ArrowDownAZIcon: IconComponent = forwardRef(
+ ({ fill = "none", size = 16, ...props }, forwardedRef) => {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 16 16"
+ width={size}
+ height={size}
+ fill={fill}
+ {...props}
+ ref={forwardedRef}
+ >
+ <path
+ stroke="#000"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth=".667"
+ d="m2 10.667 2.667 2.666 2.666-2.666M4.667 13.333V2.667M13.333 5.333H10M10 6.667V4.333a1.667 1.667 0 1 1 3.333 0v2.334M10 9.333h3.333l-3.333 4h3.333"
+ />
+ </svg>
+ );
+ }
+);
+ArrowDownAZIcon.displayName = "ArrowDownAZIcon";
+
export const ArrowDownIcon: IconComponent = forwardRef(
({ fill = "none", size = 16, ...props }, forwardedRef) => {
return (
diff --git a/packages/icons/src/__generated__/svg.ts b/packages/icons/src/__generated__/svg.ts
index a9ca5bd3aa..fad5063e6d 100644
--- a/packages/icons/src/__generated__/svg.ts
+++ b/packages/icons/src/__generated__/svg.ts
@@ -52,6 +52,8 @@ export const AlignStartHorizontalIcon = `<svg xmlns="http://www.w3.org/2000/svg"
export const AnimationGroupIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M4.5 8.3C6.3 7.7 7.8 8 9.3 11c.3-1.8 1.2-4.5 2.1-6M4.208 1.5H2.944A1.444 1.444 0 0 0 1.5 2.944v1.264m13 0V2.944A1.444 1.444 0 0 0 13.056 1.5h-1.264M14.5 13.056c0 .023 0 .046-.002.069M11.792 14.5h1.264a1.444 1.444 0 0 0 1.442-1.375m0 0v-1.333m-12.998 0v1.264A1.444 1.444 0 0 0 2.944 14.5h1.264m2.709-13h2.166m-2.166 13h2.166M1.5 6.917v2.166m13-2.166v2.166"/></svg>`;
+export const ArrowDownAZIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width=".667" d="m2 10.667 2.667 2.666 2.666-2.666M4.667 13.333V2.667M13.333 5.333H10M10 6.667V4.333a1.667 1.667 0 1 1 3.333 0v2.334M10 9.333h3.333l-3.333 4h3.333"/></svg>`;
+
export const ArrowDownIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M8 3.333v9.334M12.667 8 8 12.667 3.333 8"/></svg>`;
export const ArrowLeftIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12.667 8H3.333M8 3.333 3.333 8 8 12.667"/></svg>`;
diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.ts
index 2db3243fc9..7ca5c865ab 100644
--- a/packages/postgrest/src/__generated__/db-types.ts
+++ b/packages/postgrest/src/__generated__/db-types.ts
@@ -416,6 +416,7 @@ export type Database = {
domainsVirtualId: string;
projectId: string;
publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ updatedAt: string;
};
Insert: {
buildId: string;
@@ -424,6 +425,7 @@ export type Database = {
domainsVirtualId: string;
projectId: string;
publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ updatedAt: string;
};
Update: {
buildId?: string;
@@ -432,6 +434,7 @@ export type Database = {
domainsVirtualId?: string;
projectId?: string;
publishStatus?: Database["public"]["Enums"]["PublishStatus"];
+ updatedAt?: string;
};
Relationships: [
{
@@ -948,7 +951,7 @@ export type Database = {
};
latestBuildVirtual:
| {
- Args: { "": Database["public"]["Tables"]["Project"]["Row"] };
+ Args: { "": Database["public"]["Tables"]["domainsVirtual"]["Row"] };
Returns: {
buildId: string;
createdAt: string;
@@ -956,16 +959,17 @@ export type Database = {
domainsVirtualId: string;
projectId: string;
publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ updatedAt: string;
};
SetofOptions: {
- from: '"Project"';
+ from: '"domainsVirtual"';
to: "latestBuildVirtual";
isOneToOne: true;
isSetofReturn: true;
};
}
| {
- Args: { "": Database["public"]["Tables"]["domainsVirtual"]["Row"] };
+ Args: { "": Database["public"]["Tables"]["Project"]["Row"] };
Returns: {
buildId: string;
createdAt: string;
@@ -973,9 +977,10 @@ export type Database = {
domainsVirtualId: string;
projectId: string;
publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ updatedAt: string;
};
SetofOptions: {
- from: '"domainsVirtual"';
+ from: '"Project"';
to: "latestBuildVirtual";
isOneToOne: true;
isSetofReturn: true;
@@ -990,6 +995,7 @@ export type Database = {
domainsVirtualId: string;
projectId: string;
publishStatus: Database["public"]["Enums"]["PublishStatus"];
+ updatedAt: string;
};
SetofOptions: {
from: '"Project"';
diff --git a/packages/postgrest/supabase/tests/latest-builds-domains.sql b/packages/postgrest/supabase/tests/latest-builds-domains.sql
index afcb3a5842..69782d0349 100644
--- a/packages/postgrest/supabase/tests/latest-builds-domains.sql
+++ b/packages/postgrest/supabase/tests/latest-builds-domains.sql
@@ -1,273 +1,516 @@
BEGIN;
-SET LOCAL search_path = pgtap, public;
--- SET LOCAL search_path = pgtap,public;
+SET
+ LOCAL search_path = pgtap,
+ public;
+-- SET LOCAL search_path = pgtap,public;
-- Initialize the testing environment without planning any specific number of tests
-SELECT no_plan();
+SELECT
+ no_plan();
-- Insert a new user into the User table
-INSERT INTO "public"."User" ("id", "createdAt", "email", "username")
+INSERT INTO
+ "public"."User" ("id", "createdAt", "email", "username")
VALUES
- ('user1', '2023-01-01 00:00:00+00', '[email protected]', 'user1');
+ (
+ 'user1',
+ '2023-01-01 00:00:00+00',
+ 'user1'
+ );
-- Insert projects associated with the user
-INSERT INTO "public"."Project" ("id", "title", "domain", "userId", "isDeleted", "createdAt")
+INSERT INTO
+ "public"."Project" (
+ "id",
+ "title",
+ "domain",
+ "userId",
+ "isDeleted",
+ "createdAt"
+ )
VALUES
- ('project1', 'Project One', '517cce32-9af3-project1-domain1', 'user1', false, '2023-01-01 00:00:00+00'),
- ('project2', 'Project Two', '517cce32-9af3-project2-domain1', 'user1', false, '2023-01-01 00:00:00+00');
+ (
+ 'project1',
+ 'Project One',
+ '517cce32-9af3-project1-domain1',
+ 'user1',
+ false,
+ '2023-01-01 00:00:00+00'
+ ),
+ (
+ 'project2',
+ 'Project Two',
+ '517cce32-9af3-project2-domain1',
+ 'user1',
+ false,
+ '2023-01-01 00:00:00+00'
+ );
-- Insert custom domains into the Domain table
-INSERT INTO "public"."Domain" ("id", "domain", "createdAt", "status", "updatedAt")
+INSERT INTO
+ "public"."Domain" (
+ "id",
+ "domain",
+ "createdAt",
+ "status",
+ "updatedAt"
+ )
VALUES
- ('project-1-custom-domain-1', '517cce32-9af3-project-1-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),
- ('project-1-custom-domain-2', '517cce32-9af3-project-1-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00');
+ (
+ 'project-1-custom-domain-1',
+ '517cce32-9af3-project-1-custom-domain-1.com',
+ '2023-01-01 00:00:00+00',
+ 'INITIALIZING',
+ '2023-01-01 00:00:00+00'
+ ),
+ (
+ 'project-1-custom-domain-2',
+ '517cce32-9af3-project-1-custom-domain-2.com',
+ '2023-01-01 00:00:00+00',
+ 'INITIALIZING',
+ '2023-01-01 00:00:00+00'
+ );
-- Establish relationships between projects and custom domains
-INSERT INTO "public"."ProjectDomain" ("projectId", "domainId", "createdAt", "txtRecord", "cname")
+INSERT INTO
+ "public"."ProjectDomain" (
+ "projectId",
+ "domainId",
+ "createdAt",
+ "txtRecord",
+ "cname"
+ )
VALUES
- ('project1', 'project-1-custom-domain-1', '2023-01-01 00:00:00+00', 'txtRecord1', 'cname1'),
- ('project1', 'project-1-custom-domain-2', '2023-01-01 00:00:00+00', 'txtRecord2', 'cname2');
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ '2023-01-01 00:00:00+00',
+ 'txtRecord1',
+ 'cname1'
+ ),
+ (
+ 'project1',
+ 'project-1-custom-domain-2',
+ '2023-01-01 00:00:00+00',
+ 'txtRecord2',
+ 'cname2'
+ );
-- Create a view to encapsulate the repetitive SELECT query for testing
-CREATE OR REPLACE VIEW "public"."TestProjectDomains" AS
+CREATE
+OR REPLACE VIEW "public"."TestProjectDomains" AS
SELECT
pd."projectId",
pd."domainId",
lbv."buildId"
-FROM "public"."ProjectDomain" pd
-LEFT JOIN LATERAL (
- SELECT * FROM "latestBuildVirtual"(ROW('', pd."domainId", pd."projectId", '', 'INITIALIZING'::"DomainStatus", NULL, 'txt','expectedTxt','cname',TRUE, NOW(),NOW())::"domainsVirtual")
-) lbv ON TRUE
-ORDER BY pd."domainId";
+FROM
+ "public"."ProjectDomain" pd
+ LEFT JOIN LATERAL (
+ SELECT
+ *
+ FROM
+ "latestBuildVirtual"(
+ ROW(
+ '',
+ pd."domainId",
+ pd."projectId",
+ '',
+ 'INITIALIZING' :: "DomainStatus",
+ NULL,
+ 'txt',
+ 'expectedTxt',
+ 'cname',
+ TRUE,
+ NOW(),
+ NOW()
+ ) :: "domainsVirtual"
+ )
+ ) lbv ON TRUE
+ORDER BY
+ pd."domainId";
--------------------------------------------------------------------------------
-- Test Case 1: Initial State Without Builds
--------------------------------------------------------------------------------
-SELECT results_eq(
- 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
- $$
- SELECT * FROM (
- VALUES
- ('project1', 'project-1-custom-domain-1', NULL),
- ('project1', 'project-1-custom-domain-2', NULL)
- ) AS expected(projectId, domainId, buildId)
- ORDER BY domainId
- $$,
- 'Initial state without builds'
-);
+SELECT
+ results_eq(
+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
+ $ $
+ SELECT
+ *
+ FROM
+ (
+ VALUES
+ ('project1', 'project-1-custom-domain-1', NULL),
+ ('project1', 'project-1-custom-domain-2', NULL)
+ ) AS expected(projectId, domainId, buildId)
+ ORDER BY
+ domainId $ $,
+ 'Initial state without builds'
+ );
--------------------------------------------------------------------------------
-- Test Case 2: After Inserting Build1 Associated with Custom Domain 1
--------------------------------------------------------------------------------
-- Insert a build associated with a custom domain
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build1-for-custom-domain-1',
- '2023-01-02 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,
- '2023-01-02 00:00:00+00',
- 'PUBLISHED'
-);
+ (
+ 'build1-for-custom-domain-1',
+ '2023-01-02 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}' :: text,
+ '2023-01-02 00:00:00+00',
+ 'PUBLISHED'
+ );
-SELECT results_eq(
- 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
- $$
- SELECT * FROM (
- VALUES
- ('project1', 'project-1-custom-domain-1', 'build1-for-custom-domain-1'),
- ('project1', 'project-1-custom-domain-2', NULL)
- ) AS expected(projectId, domainId, buildId)
- ORDER BY domainId
- $$,
- 'After inserting build1 associated with custom domain 1'
-);
+SELECT
+ results_eq(
+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
+ $ $
+ SELECT
+ *
+ FROM
+ (
+ VALUES
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ 'build1-for-custom-domain-1'
+ ),
+ ('project1', 'project-1-custom-domain-2', NULL)
+ ) AS expected(projectId, domainId, buildId)
+ ORDER BY
+ domainId $ $,
+ 'After inserting build1 associated with custom domain 1'
+ );
--------------------------------------------------------------------------------
-- Test Case 3: After Inserting Build2 Associated with Custom Domain 1
--------------------------------------------------------------------------------
-- Insert a new build associated with the same custom domain
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build2-for-custom-domain-1',
- '2024-01-02 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,
- '2024-01-02 00:00:00+00',
- 'PUBLISHED'
-);
+ (
+ 'build2-for-custom-domain-1',
+ '2024-01-02 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}' :: text,
+ '2024-01-02 00:00:00+00',
+ 'PUBLISHED'
+ );
-SELECT results_eq(
- 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
- $$
- SELECT * FROM (
- VALUES
- ('project1', 'project-1-custom-domain-1', 'build2-for-custom-domain-1'),
- ('project1', 'project-1-custom-domain-2', NULL)
- ) AS expected(projectId, domainId, buildId)
- ORDER BY domainId
- $$,
- 'After inserting build2 associated with custom domain 1'
-);
+SELECT
+ results_eq(
+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
+ $ $
+ SELECT
+ *
+ FROM
+ (
+ VALUES
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ 'build2-for-custom-domain-1'
+ ),
+ ('project1', 'project-1-custom-domain-2', NULL)
+ ) AS expected(projectId, domainId, buildId)
+ ORDER BY
+ domainId $ $,
+ 'After inserting build2 associated with custom domain 1'
+ );
--------------------------------------------------------------------------------
-- Test Case 4: After Inserting Build3 Associated with Custom Domain 2
--------------------------------------------------------------------------------
-- Insert a new build associated with another custom domain
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build3-for-custom-domain-2',
- '2024-01-03 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com"]}'::text,
- '2024-01-03 00:00:00+00',
- 'PUBLISHED'
-);
+ (
+ 'build3-for-custom-domain-2',
+ '2024-01-03 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com"]}' :: text,
+ '2024-01-03 00:00:00+00',
+ 'PUBLISHED'
+ );
-SELECT results_eq(
- 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
- $$
- SELECT * FROM (
- VALUES
- ('project1', 'project-1-custom-domain-1', 'build2-for-custom-domain-1'),
- ('project1', 'project-1-custom-domain-2', 'build3-for-custom-domain-2')
- ) AS expected(projectId, domainId, buildId)
- ORDER BY domainId
- $$,
- 'After inserting build3 associated with custom domain 2'
-);
+SELECT
+ results_eq(
+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
+ $ $
+ SELECT
+ *
+ FROM
+ (
+ VALUES
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ 'build2-for-custom-domain-1'
+ ),
+ (
+ 'project1',
+ 'project-1-custom-domain-2',
+ 'build3-for-custom-domain-2'
+ )
+ ) AS expected(projectId, domainId, buildId)
+ ORDER BY
+ domainId $ $,
+ 'After inserting build3 associated with custom domain 2'
+ );
--------------------------------------------------------------------------------
-- Test Case 5: After Inserting Build4 Associated with Both Domains
--------------------------------------------------------------------------------
-- Insert a new build associated with both custom domains
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build4-for-both-domains',
- '2024-01-04 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,
- '2024-01-04 00:00:00+00',
- 'PUBLISHED'
-);
+ (
+ 'build4-for-both-domains',
+ '2024-01-04 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com", "517cce32-9af3-project-1-custom-domain-1.com"]}' :: text,
+ '2024-01-04 00:00:00+00',
+ 'PUBLISHED'
+ );
-SELECT results_eq(
- 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
- $$
- SELECT * FROM (
- VALUES
- ('project1', 'project-1-custom-domain-1', 'build4-for-both-domains'),
- ('project1', 'project-1-custom-domain-2', 'build4-for-both-domains')
- ) AS expected(projectId, domainId, buildId)
- ORDER BY domainId
- $$,
- 'After inserting build4 associated with both domains'
-);
+SELECT
+ results_eq(
+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
+ $ $
+ SELECT
+ *
+ FROM
+ (
+ VALUES
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ 'build4-for-both-domains'
+ ),
+ (
+ 'project1',
+ 'project-1-custom-domain-2',
+ 'build4-for-both-domains'
+ )
+ ) AS expected(projectId, domainId, buildId)
+ ORDER BY
+ domainId $ $,
+ 'After inserting build4 associated with both domains'
+ );
--------------------------------------------------------------------------------
-- Test Case 6: Insert Builds and Relationships for Project2
--------------------------------------------------------------------------------
-- Establish relationships between project2 and the same custom domains
-INSERT INTO "public"."ProjectDomain" ("projectId", "domainId", "createdAt", "txtRecord", "cname")
+INSERT INTO
+ "public"."ProjectDomain" (
+ "projectId",
+ "domainId",
+ "createdAt",
+ "txtRecord",
+ "cname"
+ )
VALUES
- ('project2', 'project-1-custom-domain-1', '2023-01-01 00:00:00+00', 'txtRecord21', 'cname21'),
- ('project2', 'project-1-custom-domain-2', '2023-01-01 00:00:00+00', 'txtRecord22', 'cname22');
+ (
+ 'project2',
+ 'project-1-custom-domain-1',
+ '2023-01-01 00:00:00+00',
+ 'txtRecord21',
+ 'cname21'
+ ),
+ (
+ 'project2',
+ 'project-1-custom-domain-2',
+ '2023-01-01 00:00:00+00',
+ 'txtRecord22',
+ 'cname22'
+ );
-- Insert a new build for project2 associated with both domains
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build5-project2-for-both-domains',
- '2025-01-04 00:00:00+00',
- 'home',
- 'project2',
- '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,
- '2025-01-04 00:00:00+00',
- 'PUBLISHED'
-);
+ (
+ 'build5-project2-for-both-domains',
+ '2025-01-04 00:00:00+00',
+ 'home',
+ 'project2',
+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com", "517cce32-9af3-project-1-custom-domain-1.com"]}' :: text,
+ '2025-01-04 00:00:00+00',
+ 'PUBLISHED'
+ );
--------------------------------------------------------------------------------
-- Test Case 7: Verify Results for Project1 Remain Unchanged After Project2 Updates
--------------------------------------------------------------------------------
-SELECT results_eq(
- 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
- $$
- SELECT * FROM (
- VALUES
- ('project1', 'project-1-custom-domain-1', 'build4-for-both-domains'),
- ('project1', 'project-1-custom-domain-2', 'build4-for-both-domains')
- ) AS expected(projectId, domainId, buildId)
- ORDER BY domainId
- $$,
- 'Verify Project1 results remain unchanged after Project2 updates'
-);
+SELECT
+ results_eq(
+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',
+ $ $
+ SELECT
+ *
+ FROM
+ (
+ VALUES
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ 'build4-for-both-domains'
+ ),
+ (
+ 'project1',
+ 'project-1-custom-domain-2',
+ 'build4-for-both-domains'
+ )
+ ) AS expected(projectId, domainId, buildId)
+ ORDER BY
+ domainId $ $,
+ 'Verify Project1 results remain unchanged after Project2 updates'
+ );
--------------------------------------------------------------------------------
-- Test Case 8: Verify Results for Project2 Reflect Latest Build
--------------------------------------------------------------------------------
-SELECT results_eq(
- $$SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = 'project2'$$,
- $$
- SELECT * FROM (
- VALUES
- ('project2', 'project-1-custom-domain-1', 'build5-project2-for-both-domains'),
- ('project2', 'project-1-custom-domain-2', 'build5-project2-for-both-domains')
- ) AS expected(projectId, domainId, buildId)
- ORDER BY domainId
- $$,
- 'Verify Project2 results reflect the latest build'
-);
+SELECT
+ results_eq(
+ $ $
+ SELECT
+ *
+ FROM
+ "public"."TestProjectDomains"
+ WHERE
+ "projectId" = 'project2' $ $,
+ $ $
+ SELECT
+ *
+ FROM
+ (
+ VALUES
+ (
+ 'project2',
+ 'project-1-custom-domain-1',
+ 'build5-project2-for-both-domains'
+ ),
+ (
+ 'project2',
+ 'project-1-custom-domain-2',
+ 'build5-project2-for-both-domains'
+ )
+ ) AS expected(projectId, domainId, buildId)
+ ORDER BY
+ domainId $ $,
+ 'Verify Project2 results reflect the latest build'
+ );
+
+--------------------------------------------------------------------------------
+-- Test Case 9: Verify updatedAt Field for domainsVirtual Function
+--------------------------------------------------------------------------------
+-- Insert a build with specific updatedAt value for project1 custom domain 1
+-- This build should be selected as latest because it has the newest createdAt
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
+VALUES
+ (
+ 'build-with-updatedAt-test',
+ '2025-01-10 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["517cce32-9af3-project-1-custom-domain-1.com"]}' :: text,
+ '2024-06-15 12:30:00+00',
+ 'PUBLISHED'
+ );
+
+-- Verify updatedAt is returned correctly from the latest build
+SELECT
+ is (
+ (
+ SELECT
+ "updatedAt"
+ FROM
+ "public"."latestBuildVirtual"(
+ ROW(
+ '',
+ 'project-1-custom-domain-1',
+ 'project1',
+ '',
+ 'INITIALIZING' :: "DomainStatus",
+ NULL,
+ 'txt',
+ 'expectedTxt',
+ 'cname',
+ TRUE,
+ NOW(),
+ NOW()
+ ) :: "domainsVirtual"
+ )
+ ),
+ '2024-06-15 12:30:00+00' :: timestamp with time zone,
+ 'Test Case 9: updatedAt field should be returned correctly from latestBuildVirtual(domainsVirtual).'
+ );
-- Finalize the tests
-SELECT finish();
+SELECT
+ finish();
ROLLBACK;
\ No newline at end of file
diff --git a/packages/postgrest/supabase/tests/latest-builds-projects.sql b/packages/postgrest/supabase/tests/latest-builds-projects.sql
index 631d302e74..830913eccf 100644
--- a/packages/postgrest/supabase/tests/latest-builds-projects.sql
+++ b/packages/postgrest/supabase/tests/latest-builds-projects.sql
@@ -1,494 +1,808 @@
BEGIN;
-SET LOCAL search_path = pgtap, public;
+
+SET
+ LOCAL search_path = pgtap,
+ public;
-- Initialize the testing environment without planning any specific number of tests
-SELECT no_plan();
+SELECT
+ no_plan();
--------------------------------------------------------------------------------
-- Setup: Insert Initial Data
--------------------------------------------------------------------------------
-
-- Insert a new user into the User table
-INSERT INTO "public"."User" ("id", "createdAt", "email", "username")
+INSERT INTO
+ "public"."User" ("id", "createdAt", "email", "username")
VALUES
- ('user1', '2023-01-01 00:00:00+00', '[email protected]', 'user1');
+ (
+ 'user1',
+ '2023-01-01 00:00:00+00',
+ 'user1'
+ );
-- Insert projects associated with the user
-INSERT INTO "public"."Project" ("id", "title", "domain", "userId", "isDeleted", "createdAt")
+INSERT INTO
+ "public"."Project" (
+ "id",
+ "title",
+ "domain",
+ "userId",
+ "isDeleted",
+ "createdAt"
+ )
VALUES
- ('project1', 'Project One', '517cce32-9af3-project1-domain1', 'user1', false, '2023-01-01 00:00:00+00'),
- ('project2', 'Project Two', '517cce32-9af3-project2-domain1', 'user1', false, '2023-01-01 00:00:00+00');
+ (
+ 'project1',
+ 'Project One',
+ '517cce32-9af3-project1-domain1',
+ 'user1',
+ false,
+ '2023-01-01 00:00:00+00'
+ ),
+ (
+ 'project2',
+ 'Project Two',
+ '517cce32-9af3-project2-domain1',
+ 'user1',
+ false,
+ '2023-01-01 00:00:00+00'
+ );
-- Insert builds with different deployment formats
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- -- Old deployment format: includes projectDomain
- (
- 'build1',
- '2023-01-01 00:00:00+00',
- 'home',
- 'project1',
- '{"projectDomain": "517cce32-9af3-project1-domain1", "domains": [""]}'::text,
- '2023-01-01 00:00:00+00',
- 'PUBLISHED'
- ),
- (
- 'build1-old',
- '2022-01-01 00:00:00+00',
- 'home',
- 'project1',
- '{"projectDomain": "517cce32-9af3-project1-domain1", "domains": [""]}'::text,
- '2022-01-01 00:00:00+00',
- 'PUBLISHED'
- ),
- (
- 'build1-newest-wrong-domain',
- '2024-01-01 00:00:00+00',
- 'home',
- 'project1',
- '{"projectDomain": "project-wrong", "domains": [""]}'::text,
- '2024-01-01 00:00:00+00',
- 'PUBLISHED'
- ),
- -- New deployment format: domains array only
- (
- 'build2',
- '2023-01-02 00:00:00+00',
- 'home',
- 'project2',
- '{"domains": ["517cce32-9af3-project2-domain1"]}'::text,
- '2023-01-02 00:00:00+00',
- 'PENDING'
- ),
- (
- 'build2-old',
- '2022-01-02 00:00:00+00',
- 'home',
- 'project2',
- '{"domains": ["517cce32-9af3-project2-domain1"]}'::text,
- '2022-01-02 00:00:00+00',
- 'PENDING'
- );
-
---------------------------------------------------------------------------------
--- Test Case 1: Verify Latest Build Retrieval Using Old Deployment Format (projectDomain)
---------------------------------------------------------------------------------
-SELECT is (
+ -- Old deployment format: includes projectDomain
(
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
+ 'build1',
+ '2023-01-01 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"projectDomain": "517cce32-9af3-project1-domain1", "domains": [""]}' :: text,
+ '2023-01-01 00:00:00+00',
+ 'PUBLISHED'
+ ),
+ (
+ 'build1-old',
+ '2022-01-01 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"projectDomain": "517cce32-9af3-project1-domain1", "domains": [""]}' :: text,
+ '2022-01-01 00:00:00+00',
+ 'PUBLISHED'
),
- ARRAY['build1', '517cce32-9af3-project1-domain1'],
- 'Test Case 1.1: Should return the latest build for project1 with domain matching projectDomain.'
-);
-
-
-SELECT is (
(
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestProjectDomainBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
+ 'build1-newest-wrong-domain',
+ '2024-01-01 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"projectDomain": "project-wrong", "domains": [""]}' :: text,
+ '2024-01-01 00:00:00+00',
+ 'PUBLISHED'
),
- ARRAY['build1', '517cce32-9af3-project1-domain1'],
- 'Test Case 1.2: Should return the latest build for project1 with domain matching projectDomain.'
-);
+ -- New deployment format: domains array only
+ (
+ 'build2',
+ '2023-01-02 00:00:00+00',
+ 'home',
+ 'project2',
+ '{"domains": ["517cce32-9af3-project2-domain1"]}' :: text,
+ '2023-01-02 00:00:00+00',
+ 'PENDING'
+ ),
+ (
+ 'build2-old',
+ '2022-01-02 00:00:00+00',
+ 'home',
+ 'project2',
+ '{"domains": ["517cce32-9af3-project2-domain1"]}' :: text,
+ '2022-01-02 00:00:00+00',
+ 'PENDING'
+ );
+
+--------------------------------------------------------------------------------
+-- Test Case 1: Verify Latest Build Retrieval Using Old Deployment Format (projectDomain)
+--------------------------------------------------------------------------------
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1', '517cce32-9af3-project1-domain1'],
+ 'Test Case 1.1: Should return the latest build for project1 with domain matching projectDomain.'
+ );
+
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestProjectDomainBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1', '517cce32-9af3-project1-domain1'],
+ 'Test Case 1.2: Should return the latest build for project1 with domain matching projectDomain.'
+ );
--------------------------------------------------------------------------------
-- Test Case 2: Verify Latest Build Retrieval Using New Deployment Format (domains array)
--------------------------------------------------------------------------------
-SELECT is (
- (
- SELECT "buildId"
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project2'
- )
- )
- ),
- 'build2',
- 'Test Case 2.1: Should return the latest build for project2 with domain present in domains array.'
-);
+SELECT
+ is (
+ (
+ SELECT
+ "buildId"
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project2'
+ )
+ )
+ ),
+ 'build2',
+ 'Test Case 2.1: Should return the latest build for project2 with domain present in domains array.'
+ );
+
+SELECT
+ is (
+ (
+ SELECT
+ "buildId"
+ FROM
+ "public"."latestProjectDomainBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project2'
+ )
+ )
+ ),
+ 'build2',
+ 'Test Case 2.2: Should return the latest build for project2 domain with domain present in domains array.'
+ );
-SELECT is (
- (
- SELECT "buildId"
- FROM "public"."latestProjectDomainBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project2'
- )
- )
- ),
- 'build2',
- 'Test Case 2.2: Should return the latest build for project2 domain with domain present in domains array.'
-);
--------------------------------------------------------------------------------
-- Test Case 3: Update Project Domain and Verify No Build Exists for the New Domain
--------------------------------------------------------------------------------
-- Update project1's domain to a new domain
-UPDATE "public"."Project"
-SET "domain" = 'project1-domain2'
-WHERE "id" = 'project1';
+UPDATE
+ "public"."Project"
+SET
+ "domain" = 'project1-domain2'
+WHERE
+ "id" = 'project1';
-- Verify that no build exists for the updated domain
-SELECT is (
- (
- SELECT COUNT(*)::integer
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- 0,
- 'Test Case 3.1: Should return 0 as no build exists for the updated domain project1-domain2.'
-);
-
-SELECT is (
- (
- SELECT COUNT(*)::integer
- FROM "public"."latestProjectDomainBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- 0,
- 'Test Case 3.2: Should return 0 as no build exists for the updated domain project1-domain2.'
-);
+SELECT
+ is (
+ (
+ SELECT
+ COUNT(*) :: integer
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ 0,
+ 'Test Case 3.1: Should return 0 as no build exists for the updated domain project1-domain2.'
+ );
+
+SELECT
+ is (
+ (
+ SELECT
+ COUNT(*) :: integer
+ FROM
+ "public"."latestProjectDomainBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ 0,
+ 'Test Case 3.2: Should return 0 as no build exists for the updated domain project1-domain2.'
+ );
--------------------------------------------------------------------------------
-- Test Case 4: Insert a New Build with the Updated Domain and Verify Retrieval
--------------------------------------------------------------------------------
-- Insert a new build associated with the updated domain
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build1-for-domain2',
- '2023-01-01 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["some-other-domain.com", "project1-domain2"]}'::text,
- '2023-01-01 00:00:00+00',
- 'PUBLISHED'
- );
-
--- Verify that the latest build now reflects the updated domain
-SELECT is (
(
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- ARRAY['build1-for-domain2','project1-domain2'],
- 'Test Case 4.1: Should return the latest build for project1 with the updated domain in domains array.'
-);
-
-SELECT is (
- (
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestProjectDomainBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- ARRAY['build1-for-domain2','project1-domain2'],
- 'Test Case 4.2: Should return the latest build for project1 domain with the updated domain in domains array.'
-);
+ 'build1-for-domain2',
+ '2023-01-01 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["some-other-domain.com", "project1-domain2"]}' :: text,
+ '2023-01-01 00:00:00+00',
+ 'PUBLISHED'
+ );
+-- Verify that the latest build now reflects the updated domain
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1-for-domain2','project1-domain2'],
+ 'Test Case 4.1: Should return the latest build for project1 with the updated domain in domains array.'
+ );
+
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestProjectDomainBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1-for-domain2','project1-domain2'],
+ 'Test Case 4.2: Should return the latest build for project1 domain with the updated domain in domains array.'
+ );
--------------------------------------------------------------------------------
-- Test Case 5: Register Custom Domains and Verify Latest Build for a Custom Domain
--------------------------------------------------------------------------------
-- Insert custom domains
-INSERT INTO "public"."Domain" (
- "id",
- "domain",
- "createdAt",
- "status",
- "updatedAt"
-)
+INSERT INTO
+ "public"."Domain" (
+ "id",
+ "domain",
+ "createdAt",
+ "status",
+ "updatedAt"
+ )
VALUES
- ('project-1-custom-domain-1', '517cce32-9af3-project-1-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),
- ('project-1-custom-domain-2', '517cce32-9af3-project-1-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00');
+ (
+ 'project-1-custom-domain-1',
+ '517cce32-9af3-project-1-custom-domain-1.com',
+ '2023-01-01 00:00:00+00',
+ 'INITIALIZING',
+ '2023-01-01 00:00:00+00'
+ ),
+ (
+ 'project-1-custom-domain-2',
+ '517cce32-9af3-project-1-custom-domain-2.com',
+ '2023-01-01 00:00:00+00',
+ 'INITIALIZING',
+ '2023-01-01 00:00:00+00'
+ );
-- Establish relationships between project1 and custom domains
-INSERT INTO "public"."ProjectDomain" (
- "projectId",
- "domainId",
- "createdAt",
- "txtRecord",
- "cname"
-)
+INSERT INTO
+ "public"."ProjectDomain" (
+ "projectId",
+ "domainId",
+ "createdAt",
+ "txtRecord",
+ "cname"
+ )
VALUES
- ('project1', 'project-1-custom-domain-1', '2023-01-01 00:00:00+00', 'txtRecord1', 'cname1'),
- ('project1', 'project-1-custom-domain-2', '2023-01-01 00:00:00+00', 'txtRecord2', 'cname2');
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ '2023-01-01 00:00:00+00',
+ 'txtRecord1',
+ 'cname1'
+ ),
+ (
+ 'project1',
+ 'project-1-custom-domain-2',
+ '2023-01-01 00:00:00+00',
+ 'txtRecord2',
+ 'cname2'
+ );
-- Insert a build associated with a custom domain
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build1-for-custom-domain-1',
- '2023-01-02 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,
- '2023-01-02 00:00:00+00',
- 'PUBLISHED'
- );
-
--- Verify that the latest build reflects the custom domain association
-SELECT is (
(
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- ARRAY['build1-for-custom-domain-1','517cce32-9af3-project-1-custom-domain-1.com'],
- 'Test Case 5.1: Should return the latest build for project1 with a registered custom domain in domains array.'
-);
+ 'build1-for-custom-domain-1',
+ '2023-01-02 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}' :: text,
+ '2023-01-02 00:00:00+00',
+ 'PUBLISHED'
+ );
+-- Verify that the latest build reflects the custom domain association
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1-for-custom-domain-1','517cce32-9af3-project-1-custom-domain-1.com'],
+ 'Test Case 5.1: Should return the latest build for project1 with a registered custom domain in domains array.'
+ );
-- Ensure the latest project domain build has not changed
-- The difference between latestProjectDomainBuildVirtual and latestBuildVirtual is that the first returns data only for the project domain
-SELECT is (
- (
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestProjectDomainBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- ARRAY['build1-for-domain2','project1-domain2'],
- 'Test Case 5.2: Should return the latest build for project1 domain and not affected by custom domains'
-);
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestProjectDomainBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1-for-domain2','project1-domain2'],
+ 'Test Case 5.2: Should return the latest build for project1 domain and not affected by custom domains'
+ );
--------------------------------------------------------------------------------
-- Test Case 6: Publish a Preview Domain and Verify Latest Build Retrieval
--------------------------------------------------------------------------------
-- Insert a build for the preview domain using the new deployment format
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build1-for-domain2-new',
- '2023-01-03 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["517cce32-9af3-project-1-custom-domain-1.com", "project1-domain2"]}'::text,
- '2023-01-03 00:00:00+00',
- 'PUBLISHED'
- );
-
--- Verify that the latest build reflects the preview domain
-SELECT is (
- (
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- ARRAY['build1-for-domain2-new', 'project1-domain2'],
- 'Test Case 6.1: Should return the latest build for project1 with the preview domain in domains array.'
-);
-
-SELECT is (
(
- SELECT ARRAY["buildId", "domain"]
- FROM "public"."latestProjectDomainBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- ARRAY['build1-for-domain2-new', 'project1-domain2'],
- 'Test Case 6.2: Should return the latest build for project1 with the preview domain in domains array.'
-);
+ 'build1-for-domain2-new',
+ '2023-01-03 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["517cce32-9af3-project-1-custom-domain-1.com", "project1-domain2"]}' :: text,
+ '2023-01-03 00:00:00+00',
+ 'PUBLISHED'
+ );
+-- Verify that the latest build reflects the preview domain
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1-for-domain2-new', 'project1-domain2'],
+ 'Test Case 6.1: Should return the latest build for project1 with the preview domain in domains array.'
+ );
+
+SELECT
+ is (
+ (
+ SELECT
+ ARRAY ["buildId", "domain"]
+ FROM
+ "public"."latestProjectDomainBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ ARRAY ['build1-for-domain2-new', 'project1-domain2'],
+ 'Test Case 6.2: Should return the latest build for project1 with the preview domain in domains array.'
+ );
--------------------------------------------------------------------------------
-- Test Case 7: Publish a New Build for a Custom Domain, Delete the Custom Domain, and Verify Latest Build Update
--------------------------------------------------------------------------------
-- Insert a new build for the custom domain
-INSERT INTO "public"."Build" (
- "id",
- "createdAt",
- "pages",
- "projectId",
- "deployment",
- "updatedAt",
- "publishStatus"
-)
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
VALUES
- (
- 'build1-for-custom-domain-1-new',
- '2023-01-04 00:00:00+00',
- 'home',
- 'project1',
- '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,
- '2023-01-04 00:00:00+00',
- 'PUBLISHED'
- );
+ (
+ 'build1-for-custom-domain-1-new',
+ '2023-01-04 00:00:00+00',
+ 'home',
+ 'project1',
+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}' :: text,
+ '2023-01-04 00:00:00+00',
+ 'PUBLISHED'
+ );
-- Verify that the latest build reflects the newly published build for the custom domain
-SELECT is (
- (
- SELECT "buildId"
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- 'build1-for-custom-domain-1-new',
- 'Test Case 7a: Should return the latest build after publishing a new build for a custom domain.'
-);
+SELECT
+ is (
+ (
+ SELECT
+ "buildId"
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ 'build1-for-custom-domain-1-new',
+ 'Test Case 7a: Should return the latest build after publishing a new build for a custom domain.'
+ );
-- Delete the custom domain association
-DELETE FROM "public"."ProjectDomain"
-WHERE "projectId" = 'project1' AND "domainId" = 'project-1-custom-domain-1';
+DELETE FROM
+ "public"."ProjectDomain"
+WHERE
+ "projectId" = 'project1'
+ AND "domainId" = 'project-1-custom-domain-1';
-- Verify that the latest build reverts to the previous latest build after deletion
-SELECT is (
- (
- SELECT "buildId"
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- 'build1-for-domain2-new',
- 'Test Case 7b: Should return the latest build after deleting the custom domain, reverting to the previous latest build.'
-);
+SELECT
+ is (
+ (
+ SELECT
+ "buildId"
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ 'build1-for-domain2-new',
+ 'Test Case 7b: Should return the latest build after deleting the custom domain, reverting to the previous latest build.'
+ );
--------------------------------------------------------------------------------
-- Test Case 8: Publish a New Build for a Custom Domain, Move the Custom Domain, and Verify Latest Build Update
--------------------------------------------------------------------------------
-- Re-establish the custom domain association to revert Test Case 7
-INSERT INTO "public"."ProjectDomain" (
- "projectId",
- "domainId",
- "createdAt",
- "txtRecord",
- "cname"
-)
+INSERT INTO
+ "public"."ProjectDomain" (
+ "projectId",
+ "domainId",
+ "createdAt",
+ "txtRecord",
+ "cname"
+ )
VALUES
- ('project1', 'project-1-custom-domain-1', '2023-01-01 00:00:00+00', 'txtRecord1', 'cname1');
+ (
+ 'project1',
+ 'project-1-custom-domain-1',
+ '2023-01-01 00:00:00+00',
+ 'txtRecord1',
+ 'cname1'
+ );
-- Verify that the latest build is updated after re-establishing the custom domain
-SELECT is (
- (
- SELECT "buildId"
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
- ),
- 'build1-for-custom-domain-1-new',
- 'Test Case 8a: Should return the latest build after re-publishing a new build for a custom domain.'
-);
+SELECT
+ is (
+ (
+ SELECT
+ "buildId"
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ 'build1-for-custom-domain-1-new',
+ 'Test Case 8a: Should return the latest build after re-publishing a new build for a custom domain.'
+ );
-- Move the custom domain association from project1 to project2
-UPDATE "public"."ProjectDomain"
-SET "projectId" = 'project2'
-WHERE "projectId" = 'project1' AND "domainId" = 'project-1-custom-domain-1';
+UPDATE
+ "public"."ProjectDomain"
+SET
+ "projectId" = 'project2'
+WHERE
+ "projectId" = 'project1'
+ AND "domainId" = 'project-1-custom-domain-1';
-- Verify that the latest build reverts to the previous latest build after moving the custom domain
-SELECT is (
+SELECT
+ is (
+ (
+ SELECT
+ "buildId"
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project1'
+ )
+ )
+ ),
+ 'build1-for-domain2-new',
+ 'Test Case 8b: Should return the latest build after moving the custom domain, reverting to the previous latest build.'
+ );
+
+--------------------------------------------------------------------------------
+-- Test Case 9: Verify updatedAt Field is Returned (Selection is Still by createdAt)
+--------------------------------------------------------------------------------
+-- Insert builds with different createdAt and updatedAt
+-- NOTE: "Latest build" is determined by createdAt (when published), not updatedAt
+INSERT INTO
+ "public"."Build" (
+ "id",
+ "createdAt",
+ "pages",
+ "projectId",
+ "deployment",
+ "updatedAt",
+ "publishStatus"
+ )
+VALUES
+ -- Older createdAt but newer updatedAt
(
- SELECT "buildId"
- FROM "public"."latestBuildVirtual"(
- (
- SELECT (p.*)::"Project"
- FROM "public"."Project" p
- WHERE p."id" = 'project1'
- )
- )
+ 'build-updated-recently',
+ '2023-01-01 00:00:00+00',
+ 'home',
+ 'project2',
+ '{"domains": ["517cce32-9af3-project2-domain1"]}' :: text,
+ '2024-01-01 00:00:00+00',
+ 'PUBLISHED'
),
- 'build1-for-domain2-new',
- 'Test Case 8b: Should return the latest build after moving the custom domain, reverting to the previous latest build.'
-);
+ -- Newer createdAt but older updatedAt - SHOULD be selected as "latest"
+ (
+ 'build-created-recently',
+ '2023-06-01 00:00:00+00',
+ 'home',
+ 'project2',
+ '{"domains": ["517cce32-9af3-project2-domain1"]}' :: text,
+ '2023-01-15 00:00:00+00',
+ 'PUBLISHED'
+ );
+
+-- Verify that the build with newest createdAt is selected (not newest updatedAt)
+SELECT
+ is (
+ (
+ SELECT
+ "buildId"
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project2'
+ )
+ )
+ ),
+ 'build-created-recently',
+ 'Test Case 9.1: Should select build with newest createdAt (selection is by createdAt, not updatedAt).'
+ );
+
+-- Verify that updatedAt field is returned (even though it is not the newest)
+SELECT
+ is (
+ (
+ SELECT
+ "updatedAt"
+ FROM
+ "public"."latestBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project2'
+ )
+ )
+ ),
+ '2023-01-15 00:00:00+00' :: timestamp with time zone,
+ 'Test Case 9.2: updatedAt field from the selected build should be returned in latestBuildVirtual result.'
+ );
+
+SELECT
+ is (
+ (
+ SELECT
+ "updatedAt"
+ FROM
+ "public"."latestProjectDomainBuildVirtual"(
+ (
+ SELECT
+ (p.*) :: "Project"
+ FROM
+ "public"."Project" p
+ WHERE
+ p."id" = 'project2'
+ )
+ )
+ ),
+ '2023-01-15 00:00:00+00' :: timestamp with time zone,
+ 'Test Case 9.3: updatedAt field from the selected build should be returned in latestProjectDomainBuildVirtual result.'
+ );
+
+--------------------------------------------------------------------------------
+-- Test Case 10: Verify All Columns Are Returned in Correct Order
+--------------------------------------------------------------------------------
+-- Check that all 7 columns are present in the result
+SELECT
+ ok(
+ (
+ SELECT
+ COUNT(*) = 7
+ FROM
+ information_schema.columns
+ WHERE
+ table_name = 'latestBuildVirtual'
+ ),
+ 'Test Case 10: latestBuildVirtual should have exactly 7 columns (buildId, projectId, domainsVirtualId, domain, createdAt, publishStatus, updatedAt).'
+ );
+
+-- Verify column names match expected structure
+SELECT
+ bag_eq(
+ $ $
+ SELECT
+ column_name :: text
+ FROM
+ information_schema.columns
+ WHERE
+ table_name = 'latestBuildVirtual' $ $,
+ $ $
+ VALUES
+ ('buildId'),
+ ('projectId'),
+ ('domainsVirtualId'),
+ ('domain'),
+ ('createdAt'),
+ ('publishStatus'),
+ ('updatedAt') $ $,
+ 'Test Case 10.1: All expected columns should be present in latestBuildVirtual table.'
+ );
-- Finalize the tests
-SELECT finish();
+SELECT
+ finish();
ROLLBACK;
\ No newline at end of file
diff --git a/packages/prisma-client/prisma/migrations/20251129093846_add_updated_at_to_latest_build_virtual/migration.sql b/packages/prisma-client/prisma/migrations/20251129093846_add_updated_at_to_latest_build_virtual/migration.sql
new file mode 100644
index 0000000000..d055a0bdcc
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20251129093846_add_updated_at_to_latest_build_virtual/migration.sql
@@ -0,0 +1,116 @@
+-- Add updatedAt field to latestBuildVirtual virtual table (type definition)
+-- and update both functions to include Build's updatedAt timestamp
+-- Add updatedAt column to the virtual table type definition
+ALTER TABLE
+ "latestBuildVirtual"
+ADD
+ COLUMN "updatedAt" timestamp(3) with time zone NOT NULL;
+
+COMMENT ON COLUMN "latestBuildVirtual"."updatedAt" IS 'Timestamp indicating when the Build was last updated';
+
+-- Recreate the function for Project with updatedAt field
+CREATE
+OR REPLACE FUNCTION "latestBuildVirtual"("Project") RETURNS SETOF "latestBuildVirtual" ROWS 1 AS $ $
+SELECT
+ b.id AS "buildId",
+ b."projectId",
+ '' as "domainsVirtualId",
+ -- Use CASE to determine which domain to select based on conditions
+ CASE
+ WHEN (b.deployment :: jsonb ->> 'projectDomain') = p.domain
+ OR (b.deployment :: jsonb -> 'domains') @ > to_jsonb(array [p.domain]) THEN p.domain
+ ELSE d.domain
+ END AS "domain",
+ b."createdAt",
+ b."publishStatus",
+ b."updatedAt"
+FROM
+ "Build" b
+ JOIN "Project" p ON b."projectId" = p.id
+ LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id
+ LEFT JOIN "Domain" d ON d.id = pd."domainId"
+WHERE
+ b."projectId" = $ 1.id
+ AND b.deployment IS NOT NULL -- 'destination' IS NULL for backward compatibility; 'destination' = 'saas' for non-static builds
+ AND (
+ (b.deployment :: jsonb ->> 'destination') IS NULL
+ OR (b.deployment :: jsonb ->> 'destination') = 'saas'
+ )
+ AND (
+ -- Check if 'projectDomain' matches p.domain
+ (b.deployment :: jsonb ->> 'projectDomain') = p.domain -- Check if 'domains' contains p.domain or d.domain
+ OR (b.deployment :: jsonb -> 'domains') @ > to_jsonb(array [p.domain])
+ OR (b.deployment :: jsonb -> 'domains') @ > to_jsonb(array [d.domain])
+ )
+ORDER BY
+ b."createdAt" DESC
+LIMIT
+ 1;
+
+$ $ STABLE LANGUAGE sql;
+
+-- Comment on the function
+COMMENT ON FUNCTION "latestBuildVirtual"("Project") IS 'This function computes the latest build for a project, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.';
+
+-- Recreate the function for domainsVirtual with updatedAt field
+CREATE
+OR REPLACE FUNCTION "latestBuildVirtual"("domainsVirtual") RETURNS SETOF "latestBuildVirtual" ROWS 1 AS $ $
+SELECT
+ b.id AS "buildId",
+ b."projectId",
+ '' as "domainsVirtualId",
+ d."domain",
+ b."createdAt",
+ b."publishStatus",
+ b."updatedAt"
+FROM
+ "Build" b
+ JOIN "Domain" d ON d.id = $ 1."domainId"
+WHERE
+ b."projectId" = $ 1."projectId"
+ AND b.deployment IS NOT NULL
+ AND (b.deployment :: jsonb -> 'domains') @ > to_jsonb(array [d.domain])
+ORDER BY
+ b."createdAt" DESC
+LIMIT
+ 1;
+
+$ $ STABLE LANGUAGE sql;
+
+-- Adding a comment to provide more context
+COMMENT ON FUNCTION "latestBuildVirtual"("domainsVirtual") IS 'Returns the latest build for a given project and domain as a computed field for PostgREST.';
+
+-- Update latestProjectDomainBuildVirtual function to include updatedAt
+CREATE
+OR REPLACE FUNCTION "latestProjectDomainBuildVirtual"("Project") RETURNS SETOF "latestBuildVirtual" ROWS 1 AS $ $
+SELECT
+ b.id AS "buildId",
+ b."projectId",
+ '' as "domainsVirtualId",
+ p.domain AS "domain",
+ b."createdAt",
+ b."publishStatus",
+ b."updatedAt"
+FROM
+ "Build" b
+ JOIN "Project" p ON b."projectId" = p.id
+ LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id
+WHERE
+ b."projectId" = $ 1.id
+ AND b.deployment IS NOT NULL
+ AND (
+ (b.deployment :: jsonb ->> 'destination') IS NULL
+ OR (b.deployment :: jsonb ->> 'destination') = 'saas'
+ )
+ AND (
+ (b.deployment :: jsonb ->> 'projectDomain') = p.domain
+ OR (b.deployment :: jsonb -> 'domains') @ > to_jsonb(array [p.domain])
+ )
+ORDER BY
+ b."createdAt" DESC
+LIMIT
+ 1;
+
+$ $ STABLE LANGUAGE sql;
+
+COMMENT ON FUNCTION "latestProjectDomainBuildVirtual"("Project") IS 'This function computes the latest build for a project domain, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.';
\ No newline at end of file
diff --git a/packages/prisma-client/prisma/migrations/20251130131728_add_latest_build_virtual_for_dashboard_project/migration.sql b/packages/prisma-client/prisma/migrations/20251130131728_add_latest_build_virtual_for_dashboard_project/migration.sql
new file mode 100644
index 0000000000..f996c5d920
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20251130131728_add_latest_build_virtual_for_dashboard_project/migration.sql
@@ -0,0 +1,28 @@
+-- Add latestBuildVirtual function overload for DashboardProject view
+-- This is needed because PostgREST computed fields require a function
+-- that matches the source table/view type. DashboardProject is a view
+-- over Project, so we need this wrapper function.
+CREATE
+OR REPLACE FUNCTION "latestBuildVirtual"("DashboardProject") RETURNS SETOF "latestBuildVirtual" ROWS 1 AS $ $
+SELECT
+ *
+FROM
+ "latestBuildVirtual"(
+ (
+ SELECT
+ p
+ FROM
+ "Project" p
+ WHERE
+ p.id = $ 1.id
+ )
+ );
+
+$ $ STABLE LANGUAGE sql;
+
+COMMENT ON FUNCTION "latestBuildVirtual"("DashboardProject") IS 'Wrapper function to make latestBuildVirtual work with DashboardProject view for PostgREST computed fields.';
+
+-- Grant execute permissions to all PostgREST roles
+GRANT EXECUTE ON FUNCTION "latestBuildVirtual"("DashboardProject") TO anon,
+authenticated,
+service_role;
\ No newline at end of file