commit
0ca6695869
@ -1,8 +0,0 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "QuestionsQuestion" ADD COLUMN "contentSearch" TSVECTOR
|
||||
GENERATED ALWAYS AS
|
||||
(to_tsvector('english', coalesce(content, '')))
|
||||
STORED;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "QuestionsQuestion_contentSearch_idx" ON "QuestionsQuestion" USING GIN("contentSearch");
|
@ -1,8 +0,0 @@
|
||||
-- DropIndex
|
||||
DROP INDEX "QuestionsQuestion_contentSearch_idx";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "QuestionsQuestion" ALTER COLUMN "contentSearch" DROP DEFAULT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "QuestionsQuestion_contentSearch_idx" ON "QuestionsQuestion"("contentSearch");
|
@ -0,0 +1,160 @@
|
||||
import clsx from 'clsx';
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
import { Fragment, useRef, useState } from 'react';
|
||||
import { Menu, Transition } from '@headlessui/react';
|
||||
import { CheckIcon, HeartIcon } from '@heroicons/react/20/solid';
|
||||
|
||||
import { trpc } from '~/utils/trpc';
|
||||
|
||||
export type AddToListDropdownProps = {
|
||||
questionId: string;
|
||||
};
|
||||
|
||||
export default function AddToListDropdown({
|
||||
questionId,
|
||||
}: AddToListDropdownProps) {
|
||||
const [menuOpened, setMenuOpened] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
const utils = trpc.useContext();
|
||||
const { data: lists } = trpc.useQuery(['questions.lists.getListsByUser']);
|
||||
|
||||
const listsWithQuestionData = useMemo(() => {
|
||||
return lists?.map((list) => ({
|
||||
...list,
|
||||
hasQuestion: list.questionEntries.some(
|
||||
(entry) => entry.question.id === questionId,
|
||||
),
|
||||
}));
|
||||
}, [lists, questionId]);
|
||||
|
||||
const { mutateAsync: addQuestionToList } = trpc.useMutation(
|
||||
'questions.lists.createQuestionEntry',
|
||||
{
|
||||
// TODO: Add optimistic update
|
||||
onSuccess: () => {
|
||||
utils.invalidateQueries(['questions.lists.getListsByUser']);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const { mutateAsync: removeQuestionFromList } = trpc.useMutation(
|
||||
'questions.lists.deleteQuestionEntry',
|
||||
{
|
||||
// TODO: Add optimistic update
|
||||
onSuccess: () => {
|
||||
utils.invalidateQueries(['questions.lists.getListsByUser']);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const addClickOutsideListener = () => {
|
||||
document.addEventListener('click', handleClickOutside, true);
|
||||
};
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(event.target as Node)) {
|
||||
setMenuOpened(false);
|
||||
document.removeEventListener('click', handleClickOutside, true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddToList = async (listId: string) => {
|
||||
await addQuestionToList({
|
||||
listId,
|
||||
questionId,
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteFromList = async (listId: string) => {
|
||||
const list = listsWithQuestionData?.find(
|
||||
(listWithQuestion) => listWithQuestion.id === listId,
|
||||
);
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
const entry = list.questionEntries.find(
|
||||
(questionEntry) => questionEntry.question.id === questionId,
|
||||
);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
await removeQuestionFromList({
|
||||
id: entry.id,
|
||||
});
|
||||
};
|
||||
|
||||
const CustomMenuButton = ({ children }: PropsWithChildren<unknown>) => (
|
||||
<button
|
||||
className="focus:ring-primary-500 inline-flex w-full justify-center rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 shadow-sm hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-slate-100"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
addClickOutsideListener();
|
||||
setMenuOpened(!menuOpened);
|
||||
}}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<Menu ref={ref} as="div" className="relative inline-block text-left">
|
||||
<div>
|
||||
<Menu.Button as={CustomMenuButton}>
|
||||
<HeartIcon aria-hidden="true" className="-ml-1 mr-2 h-5 w-5" />
|
||||
Add to List
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
show={menuOpened}>
|
||||
<Menu.Items
|
||||
className="absolute right-0 z-10 mt-2 w-56 origin-top-right divide-y divide-slate-100 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
|
||||
static={true}>
|
||||
{menuOpened && (
|
||||
<>
|
||||
{(listsWithQuestionData ?? []).map((list) => (
|
||||
<div key={list.id} className="py-1">
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
className={clsx(
|
||||
active
|
||||
? 'bg-slate-100 text-slate-900'
|
||||
: 'text-slate-700',
|
||||
'group flex w-full items-center px-4 py-2 text-sm',
|
||||
)}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (list.hasQuestion) {
|
||||
handleDeleteFromList(list.id);
|
||||
} else {
|
||||
handleAddToList(list.id);
|
||||
}
|
||||
}}>
|
||||
{list.hasQuestion && (
|
||||
<CheckIcon
|
||||
aria-hidden="true"
|
||||
className="mr-3 h-5 w-5 text-slate-400 group-hover:text-slate-500"
|
||||
/>
|
||||
)}
|
||||
{list.name}
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
);
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Button, Dialog, TextInput } from '@tih/ui';
|
||||
|
||||
import { useFormRegister } from '~/utils/questions/useFormRegister';
|
||||
|
||||
export type CreateListFormData = {
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type CreateListDialogProps = {
|
||||
onCancel: () => void;
|
||||
onSubmit: (data: CreateListFormData) => Promise<void>;
|
||||
show: boolean;
|
||||
};
|
||||
|
||||
export default function CreateListDialog({
|
||||
show,
|
||||
onCancel,
|
||||
onSubmit,
|
||||
}: CreateListDialogProps) {
|
||||
const {
|
||||
register: formRegister,
|
||||
handleSubmit,
|
||||
formState: { isSubmitting },
|
||||
reset,
|
||||
} = useForm<CreateListFormData>();
|
||||
const register = useFormRegister(formRegister);
|
||||
|
||||
const handleDialogCancel = () => {
|
||||
onCancel();
|
||||
reset();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
isShown={show}
|
||||
primaryButton={undefined}
|
||||
title="Create question list"
|
||||
onClose={handleDialogCancel}>
|
||||
<form
|
||||
className="mt-5 gap-2 sm:flex sm:items-center"
|
||||
onSubmit={handleSubmit(async (data) => {
|
||||
await onSubmit(data);
|
||||
reset();
|
||||
})}>
|
||||
<div className="w-full sm:max-w-xs">
|
||||
<TextInput
|
||||
id="listName"
|
||||
isLabelHidden={true}
|
||||
{...register('name')}
|
||||
autoComplete="off"
|
||||
label="Name"
|
||||
placeholder="List name"
|
||||
type="text"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
display="inline"
|
||||
label="Cancel"
|
||||
size="md"
|
||||
variant="tertiary"
|
||||
onClick={handleDialogCancel}
|
||||
/>
|
||||
<Button
|
||||
display="inline"
|
||||
isLoading={isSubmitting}
|
||||
label="Create"
|
||||
size="md"
|
||||
type="submit"
|
||||
variant="primary"
|
||||
/>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
import { Button, Dialog } from '@tih/ui';
|
||||
|
||||
export type DeleteListDialogProps = {
|
||||
onCancel: () => void;
|
||||
onDelete: () => void;
|
||||
show: boolean;
|
||||
};
|
||||
export default function DeleteListDialog({
|
||||
show,
|
||||
onCancel,
|
||||
onDelete,
|
||||
}: DeleteListDialogProps) {
|
||||
return (
|
||||
<Dialog
|
||||
isShown={show}
|
||||
primaryButton={
|
||||
<Button label="Delete" variant="primary" onClick={onDelete} />
|
||||
}
|
||||
secondaryButton={
|
||||
<Button label="Cancel" variant="tertiary" onClick={onCancel} />
|
||||
}
|
||||
title="Delete List"
|
||||
onClose={onCancel}>
|
||||
<p>
|
||||
Are you sure you want to delete this list? This action cannot be undone.
|
||||
</p>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
@ -0,0 +1,275 @@
|
||||
import { z } from 'zod';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { createQuestionWithAggregateData } from '~/utils/questions/server/aggregate-encounters';
|
||||
|
||||
import { createProtectedRouter } from './context';
|
||||
|
||||
export const questionsListRouter = createProtectedRouter()
|
||||
.query('getListsByUser', {
|
||||
async resolve({ ctx }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
// TODO: Optimize by not returning question entries
|
||||
const questionsLists = await ctx.prisma.questionsList.findMany({
|
||||
include: {
|
||||
questionEntries: {
|
||||
include: {
|
||||
question: {
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
answers: true,
|
||||
comments: true,
|
||||
},
|
||||
},
|
||||
encounters: {
|
||||
select: {
|
||||
company: true,
|
||||
location: true,
|
||||
role: true,
|
||||
seenAt: true,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'asc',
|
||||
},
|
||||
where: {
|
||||
userId,
|
||||
},
|
||||
});
|
||||
|
||||
const lists = questionsLists.map((list) => ({
|
||||
...list,
|
||||
questionEntries: list.questionEntries.map((entry) => ({
|
||||
...entry,
|
||||
question: createQuestionWithAggregateData(entry.question),
|
||||
})),
|
||||
}));
|
||||
|
||||
return lists;
|
||||
},
|
||||
})
|
||||
.query('getListById', {
|
||||
input: z.object({
|
||||
listId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
const { listId } = input;
|
||||
|
||||
const questionList = await ctx.prisma.questionsList.findFirst({
|
||||
include: {
|
||||
questionEntries: {
|
||||
include: {
|
||||
question: {
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
answers: true,
|
||||
comments: true,
|
||||
},
|
||||
},
|
||||
encounters: {
|
||||
select: {
|
||||
company: true,
|
||||
location: true,
|
||||
role: true,
|
||||
seenAt: true,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'asc',
|
||||
},
|
||||
where: {
|
||||
id: listId,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!questionList) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Question list not found',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...questionList,
|
||||
questionEntries: questionList.questionEntries.map((questionEntry) => ({
|
||||
...questionEntry,
|
||||
question: createQuestionWithAggregateData(questionEntry.question),
|
||||
})),
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation('create', {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const { name } = input;
|
||||
|
||||
return await ctx.prisma.questionsList.create({
|
||||
data: {
|
||||
name,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('update', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
name: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
const { name, id } = input;
|
||||
|
||||
const listToUpdate = await ctx.prisma.questionsList.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (listToUpdate?.id !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.questionsList.update({
|
||||
data: {
|
||||
name,
|
||||
},
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('delete', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const listToDelete = await ctx.prisma.questionsList.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (listToDelete?.userId !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.questionsList.delete({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('createQuestionEntry', {
|
||||
input: z.object({
|
||||
listId: z.string(),
|
||||
questionId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const listToAugment = await ctx.prisma.questionsList.findUnique({
|
||||
where: {
|
||||
id: input.listId,
|
||||
},
|
||||
});
|
||||
|
||||
if (listToAugment?.userId !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
const { questionId, listId } = input;
|
||||
|
||||
return await ctx.prisma.questionsListQuestionEntry.create({
|
||||
data: {
|
||||
listId,
|
||||
questionId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('deleteQuestionEntry', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const entryToDelete =
|
||||
await ctx.prisma.questionsListQuestionEntry.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (entryToDelete === null) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Entry not found.',
|
||||
});
|
||||
}
|
||||
|
||||
const listToAugment = await ctx.prisma.questionsList.findUnique({
|
||||
where: {
|
||||
id: entryToDelete.listId,
|
||||
},
|
||||
});
|
||||
|
||||
if (listToAugment?.userId !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.questionsListQuestionEntry.delete({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
@ -0,0 +1,437 @@
|
||||
import { z } from 'zod';
|
||||
import { QuestionsQuestionType, Vote } from '@prisma/client';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { createQuestionWithAggregateData } from '~/utils/questions/server/aggregate-encounters';
|
||||
|
||||
import { createProtectedRouter } from './context';
|
||||
|
||||
import { SortOrder, SortType } from '~/types/questions.d';
|
||||
|
||||
export const questionsQuestionRouter = createProtectedRouter()
|
||||
.query('getQuestionsByFilter', {
|
||||
input: z.object({
|
||||
companyNames: z.string().array(),
|
||||
cursor: z
|
||||
.object({
|
||||
idCursor: z.string().optional(),
|
||||
lastSeenCursor: z.date().nullish().optional(),
|
||||
upvoteCursor: z.number().optional(),
|
||||
})
|
||||
.nullish(),
|
||||
endDate: z.date().default(new Date()),
|
||||
limit: z.number().min(1).default(50),
|
||||
locations: z.string().array(),
|
||||
questionTypes: z.nativeEnum(QuestionsQuestionType).array(),
|
||||
roles: z.string().array(),
|
||||
sortOrder: z.nativeEnum(SortOrder),
|
||||
sortType: z.nativeEnum(SortType),
|
||||
startDate: z.date().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { cursor } = input;
|
||||
|
||||
const sortCondition =
|
||||
input.sortType === SortType.TOP
|
||||
? [
|
||||
{
|
||||
upvotes: input.sortOrder,
|
||||
},
|
||||
{
|
||||
id: input.sortOrder,
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
lastSeenAt: input.sortOrder,
|
||||
},
|
||||
{
|
||||
id: input.sortOrder,
|
||||
},
|
||||
];
|
||||
|
||||
const questionsData = await ctx.prisma.questionsQuestion.findMany({
|
||||
cursor:
|
||||
cursor !== undefined
|
||||
? {
|
||||
id: cursor ? cursor!.idCursor : undefined,
|
||||
}
|
||||
: undefined,
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
answers: true,
|
||||
comments: true,
|
||||
},
|
||||
},
|
||||
encounters: {
|
||||
select: {
|
||||
company: true,
|
||||
location: true,
|
||||
role: true,
|
||||
seenAt: true,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
orderBy: sortCondition,
|
||||
take: input.limit + 1,
|
||||
where: {
|
||||
...(input.questionTypes.length > 0
|
||||
? {
|
||||
questionType: {
|
||||
in: input.questionTypes,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
encounters: {
|
||||
some: {
|
||||
seenAt: {
|
||||
gte: input.startDate,
|
||||
lte: input.endDate,
|
||||
},
|
||||
...(input.companyNames.length > 0
|
||||
? {
|
||||
company: {
|
||||
name: {
|
||||
in: input.companyNames,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(input.locations.length > 0
|
||||
? {
|
||||
location: {
|
||||
in: input.locations,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(input.roles.length > 0
|
||||
? {
|
||||
role: {
|
||||
in: input.roles,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const processedQuestionsData = questionsData.map(
|
||||
createQuestionWithAggregateData,
|
||||
);
|
||||
|
||||
let nextCursor: typeof cursor | undefined = undefined;
|
||||
|
||||
if (questionsData.length > input.limit) {
|
||||
const nextItem = questionsData.pop()!;
|
||||
processedQuestionsData.pop();
|
||||
|
||||
const nextIdCursor: string | undefined = nextItem.id;
|
||||
const nextLastSeenCursor =
|
||||
input.sortType === SortType.NEW ? nextItem.lastSeenAt : undefined;
|
||||
const nextUpvoteCursor =
|
||||
input.sortType === SortType.TOP ? nextItem.upvotes : undefined;
|
||||
|
||||
nextCursor = {
|
||||
idCursor: nextIdCursor,
|
||||
lastSeenCursor: nextLastSeenCursor,
|
||||
upvoteCursor: nextUpvoteCursor,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
data: processedQuestionsData,
|
||||
nextCursor,
|
||||
};
|
||||
},
|
||||
})
|
||||
.query('getQuestionById', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const questionData = await ctx.prisma.questionsQuestion.findUnique({
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
answers: true,
|
||||
comments: true,
|
||||
},
|
||||
},
|
||||
encounters: {
|
||||
select: {
|
||||
company: true,
|
||||
location: true,
|
||||
role: true,
|
||||
seenAt: true,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
if (!questionData) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Question not found',
|
||||
});
|
||||
}
|
||||
|
||||
return createQuestionWithAggregateData(questionData);
|
||||
},
|
||||
})
|
||||
.mutation('create', {
|
||||
input: z.object({
|
||||
companyId: z.string(),
|
||||
content: z.string(),
|
||||
location: z.string(),
|
||||
questionType: z.nativeEnum(QuestionsQuestionType),
|
||||
role: z.string(),
|
||||
seenAt: z.date(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
return await ctx.prisma.questionsQuestion.create({
|
||||
data: {
|
||||
content: input.content,
|
||||
encounters: {
|
||||
create: {
|
||||
company: {
|
||||
connect: {
|
||||
id: input.companyId,
|
||||
},
|
||||
},
|
||||
location: input.location,
|
||||
role: input.role,
|
||||
seenAt: input.seenAt,
|
||||
user: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
lastSeenAt: input.seenAt,
|
||||
questionType: input.questionType,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('update', {
|
||||
input: z.object({
|
||||
content: z.string().optional(),
|
||||
id: z.string(),
|
||||
questionType: z.nativeEnum(QuestionsQuestionType).optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const questionToUpdate = await ctx.prisma.questionsQuestion.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (questionToUpdate?.id !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
// Optional: pass the original error to retain stack trace
|
||||
});
|
||||
}
|
||||
|
||||
const { content, questionType } = input;
|
||||
|
||||
return await ctx.prisma.questionsQuestion.update({
|
||||
data: {
|
||||
content,
|
||||
questionType,
|
||||
},
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('delete', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const questionToDelete = await ctx.prisma.questionsQuestion.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (questionToDelete?.id !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
// Optional: pass the original error to retain stack trace
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.questionsQuestion.delete({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.query('getVote', {
|
||||
input: z.object({
|
||||
questionId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
const { questionId } = input;
|
||||
|
||||
return await ctx.prisma.questionsQuestionVote.findUnique({
|
||||
where: {
|
||||
questionId_userId: { questionId, userId },
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('createVote', {
|
||||
input: z.object({
|
||||
questionId: z.string(),
|
||||
vote: z.nativeEnum(Vote),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
const { questionId, vote } = input;
|
||||
|
||||
const incrementValue = vote === Vote.UPVOTE ? 1 : -1;
|
||||
|
||||
const [questionVote] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.questionsQuestionVote.create({
|
||||
data: {
|
||||
questionId,
|
||||
userId,
|
||||
vote,
|
||||
},
|
||||
}),
|
||||
ctx.prisma.questionsQuestion.update({
|
||||
data: {
|
||||
upvotes: {
|
||||
increment: incrementValue,
|
||||
},
|
||||
},
|
||||
where: {
|
||||
id: questionId,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return questionVote;
|
||||
},
|
||||
})
|
||||
.mutation('updateVote', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
vote: z.nativeEnum(Vote),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
const { id, vote } = input;
|
||||
|
||||
const voteToUpdate = await ctx.prisma.questionsQuestionVote.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (voteToUpdate?.userId !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
const incrementValue = vote === Vote.UPVOTE ? 2 : -2;
|
||||
|
||||
const [questionVote] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.questionsQuestionVote.update({
|
||||
data: {
|
||||
vote,
|
||||
},
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
}),
|
||||
ctx.prisma.questionsQuestion.update({
|
||||
data: {
|
||||
upvotes: {
|
||||
increment: incrementValue,
|
||||
},
|
||||
},
|
||||
where: {
|
||||
id: voteToUpdate.questionId,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return questionVote;
|
||||
},
|
||||
})
|
||||
.mutation('deleteVote', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const voteToDelete = await ctx.prisma.questionsQuestionVote.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (voteToDelete?.userId !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
const incrementValue = voteToDelete.vote === Vote.UPVOTE ? -1 : 1;
|
||||
|
||||
const [questionVote] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.questionsQuestionVote.delete({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
}),
|
||||
ctx.prisma.questionsQuestion.update({
|
||||
data: {
|
||||
upvotes: {
|
||||
increment: incrementValue,
|
||||
},
|
||||
},
|
||||
where: {
|
||||
id: voteToDelete.questionId,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return questionVote;
|
||||
},
|
||||
});
|
@ -0,0 +1,102 @@
|
||||
import type {
|
||||
Company,
|
||||
QuestionsQuestion,
|
||||
QuestionsQuestionVote,
|
||||
} from '@prisma/client';
|
||||
import { Vote } from '@prisma/client';
|
||||
|
||||
import type { AggregatedQuestionEncounter, Question } from '~/types/questions';
|
||||
|
||||
type AggregatableEncounters = Array<{
|
||||
company: Company | null;
|
||||
location: string;
|
||||
role: string;
|
||||
seenAt: Date;
|
||||
}>;
|
||||
|
||||
type QuestionWithAggregatableData = QuestionsQuestion & {
|
||||
_count: {
|
||||
answers: number;
|
||||
comments: number;
|
||||
};
|
||||
encounters: AggregatableEncounters;
|
||||
user: {
|
||||
name: string | null;
|
||||
} | null;
|
||||
votes: Array<QuestionsQuestionVote>;
|
||||
};
|
||||
|
||||
export function createQuestionWithAggregateData(
|
||||
data: QuestionWithAggregatableData,
|
||||
): Question {
|
||||
const votes: number = data.votes.reduce(
|
||||
(previousValue: number, currentValue) => {
|
||||
let result: number = previousValue;
|
||||
|
||||
switch (currentValue.vote) {
|
||||
case Vote.UPVOTE:
|
||||
result += 1;
|
||||
break;
|
||||
case Vote.DOWNVOTE:
|
||||
result -= 1;
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
0,
|
||||
);
|
||||
|
||||
const question: Question = {
|
||||
aggregatedQuestionEncounters: createAggregatedQuestionEncounter(
|
||||
data.encounters,
|
||||
),
|
||||
content: data.content,
|
||||
id: data.id,
|
||||
numAnswers: data._count.answers,
|
||||
numComments: data._count.comments,
|
||||
numVotes: votes,
|
||||
receivedCount: data.encounters.length,
|
||||
seenAt: data.encounters[0].seenAt,
|
||||
type: data.questionType,
|
||||
updatedAt: data.updatedAt,
|
||||
user: data.user?.name ?? '',
|
||||
};
|
||||
return question;
|
||||
}
|
||||
|
||||
export function createAggregatedQuestionEncounter(
|
||||
encounters: AggregatableEncounters,
|
||||
): AggregatedQuestionEncounter {
|
||||
const companyCounts: Record<string, number> = {};
|
||||
const locationCounts: Record<string, number> = {};
|
||||
const roleCounts: Record<string, number> = {};
|
||||
|
||||
let latestSeenAt = encounters[0].seenAt;
|
||||
|
||||
for (const encounter of encounters) {
|
||||
latestSeenAt =
|
||||
latestSeenAt < encounter.seenAt ? encounter.seenAt : latestSeenAt;
|
||||
|
||||
if (!(encounter.company!.name in companyCounts)) {
|
||||
companyCounts[encounter.company!.name] = 0;
|
||||
}
|
||||
companyCounts[encounter.company!.name] += 1;
|
||||
|
||||
if (!(encounter.location in locationCounts)) {
|
||||
locationCounts[encounter.location] = 0;
|
||||
}
|
||||
locationCounts[encounter.location] += 1;
|
||||
|
||||
if (!(encounter.role in roleCounts)) {
|
||||
roleCounts[encounter.role] = 0;
|
||||
}
|
||||
roleCounts[encounter.role] += 1;
|
||||
}
|
||||
|
||||
return {
|
||||
companyCounts,
|
||||
latestSeenAt,
|
||||
locationCounts,
|
||||
roleCounts,
|
||||
};
|
||||
}
|
Loading…
Reference in new issue