Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/admin create index page temp workabout #1065

Merged
merged 18 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { Tooltip } from "@chakra-ui/react"
import { Button, useToast } from "@opengovsg/design-system-react"
import { BiLogoDevTo } from "react-icons/bi"

import { BRIEF_TOAST_SETTINGS } from "~/constants/toast"
import { useIsUserIsomerAdmin } from "~/hooks/useIsUserIsomerAdmin"
import { trpc } from "~/utils/trpc"

interface AdminCreateIndexPageButtonProps {
siteId: number
parentId: number
}
export const AdminCreateIndexPageButton = ({
siteId,
parentId,
}: AdminCreateIndexPageButtonProps) => {
const toast = useToast()
const utils = trpc.useUtils()
const isUserIsomerAdmin = useIsUserIsomerAdmin()

const { data: indexPage } = trpc.resource.getIndexPage.useQuery({
siteId,
parentId: String(parentId),
})

const hasIndexPage = !!indexPage

const { mutate: createIndexPage, isLoading } =
trpc.page.createIndexPage.useMutation({
onSuccess: async () => {
// Invalidate only the necessary queries
await Promise.all([
utils.resource.getChildrenOf.invalidate({
siteId: String(siteId),
resourceId: String(parentId),
}),
utils.resource.listWithoutRoot.invalidate({ siteId: Number(siteId) }),
utils.collection.list.invalidate({ siteId: Number(siteId) }),
utils.resource.getIndexPage.invalidate({
siteId,
parentId: String(parentId),
}),
])
toast({
status: "success",
title: "Index page created successfully",
...BRIEF_TOAST_SETTINGS,
})
},
onError: (error) => {
toast({
status: "error",
title: "Failed to create index page",
description: error.message,
...BRIEF_TOAST_SETTINGS,
})
},
})

if (!isUserIsomerAdmin) return null
return (
<Tooltip
label={
hasIndexPage ? "Index page already exists" : "For Isomer Admins only"
}
placement="top"
>
<Button
variant="outline"
size="md"
isDisabled={isLoading || hasIndexPage}
isLoading={isLoading}
onClick={() => createIndexPage({ siteId, parentId: String(parentId) })}
leftIcon={<BiLogoDevTo fontSize="1rem" />}
aria-label="Create index page"
>
Add index page
</Button>
</Tooltip>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { z } from "zod"

import { PermissionsBoundary } from "~/components/AuthWrappers"
import { folderSettingsModalAtom } from "~/features/dashboard/atoms"
import { AdminCreateIndexPageButton } from "~/features/dashboard/components/AdminCreateIndexPageButton"
import { CollectionBanner } from "~/features/dashboard/components/CollectionBanner"
import { CollectionTable } from "~/features/dashboard/components/CollectionTable"
import { DashboardLayout } from "~/features/dashboard/components/DashboardLayout"
Expand Down Expand Up @@ -56,6 +57,7 @@ const CollectionResourceListPage: NextPageWithLayout = () => {
title={metadata.title}
buttons={
<>
<AdminCreateIndexPageButton siteId={siteId} parentId={resourceId} />
<Button
variant="outline"
size="md"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { z } from "zod"
import type { RouterOutput } from "~/utils/trpc"
import { PermissionsBoundary } from "~/components/AuthWrappers"
import { folderSettingsModalAtom } from "~/features/dashboard/atoms"
import { AdminCreateIndexPageButton } from "~/features/dashboard/components/AdminCreateIndexPageButton"
import { DashboardLayout } from "~/features/dashboard/components/DashboardLayout"
import { DeleteResourceModal } from "~/features/dashboard/components/DeleteResourceModal/DeleteResourceModal"
import { FolderSettingsModal } from "~/features/dashboard/components/FolderSettingsModal"
Expand Down Expand Up @@ -109,6 +110,10 @@ const FolderPage: NextPageWithLayout = () => {
title={title}
buttons={
<>
<AdminCreateIndexPageButton
siteId={parseInt(siteId)}
parentId={parseInt(folderId)}
/>
<Button
variant="outline"
size="md"
Expand Down
5 changes: 5 additions & 0 deletions apps/studio/src/schemas/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,8 @@ export const updatePageMetaSchema = z.object({
siteId: z.number().min(1),
resourceId: z.string().min(1),
})

export const createIndexPageSchema = z.object({
siteId: z.number().min(1),
parentId: z.string(),
})
9 changes: 9 additions & 0 deletions apps/studio/src/schemas/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,12 @@ export const searchWithResourceIdsSchema = z.object({
export const searchWithResourceIdsOutputSchema = z.array(
z.custom<SearchResultResource>(),
)

export const getIndexPageSchema = z.object({
siteId: z.number(),
parentId: z.string(),
})

export const getIndexPageOutputSchema = z.object({
id: z.string(),
})
101 changes: 99 additions & 2 deletions apps/studio/src/server/modules/page/page.router.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import type { IsomerSchema } from "@opengovsg/isomer-components"
import { getLayoutMetadataSchema, schema } from "@opengovsg/isomer-components"
import {
getLayoutMetadataSchema,
ISOMER_USABLE_PAGE_LAYOUTS,
schema,
} from "@opengovsg/isomer-components"
import { TRPCError } from "@trpc/server"
import { ResourceState, ResourceType } from "~prisma/generated/generatedEnums"
import { get, isEmpty, isEqual } from "lodash"
import { z } from "zod"

import { INDEX_PAGE_PERMALINK } from "~/constants/sitemap"
import {
basePageSchema,
createIndexPageSchema,
createPageSchema,
getRootPageSchema,
pageSettingsSchema,
Expand All @@ -19,7 +26,7 @@ import { protectedProcedure, router } from "~/server/trpc"
import { ajv } from "~/utils/ajv"
import { safeJsonParse } from "~/utils/safeJsonParse"
import { publishSite } from "../aws/codebuild.service"
import { db, jsonb, ResourceType } from "../database"
import { db, jsonb } from "../database"
import { PG_ERROR_CODES } from "../database/constants"
import { validateUserPermissionsForResource } from "../permissions/permissions.service"
import {
Expand Down Expand Up @@ -534,4 +541,94 @@ export const pageRouter = router({
}
return permalinkTree
}),

createIndexPage: protectedProcedure
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note - this mimics how on-call isoengineer currently add an index page manually

.input(createIndexPageSchema)
.mutation(async ({ ctx, input: { siteId, parentId } }) => {
await validateUserPermissionsForResource({
userId: ctx.user.id,
siteId: siteId,
action: "create",
resourceId: parentId,
})

// Validate whether parentId exists and is a Folder or Collection
const parent = await db
.selectFrom("Resource")
.where("Resource.id", "=", parentId)
.where("Resource.siteId", "=", siteId)
.where("Resource.type", "in", [
ResourceType.Folder,
ResourceType.Collection,
])
.select(["title", "permalink", "type"])
.executeTakeFirst()

if (!parent) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Parent resource not found or is not a folder/collection",
})
}

const blobContent =
parent.type === ResourceType.Collection
? {
layout: ISOMER_USABLE_PAGE_LAYOUTS.Collection,
page: {
title: parent.title,
subtitle: `Read more on ${parent.title.toLowerCase()} here.`,
defaultSortBy: "date",
defaultSortDirection: "asc",
},
content: [],
version: "0.1.0",
}
: {
layout: ISOMER_USABLE_PAGE_LAYOUTS.Index,
page: {
title: parent.title,
lastModified: new Date().toISOString(),
contentPageHeader: {
// follow the same format as autogenerated index pages
summary: `Pages in ${parent.title}`,
},
},
content: [],
version: "0.1.0",
}

return db.transaction().execute(async (tx) => {
const blob = await tx
.insertInto("Blob")
.values({ content: jsonb(blobContent) })
.returning("Blob.id")
.executeTakeFirstOrThrow()

const addedResource = await tx
.insertInto("Resource")
.values({
title: parent.title,
permalink: INDEX_PAGE_PERMALINK,
siteId,
parentId,
draftBlobId: blob.id,
type: ResourceType.IndexPage,
state: ResourceState.Draft,
})
.returning("Resource.id")
.executeTakeFirstOrThrow()
.catch((err) => {
if (get(err, "code") === PG_ERROR_CODES.uniqueViolation) {
throw new TRPCError({
code: "CONFLICT",
message: "A resource with the same permalink already exists",
})
}
throw err
})

return { pageId: addedResource.id }
})
}),
})
21 changes: 21 additions & 0 deletions apps/studio/src/server/modules/resource/resource.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
getAncestrySchema,
getChildrenSchema,
getFullPermalinkSchema,
getIndexPageOutputSchema,
getIndexPageSchema,
getMetadataSchema,
getParentSchema,
listResourceSchema,
Expand Down Expand Up @@ -572,4 +574,23 @@ export const resourceRouter = router({
(a, b) => resourceIds.indexOf(a.id) - resourceIds.indexOf(b.id),
)
}),

getIndexPage: protectedProcedure
.input(getIndexPageSchema)
.output(getIndexPageOutputSchema)
.query(async ({ input: { siteId, parentId } }) => {
const parent = await db
.selectFrom("Resource")
.where("Resource.siteId", "=", siteId)
.where("Resource.parentId", "=", parentId)
.where("Resource.type", "=", ResourceType.IndexPage)
.select(["Resource.id"])
.executeTakeFirst()

if (!parent) {
throw new TRPCError({ code: "NOT_FOUND" })
}

return parent
}),
})
Loading