Skip to content
This repository has been archived by the owner on Jan 30, 2024. It is now read-only.

Add ability to edit topic labels and topic groups #268

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/squeak/src/lib/api/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,19 @@ export function patchTopic({
organizationId,
id,
topicGroupId,
label,
}: {
organizationId: string
id: ID
topicGroupId: string | null
label?: string
}) {
return doPatch<GetTopicGroupsResponse[]>(`/api/topics/${id}`, { organizationId, id, topicGroupId })
return doPatch<GetTopicGroupsResponse[]>(`/api/topics/${id}`, {
organizationId,
id,
topicGroupId,
label,
})
}

export function createTopicGroup(label: string) {
Expand All @@ -35,3 +42,7 @@ export function createTopicGroup(label: string) {
export function getTopicGroups(organizationId: string) {
return doGet<GetTopicGroupsResponse[]>('/api/topic-groups', { organizationId })
}

export function patchTopicGroup({ organizationId, id, label }) {
return doPatch<GetTopicGroupsResponse[]>('/api/topic-groups', { organizationId, id, label })
}
26 changes: 25 additions & 1 deletion packages/squeak/src/pages/api/topic-groups.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TopicGroup, Prisma } from '@prisma/client'
import { NextApiRequest, NextApiResponse } from 'next'
import { getSessionUser } from 'src/lib/auth'

import { requireOrgAdmin } from '../../lib/api/apiUtils'
import { methodNotAllowed, orgIdNotFound, safeJson } from '../../lib/api/apiUtils'
import prisma from '../../lib/db'

Expand All @@ -19,6 +19,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
switch (req.method) {
case 'POST':
return handlePost(req, res)
case 'PATCH':
return handlePatch(req, res)
case 'GET':
return handleGet(req, res)
default:
Expand All @@ -43,6 +45,28 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
safeJson(res, topicGroup, 201)
}

async function handlePatch(req: NextApiRequest, res: NextApiResponse) {
if (!(await requireOrgAdmin(req, res))) return
const user = await getSessionUser(req)

if (!user) return orgIdNotFound(res)

const body = req.body

if (!body?.id || !body?.label) return res.status(400).json({ error: 'Missing required fields' })

const topicGroup: TopicGroup = await prisma.topicGroup.update({
where: {
id: BigInt(body?.id),
},
data: {
label: body?.label,
},
})

safeJson(res, topicGroup, 201)
}

async function handleGet(req: NextApiRequest, res: NextApiResponse) {
const organizationId = req.body.organizationId || req.query.organizationId

Expand Down
3 changes: 2 additions & 1 deletion packages/squeak/src/pages/api/topics/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,13 @@ async function handlePatch(req: NextApiRequest, res: NextApiResponse) {

if (!user) return orgIdNotFound(res)

const { id, topicGroupId } = req.body
const { id, topicGroupId, label } = req.body

await prisma.topic.updateMany({
where: { id: parseInt(id), organization_id: user.organizationId },
data: {
topic_group_id: topicGroupId && parseInt(topicGroupId),
...(label ? { label } : {}),
},
})

Expand Down
135 changes: 96 additions & 39 deletions packages/squeak/src/pages/topics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Modal from '../components/Modal'
import { useEffect, useState } from 'react'
import { Form, Formik } from 'formik'
import Input from '../components/Input'
import { createTopicGroup, getTopicGroups, getTopics, patchTopic } from '../lib/api/topics'
import { createTopicGroup, getTopicGroups, getTopics, patchTopic, patchTopicGroup } from '../lib/api/topics'
import Select from '../components/Select'
import { ID } from '../lib/types'
import { GetTopicsResponse } from './api/topics'
Expand All @@ -29,20 +29,26 @@ const Row = ({ label, topic_group, id, organizationId, handleSubmit, topicGroups
const [modalOpen, setModalOpen] = useState(false)
const [loading, setLoading] = useState(false)

const handleAddTopicToGroup = async ({
const handleUpdateTopic = async ({
topicGroup,
newTopicGroup,
label,
editTopicGroup,
}: {
topicGroup: string | bigint
newTopicGroup: string
label: string
editTopicGroup: string | null
}) => {
setLoading(true)
let topicGroupId: bigint | string = topicGroup
if (newTopicGroup) {
const topicGroupRes = await createTopicGroup(newTopicGroup.trim())
if (topicGroupRes?.body?.id) topicGroupId = topicGroupRes?.body?.id
} else if (editTopicGroup) {
await patchTopicGroup({ organizationId, id: topicGroupId, label: editTopicGroup })
}
await patchTopic({ organizationId, id, topicGroupId: topicGroupId as string })
await patchTopic({ organizationId, id, label, topicGroupId: topicGroupId as string })
setModalOpen(false)
handleSubmit()
setLoading(false)
Expand All @@ -58,7 +64,12 @@ const Row = ({ label, topic_group, id, organizationId, handleSubmit, topicGroups
<>
<Modal open={modalOpen} onClose={() => setModalOpen(false)}>
<Formik
initialValues={{ topicGroup: topicGroups[0]?.id, newTopicGroup: '' }}
initialValues={{
topicGroup: topicGroups[0]?.id,
newTopicGroup: '',
label,
editTopicGroup: topicGroups[0]?.label,
}}
validateOnMount
validate={(values) => {
const errors: {
Expand All @@ -70,16 +81,27 @@ const Row = ({ label, topic_group, id, organizationId, handleSubmit, topicGroups

return errors
}}
onSubmit={({ newTopicGroup, topicGroup }) => handleAddTopicToGroup({ newTopicGroup, topicGroup })}
onSubmit={({ newTopicGroup, topicGroup, label, editTopicGroup }) =>
handleUpdateTopic({ newTopicGroup, topicGroup, label, editTopicGroup })
}
>
{() => {
{({ values, setFieldValue }) => {
return (
<Form>
<Input value={values.label} label="Label" placeholder="Label" id="label" name="label" />
<TopicGroupForm
handleRemoveTopicGroup={handleRemoveTopicGroup}
topicGroups={topicGroups}
loading={loading}
topicGroup={topic_group}
values={values}
setFieldValue={setFieldValue}
/>
<div className="flex items-center mt-4 space-x-6">
<Button type="submit" loading={loading} disabled={loading}>
Update
</Button>
</div>
</Form>
)
}}
Expand All @@ -94,17 +116,35 @@ const Row = ({ label, topic_group, id, organizationId, handleSubmit, topicGroups
{topic_group?.label || 'Add to a group'}
</button>
</td>
<td className="px-6 py-4 text-sm text-gray-500 whitespace-nowrap">
<button onClick={() => setModalOpen(true)} className="text-red font-semibold">
Edit
</button>
</td>
</tr>
</>
)
}

const TopicGroupForm = ({ loading, topicGroups, handleRemoveTopicGroup }) => {
const TopicGroupForm = ({ loading, topicGroups, handleRemoveTopicGroup, topicGroup, values, setFieldValue }) => {
const [createNewGroup, setCreateNewGroup] = useState(false)
const [editGroup, setEditGroup] = useState(false)

useEffect(() => {
setFieldValue('editTopicGroup', topicGroups.find((group) => group?.id === values.topicGroup)?.label)
}, [values?.topicGroup])

return (
<>
{createNewGroup ? (
{editGroup ? (
<Input
value={values.editTopicGroup}
label="Edit group"
placeholder="Edit group"
id="edit-topic-group"
name="editTopicGroup"
/>
) : createNewGroup ? (
<Input label="New group" placeholder="New group" id="new-topic-group" name="newTopicGroup" />
) : (
<Select
Expand All @@ -116,37 +156,48 @@ const TopicGroupForm = ({ loading, topicGroups, handleRemoveTopicGroup }) => {
})}
/>
)}
{createNewGroup ? (
<button
type="button"
className="text-red font-semibold -mt-4 block"
onClick={(e) => {
e.preventDefault()
setCreateNewGroup(false)
}}
>
Add to existing group
</button>
) : (
<button
type="button"
className="text-red font-semibold -mt-4 block"
onClick={(e) => {
e.preventDefault()
setCreateNewGroup(true)
}}
>
Create new group
</button>
)}

<div className="flex items-center mt-4 space-x-6">
<Button type="submit" loading={loading} disabled={loading}>
Add
</Button>
<Button type="button" onClick={handleRemoveTopicGroup} loading={loading} disabled={loading}>
Remove
</Button>
<div className="w-full flex justify-between">
{createNewGroup ? (
<button
type="button"
className="text-red font-semibold -mt-4 block"
onClick={(e) => {
e.preventDefault()
setCreateNewGroup(false)
setEditGroup(false)
}}
>
Add to existing group
</button>
) : (
<button
type="button"
className="text-red font-semibold -mt-4 block"
onClick={(e) => {
e.preventDefault()
setCreateNewGroup(true)
setEditGroup(false)
}}
>
Create new group
</button>
)}
{!createNewGroup && (
<button
type="button"
className="text-red font-semibold -mt-4 block"
onClick={(e) => {
e.preventDefault()
setFieldValue(
'editTopicGroup',
editGroup ? null : topicGroups.find((group) => group?.id === values.topicGroup)?.label
)
setEditGroup(!editGroup)
}}
>
Edit group
</button>
)}
</div>
</>
)
Expand Down Expand Up @@ -184,6 +235,12 @@ const TopicsLayout: React.VoidFunctionComponent<Props> = ({ organizationId }) =>
>
Group
</th>
<th
scope="col"
className="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase"
>
<span className="sr-only">Edit</span>
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
Expand Down