commit
7381a3c83f
@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "QuestionsQuestion" ALTER COLUMN "lastSeenAt" DROP NOT NULL;
|
@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "ResumesResume" ADD COLUMN "isResolved" BOOLEAN NOT NULL DEFAULT false;
|
@ -0,0 +1,102 @@
|
||||
import { useRouter } from 'next/router';
|
||||
import Script from 'next/script';
|
||||
import { createContext, useContext, useEffect } from 'react';
|
||||
|
||||
type Context = Readonly<{
|
||||
event: (payload: GoogleAnalyticsEventPayload) => void;
|
||||
}>;
|
||||
|
||||
export const GoogleAnalyticsContext = createContext<Context>({
|
||||
event,
|
||||
});
|
||||
|
||||
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
|
||||
function pageview(measurementID: string, url: string) {
|
||||
// Don't log analytics during development.
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return;
|
||||
}
|
||||
|
||||
window.gtag('config', measurementID, {
|
||||
page_path: url,
|
||||
});
|
||||
|
||||
window.gtag('event', url, {
|
||||
event_category: 'pageview',
|
||||
event_label: document.title,
|
||||
});
|
||||
}
|
||||
|
||||
type GoogleAnalyticsEventPayload = Readonly<{
|
||||
action: string;
|
||||
category: string;
|
||||
label: string;
|
||||
value?: number;
|
||||
}>;
|
||||
|
||||
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
|
||||
export function event({
|
||||
action,
|
||||
category,
|
||||
label,
|
||||
value,
|
||||
}: GoogleAnalyticsEventPayload) {
|
||||
// Don't log analytics during development.
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return;
|
||||
}
|
||||
|
||||
window.gtag('event', action, {
|
||||
event_category: category,
|
||||
event_label: label,
|
||||
value,
|
||||
});
|
||||
}
|
||||
|
||||
type Props = Readonly<{
|
||||
children: React.ReactNode;
|
||||
measurementID: string;
|
||||
}>;
|
||||
|
||||
export function useGoogleAnalytics() {
|
||||
return useContext(GoogleAnalyticsContext);
|
||||
}
|
||||
|
||||
export default function GoogleAnalytics({ children, measurementID }: Props) {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
function handleRouteChange(url: string) {
|
||||
pageview(measurementID, url);
|
||||
}
|
||||
|
||||
router.events.on('routeChangeComplete', handleRouteChange);
|
||||
return () => {
|
||||
router.events.off('routeChangeComplete', handleRouteChange);
|
||||
};
|
||||
}, [router.events, measurementID]);
|
||||
|
||||
return (
|
||||
<GoogleAnalyticsContext.Provider value={{ event }}>
|
||||
{children}
|
||||
{/* Global Site Tag (gtag.js) - Google Analytics */}
|
||||
<Script
|
||||
src={`https://www.googletagmanager.com/gtag/js?id=${measurementID}`}
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
<Script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', '${measurementID}', {
|
||||
page_path: window.location.pathname,
|
||||
});
|
||||
`,
|
||||
}}
|
||||
id="gtag-init"
|
||||
strategy="afterInteractive"
|
||||
/>
|
||||
</GoogleAnalyticsContext.Provider>
|
||||
);
|
||||
}
|
@ -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,5 @@
|
||||
import OffersSubmissionForm from '~/components/offers/offersSubmission/OffersSubmissionForm';
|
||||
|
||||
export default function OffersSubmissionPage() {
|
||||
return <OffersSubmissionForm />;
|
||||
}
|
@ -0,0 +1,123 @@
|
||||
import { useRouter } from 'next/router';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/20/solid';
|
||||
import { EyeIcon } from '@heroicons/react/24/outline';
|
||||
import { Button, Spinner } from '@tih/ui';
|
||||
|
||||
import type { BreadcrumbStep } from '~/components/offers/Breadcrumb';
|
||||
import { Breadcrumbs } from '~/components/offers/Breadcrumb';
|
||||
import OffersProfileSave from '~/components/offers/offersSubmission/OffersProfileSave';
|
||||
import OffersSubmissionAnalysis from '~/components/offers/offersSubmission/OffersSubmissionAnalysis';
|
||||
|
||||
import { getProfilePath } from '~/utils/offers/link';
|
||||
import { trpc } from '~/utils/trpc';
|
||||
|
||||
import type { ProfileAnalysis } from '~/types/offers';
|
||||
|
||||
export default function OffersSubmissionResult() {
|
||||
const router = useRouter();
|
||||
let { offerProfileId, token = '' } = router.query;
|
||||
offerProfileId = offerProfileId as string;
|
||||
token = token as string;
|
||||
const [step, setStep] = useState(0);
|
||||
const [analysis, setAnalysis] = useState<ProfileAnalysis | null>(null);
|
||||
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const scrollToTop = () =>
|
||||
pageRef.current?.scrollTo({ behavior: 'smooth', top: 0 });
|
||||
|
||||
// TODO: Check if the token is valid before showing this page
|
||||
const getAnalysis = trpc.useQuery(
|
||||
['offers.analysis.get', { profileId: offerProfileId }],
|
||||
{
|
||||
onSuccess(data) {
|
||||
setAnalysis(data);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const steps = [
|
||||
<OffersProfileSave key={0} profileId={offerProfileId} token={token} />,
|
||||
<OffersSubmissionAnalysis
|
||||
key={1}
|
||||
analysis={analysis}
|
||||
isError={getAnalysis.isError}
|
||||
isLoading={getAnalysis.isLoading}
|
||||
/>,
|
||||
];
|
||||
|
||||
const breadcrumbSteps: Array<BreadcrumbStep> = [
|
||||
{
|
||||
label: 'Offers',
|
||||
},
|
||||
{
|
||||
label: 'Background',
|
||||
},
|
||||
{
|
||||
label: 'Save profile',
|
||||
step: 0,
|
||||
},
|
||||
{
|
||||
label: 'Analysis',
|
||||
step: 1,
|
||||
},
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
scrollToTop();
|
||||
}, [step]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{getAnalysis.isLoading && (
|
||||
<Spinner className="m-10" display="block" size="lg" />
|
||||
)}
|
||||
{!getAnalysis.isLoading && (
|
||||
<div ref={pageRef} className="fixed h-full w-full overflow-y-scroll">
|
||||
<div className="mb-20 flex justify-center">
|
||||
<div className="my-5 block w-full max-w-screen-md rounded-lg bg-white py-10 px-10 shadow-lg">
|
||||
<div className="mb-4 flex justify-end">
|
||||
<Breadcrumbs
|
||||
currentStep={step}
|
||||
setStep={setStep}
|
||||
steps={breadcrumbSteps}
|
||||
/>
|
||||
</div>
|
||||
{steps[step]}
|
||||
{step === 0 && (
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
disabled={false}
|
||||
icon={ArrowRightIcon}
|
||||
label="Next"
|
||||
variant="secondary"
|
||||
onClick={() => setStep(step + 1)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{step === 1 && (
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
icon={ArrowLeftIcon}
|
||||
label="Previous"
|
||||
variant="secondary"
|
||||
onClick={() => setStep(step - 1)}
|
||||
/>
|
||||
<Button
|
||||
href={getProfilePath(
|
||||
offerProfileId as string,
|
||||
token as string,
|
||||
)}
|
||||
icon={EyeIcon}
|
||||
label="View your profile"
|
||||
variant="primary"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
export default function AboutUsPage() {
|
||||
return (
|
||||
<div className="my-10 flex w-full flex-col items-center overflow-y-auto">
|
||||
<div className="flex justify-center text-4xl font-bold">
|
||||
Resume Review Portal
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex justify-center text-2xl font-bold">
|
||||
<div className="font-display sm:text-md mx-auto max-w-xl text-2xl font-medium italic tracking-tight text-slate-900">
|
||||
Resume reviews{' '}
|
||||
<span className="text-primary-500 relative whitespace-nowrap">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="absolute top-2/3 left-0 h-[0.58em] w-full fill-blue-300/70"
|
||||
preserveAspectRatio="none"
|
||||
viewBox="0 0 418 42">
|
||||
<path d="M203.371.916c-26.013-2.078-76.686 1.963-124.73 9.946L67.3 12.749C35.421 18.062 18.2 21.766 6.004 25.934 1.244 27.561.828 27.778.874 28.61c.07 1.214.828 1.121 9.595-1.176 9.072-2.377 17.15-3.92 39.246-7.496C123.565 7.986 157.869 4.492 195.942 5.046c7.461.108 19.25 1.696 19.17 2.582-.107 1.183-7.874 4.31-25.75 10.366-21.992 7.45-35.43 12.534-36.701 13.884-2.173 2.308-.202 4.407 4.442 4.734 2.654.187 3.263.157 15.593-.78 35.401-2.686 57.944-3.488 88.365-3.143 46.327.526 75.721 2.23 130.788 7.584 19.787 1.924 20.814 1.98 24.557 1.332l.066-.011c1.201-.203 1.53-1.825.399-2.335-2.911-1.31-4.893-1.604-22.048-3.261-57.509-5.556-87.871-7.36-132.059-7.842-23.239-.254-33.617-.116-50.627.674-11.629.54-42.371 2.494-46.696 2.967-2.359.259 8.133-3.625 26.504-9.81 23.239-7.825 27.934-10.149 28.304-14.005.417-4.348-3.529-6-16.878-7.066Z" />
|
||||
</svg>
|
||||
<span className="relative">made simple</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* About Us Section */}
|
||||
<div className="mt-10 flex w-4/5 text-left text-3xl font-bold xl:w-1/2">
|
||||
About Us 🤓
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex w-4/5 text-lg xl:w-1/2">
|
||||
As you apply for your dream jobs or internships, have you ever felt
|
||||
unsure about your resume? Have you wondered about how others got past
|
||||
resume screening in a breeze? Wonder no more!
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex w-4/5 text-lg xl:w-1/2">
|
||||
Tech Interview Handbook's very own Resume Review portal is here to help!
|
||||
Simply submit your resume and collect invaluable feedback from our
|
||||
community of Software Engineers, Hiring Managers and so many more...
|
||||
</div>
|
||||
|
||||
{/* Feedback */}
|
||||
<div className="mt-10 flex w-4/5 text-left text-3xl font-bold xl:w-1/2">
|
||||
Feedback? New Features? BUGS?! 😱
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex w-4/5 text-lg xl:w-1/2">
|
||||
Submit your feedback
|
||||
<a
|
||||
className="ml-1 text-indigo-600 hover:text-indigo-400"
|
||||
href="https://forms.gle/KgA6KWDD4XNa53uJA"
|
||||
rel="noreferrer"
|
||||
target="_blank">
|
||||
here
|
||||
</a>
|
||||
.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,131 @@
|
||||
import { z } from 'zod';
|
||||
import * as trpc from '@trpc/server';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import {
|
||||
addToProfileResponseMapper, getUserProfileResponseMapper,
|
||||
} from '~/mappers/offers-mappers';
|
||||
|
||||
import { createProtectedRouter } from '../context';
|
||||
|
||||
export const offersUserProfileRouter = createProtectedRouter()
|
||||
.mutation('addToUserProfile', {
|
||||
input: z.object({
|
||||
profileId: z.string(),
|
||||
token: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const profile = await ctx.prisma.offersProfile.findFirst({
|
||||
where: {
|
||||
id: input.profileId,
|
||||
},
|
||||
});
|
||||
|
||||
const profileEditToken = profile?.editToken;
|
||||
if (profileEditToken === input.token) {
|
||||
|
||||
const userId = ctx.session.user.id
|
||||
const updated = await ctx.prisma.offersProfile.update({
|
||||
data: {
|
||||
user: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
where: {
|
||||
id: input.profileId,
|
||||
},
|
||||
});
|
||||
|
||||
return addToProfileResponseMapper(updated);
|
||||
}
|
||||
|
||||
throw new trpc.TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'Invalid token.',
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('getUserProfiles', {
|
||||
async resolve({ ctx }) {
|
||||
const userId = ctx.session.user.id
|
||||
const result = await ctx.prisma.user.findFirst({
|
||||
include: {
|
||||
OffersProfile: {
|
||||
include: {
|
||||
offers: {
|
||||
include: {
|
||||
company: true,
|
||||
offersFullTime: {
|
||||
include: {
|
||||
totalCompensation: true
|
||||
}
|
||||
},
|
||||
offersIntern: {
|
||||
include: {
|
||||
monthlySalary: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
where: {
|
||||
id: userId
|
||||
}
|
||||
})
|
||||
|
||||
return getUserProfileResponseMapper(result)
|
||||
}
|
||||
})
|
||||
.mutation('removeFromUserProfile', {
|
||||
input: z.object({
|
||||
profileId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session.user.id
|
||||
|
||||
const profiles = await ctx.prisma.user.findFirst({
|
||||
include: {
|
||||
OffersProfile: true
|
||||
},
|
||||
where: {
|
||||
id: userId
|
||||
}
|
||||
})
|
||||
|
||||
// Validation
|
||||
let doesProfileExist = false;
|
||||
|
||||
if (profiles?.OffersProfile) {
|
||||
for (let i = 0; i < profiles.OffersProfile.length; i++) {
|
||||
if (profiles.OffersProfile[i].id === input.profileId) {
|
||||
doesProfileExist = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!doesProfileExist) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'No such profile id saved.'
|
||||
})
|
||||
}
|
||||
|
||||
await ctx.prisma.user.update({
|
||||
data: {
|
||||
OffersProfile: {
|
||||
disconnect: [{
|
||||
id: input.profileId
|
||||
}]
|
||||
}
|
||||
},
|
||||
where: {
|
||||
id: userId
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
})
|
@ -1,141 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { createProtectedRouter } from './context';
|
||||
|
||||
import type { AggregatedQuestionEncounter } from '~/types/questions';
|
||||
|
||||
export const questionsQuestionEncounterRouter = createProtectedRouter()
|
||||
.query('getAggregatedEncounters', {
|
||||
input: z.object({
|
||||
questionId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const questionEncountersData =
|
||||
await ctx.prisma.questionsQuestionEncounter.findMany({
|
||||
include: {
|
||||
company: true,
|
||||
},
|
||||
where: {
|
||||
...input,
|
||||
},
|
||||
});
|
||||
|
||||
const companyCounts: Record<string, number> = {};
|
||||
const locationCounts: Record<string, number> = {};
|
||||
const roleCounts: Record<string, number> = {};
|
||||
|
||||
let latestSeenAt = questionEncountersData[0].seenAt;
|
||||
|
||||
for (let i = 0; i < questionEncountersData.length; i++) {
|
||||
const encounter = questionEncountersData[i];
|
||||
|
||||
latestSeenAt = latestSeenAt < encounter.seenAt ? encounter.seenAt : latestSeenAt;
|
||||
|
||||
if (!(encounter.company!.name in companyCounts)) {
|
||||
companyCounts[encounter.company!.name] = 1;
|
||||
}
|
||||
companyCounts[encounter.company!.name] += 1;
|
||||
|
||||
if (!(encounter.location in locationCounts)) {
|
||||
locationCounts[encounter.location] = 1;
|
||||
}
|
||||
locationCounts[encounter.location] += 1;
|
||||
|
||||
if (!(encounter.role in roleCounts)) {
|
||||
roleCounts[encounter.role] = 1;
|
||||
}
|
||||
roleCounts[encounter.role] += 1;
|
||||
}
|
||||
|
||||
const questionEncounter: AggregatedQuestionEncounter = {
|
||||
companyCounts,
|
||||
latestSeenAt,
|
||||
locationCounts,
|
||||
roleCounts,
|
||||
};
|
||||
return questionEncounter;
|
||||
},
|
||||
})
|
||||
.mutation('create', {
|
||||
input: z.object({
|
||||
companyId: z.string(),
|
||||
location: z.string(),
|
||||
questionId: z.string(),
|
||||
role: z.string(),
|
||||
seenAt: z.date(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
return await ctx.prisma.questionsQuestionEncounter.create({
|
||||
data: {
|
||||
...input,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('update', {
|
||||
input: z.object({
|
||||
companyId: z.string().optional(),
|
||||
id: z.string(),
|
||||
location: z.string().optional(),
|
||||
role: z.string().optional(),
|
||||
seenAt: z.date().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const questionEncounterToUpdate =
|
||||
await ctx.prisma.questionsQuestionEncounter.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (questionEncounterToUpdate?.id !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.questionsQuestionEncounter.update({
|
||||
data: {
|
||||
...input,
|
||||
},
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('delete', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const questionEncounterToDelete =
|
||||
await ctx.prisma.questionsQuestionEncounter.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (questionEncounterToDelete?.id !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.questionsQuestionEncounter.delete({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
@ -0,0 +1,64 @@
|
||||
import { z } from 'zod';
|
||||
import { Vote } from '@prisma/client';
|
||||
|
||||
import { createRouter } from '../context';
|
||||
|
||||
import type { AnswerComment } from '~/types/questions';
|
||||
|
||||
export const questionsAnswerCommentRouter = createRouter().query(
|
||||
'getAnswerComments',
|
||||
{
|
||||
input: z.object({
|
||||
answerId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const questionAnswerCommentsData =
|
||||
await ctx.prisma.questionsAnswerComment.findMany({
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
image: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
where: {
|
||||
answerId: input.answerId,
|
||||
},
|
||||
});
|
||||
return questionAnswerCommentsData.map((data) => {
|
||||
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 answerComment: AnswerComment = {
|
||||
content: data.content,
|
||||
createdAt: data.createdAt,
|
||||
id: data.id,
|
||||
numVotes: votes,
|
||||
updatedAt: data.updatedAt,
|
||||
user: data.user?.name ?? '',
|
||||
userImage: data.user?.image ?? '',
|
||||
};
|
||||
return answerComment;
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
@ -0,0 +1,128 @@
|
||||
import { z } from 'zod';
|
||||
import { Vote } from '@prisma/client';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { createRouter } from '../context';
|
||||
|
||||
import type { Answer } from '~/types/questions';
|
||||
|
||||
export const questionsAnswerRouter = createRouter()
|
||||
.query('getAnswers', {
|
||||
input: z.object({
|
||||
questionId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { questionId } = input;
|
||||
|
||||
const answersData = await ctx.prisma.questionsAnswer.findMany({
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
comments: true,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
image: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
where: {
|
||||
questionId,
|
||||
},
|
||||
});
|
||||
return answersData.map((data) => {
|
||||
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 answer: Answer = {
|
||||
content: data.content,
|
||||
createdAt: data.createdAt,
|
||||
id: data.id,
|
||||
numComments: data._count.comments,
|
||||
numVotes: votes,
|
||||
user: data.user?.name ?? '',
|
||||
userImage: data.user?.image ?? '',
|
||||
};
|
||||
return answer;
|
||||
});
|
||||
},
|
||||
})
|
||||
.query('getAnswerById', {
|
||||
input: z.object({
|
||||
answerId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const answerData = await ctx.prisma.questionsAnswer.findUnique({
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
comments: true,
|
||||
},
|
||||
},
|
||||
user: {
|
||||
select: {
|
||||
image: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
where: {
|
||||
id: input.answerId,
|
||||
},
|
||||
});
|
||||
if (!answerData) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Answer not found',
|
||||
});
|
||||
}
|
||||
const votes: number = answerData.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 answer: Answer = {
|
||||
content: answerData.content,
|
||||
createdAt: answerData.createdAt,
|
||||
id: answerData.id,
|
||||
numComments: answerData._count.comments,
|
||||
numVotes: votes,
|
||||
user: answerData.user?.name ?? '',
|
||||
userImage: answerData.user?.image ?? '',
|
||||
};
|
||||
return answer;
|
||||
},
|
||||
});
|
@ -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,64 @@
|
||||
import { z } from 'zod';
|
||||
import { Vote } from '@prisma/client';
|
||||
|
||||
import { createRouter } from '../context';
|
||||
|
||||
import type { QuestionComment } from '~/types/questions';
|
||||
|
||||
export const questionsQuestionCommentRouter = createRouter().query(
|
||||
'getQuestionComments',
|
||||
{
|
||||
input: z.object({
|
||||
questionId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { questionId } = input;
|
||||
const questionCommentsData =
|
||||
await ctx.prisma.questionsQuestionComment.findMany({
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
image: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
votes: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
where: {
|
||||
questionId,
|
||||
},
|
||||
});
|
||||
return questionCommentsData.map((data) => {
|
||||
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 questionComment: QuestionComment = {
|
||||
content: data.content,
|
||||
createdAt: data.createdAt,
|
||||
id: data.id,
|
||||
numVotes: votes,
|
||||
user: data.user?.name ?? '',
|
||||
userImage: data.user?.image ?? '',
|
||||
};
|
||||
return questionComment;
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
@ -0,0 +1,61 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { createRouter } from '../context';
|
||||
|
||||
import type { AggregatedQuestionEncounter } from '~/types/questions';
|
||||
|
||||
export const questionsQuestionEncounterRouter = createRouter().query(
|
||||
'getAggregatedEncounters',
|
||||
{
|
||||
input: z.object({
|
||||
questionId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const questionEncountersData =
|
||||
await ctx.prisma.questionsQuestionEncounter.findMany({
|
||||
include: {
|
||||
company: true,
|
||||
},
|
||||
where: {
|
||||
...input,
|
||||
},
|
||||
});
|
||||
|
||||
const companyCounts: Record<string, number> = {};
|
||||
const locationCounts: Record<string, number> = {};
|
||||
const roleCounts: Record<string, number> = {};
|
||||
|
||||
let latestSeenAt = questionEncountersData[0].seenAt;
|
||||
|
||||
for (let i = 0; i < questionEncountersData.length; i++) {
|
||||
const encounter = questionEncountersData[i];
|
||||
|
||||
latestSeenAt =
|
||||
latestSeenAt < encounter.seenAt ? encounter.seenAt : latestSeenAt;
|
||||
|
||||
if (!(encounter.company!.name in companyCounts)) {
|
||||
companyCounts[encounter.company!.name] = 1;
|
||||
}
|
||||
companyCounts[encounter.company!.name] += 1;
|
||||
|
||||
if (!(encounter.location in locationCounts)) {
|
||||
locationCounts[encounter.location] = 1;
|
||||
}
|
||||
locationCounts[encounter.location] += 1;
|
||||
|
||||
if (!(encounter.role in roleCounts)) {
|
||||
roleCounts[encounter.role] = 1;
|
||||
}
|
||||
roleCounts[encounter.role] += 1;
|
||||
}
|
||||
|
||||
const questionEncounter: AggregatedQuestionEncounter = {
|
||||
companyCounts,
|
||||
latestSeenAt,
|
||||
locationCounts,
|
||||
roleCounts,
|
||||
};
|
||||
return questionEncounter;
|
||||
},
|
||||
},
|
||||
);
|
@ -0,0 +1,207 @@
|
||||
import { z } from 'zod';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { createAggregatedQuestionEncounter } from '~/utils/questions/server/aggregate-encounters';
|
||||
|
||||
import { createProtectedRouter } from '../context';
|
||||
|
||||
import { SortOrder } from '~/types/questions.d';
|
||||
|
||||
export const questionsQuestionEncounterUserRouter = createProtectedRouter()
|
||||
.query('getAggregatedEncounters', {
|
||||
input: z.object({
|
||||
questionId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const questionEncountersData =
|
||||
await ctx.prisma.questionsQuestionEncounter.findMany({
|
||||
include: {
|
||||
company: true,
|
||||
},
|
||||
where: {
|
||||
...input,
|
||||
},
|
||||
});
|
||||
|
||||
return createAggregatedQuestionEncounter(questionEncountersData);
|
||||
},
|
||||
})
|
||||
.mutation('create', {
|
||||
input: z.object({
|
||||
companyId: z.string(),
|
||||
location: z.string(),
|
||||
questionId: z.string(),
|
||||
role: z.string(),
|
||||
seenAt: z.date(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
return await ctx.prisma.$transaction(async (tx) => {
|
||||
const [questionToUpdate, questionEncounterCreated] = await Promise.all([
|
||||
tx.questionsQuestion.findUnique({
|
||||
where: {
|
||||
id: input.questionId,
|
||||
},
|
||||
}),
|
||||
tx.questionsQuestionEncounter.create({
|
||||
data: {
|
||||
...input,
|
||||
userId,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
if (questionToUpdate === null) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Question does not exist',
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
questionToUpdate.lastSeenAt === null ||
|
||||
questionToUpdate.lastSeenAt < input.seenAt
|
||||
) {
|
||||
await tx.questionsQuestion.update({
|
||||
data: {
|
||||
lastSeenAt: input.seenAt,
|
||||
},
|
||||
where: {
|
||||
id: input.questionId,
|
||||
},
|
||||
});
|
||||
}
|
||||
return questionEncounterCreated;
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('update', {
|
||||
input: z.object({
|
||||
companyId: z.string().optional(),
|
||||
id: z.string(),
|
||||
location: z.string().optional(),
|
||||
role: z.string().optional(),
|
||||
seenAt: z.date().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const questionEncounterToUpdate =
|
||||
await ctx.prisma.questionsQuestionEncounter.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (questionEncounterToUpdate?.id !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.$transaction(async (tx) => {
|
||||
const [questionToUpdate, questionEncounterUpdated] = await Promise.all([
|
||||
tx.questionsQuestion.findUnique({
|
||||
where: {
|
||||
id: questionEncounterToUpdate.questionId,
|
||||
},
|
||||
}),
|
||||
tx.questionsQuestionEncounter.update({
|
||||
data: {
|
||||
...input,
|
||||
},
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
if (questionToUpdate!.lastSeenAt === questionEncounterToUpdate.seenAt) {
|
||||
const latestEncounter =
|
||||
await ctx.prisma.questionsQuestionEncounter.findFirst({
|
||||
orderBy: {
|
||||
seenAt: SortOrder.DESC,
|
||||
},
|
||||
where: {
|
||||
questionId: questionToUpdate!.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.questionsQuestion.update({
|
||||
data: {
|
||||
lastSeenAt: latestEncounter!.seenAt,
|
||||
},
|
||||
where: {
|
||||
id: questionToUpdate!.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return questionEncounterUpdated;
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation('delete', {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const userId = ctx.session?.user?.id;
|
||||
|
||||
const questionEncounterToDelete =
|
||||
await ctx.prisma.questionsQuestionEncounter.findUnique({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (questionEncounterToDelete?.id !== userId) {
|
||||
throw new TRPCError({
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User have no authorization to record.',
|
||||
});
|
||||
}
|
||||
|
||||
return await ctx.prisma.$transaction(async (tx) => {
|
||||
const [questionToUpdate, questionEncounterDeleted] = await Promise.all([
|
||||
tx.questionsQuestion.findUnique({
|
||||
where: {
|
||||
id: questionEncounterToDelete.questionId,
|
||||
},
|
||||
}),
|
||||
tx.questionsQuestionEncounter.delete({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
if (questionToUpdate!.lastSeenAt === questionEncounterToDelete.seenAt) {
|
||||
const latestEncounter =
|
||||
await ctx.prisma.questionsQuestionEncounter.findFirst({
|
||||
orderBy: {
|
||||
seenAt: SortOrder.DESC,
|
||||
},
|
||||
where: {
|
||||
questionId: questionToUpdate!.id,
|
||||
},
|
||||
});
|
||||
|
||||
const lastSeenVal = latestEncounter ? latestEncounter!.seenAt : null;
|
||||
|
||||
await tx.questionsQuestion.update({
|
||||
data: {
|
||||
lastSeenAt: lastSeenVal,
|
||||
},
|
||||
where: {
|
||||
id: questionToUpdate!.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return questionEncounterDeleted;
|
||||
});
|
||||
},
|
||||
});
|
@ -0,0 +1,196 @@
|
||||
import { z } from 'zod';
|
||||
import { QuestionsQuestionType } from '@prisma/client';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { createQuestionWithAggregateData } from '~/utils/questions/server/aggregate-encounters';
|
||||
|
||||
import { createRouter } from '../context';
|
||||
|
||||
import { SortOrder, SortType } from '~/types/questions.d';
|
||||
|
||||
export const questionsQuestionRouter = createRouter()
|
||||
.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);
|
||||
},
|
||||
});
|
@ -0,0 +1,248 @@
|
||||
import { z } from 'zod';
|
||||
import { QuestionsQuestionType, Vote } from '@prisma/client';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { createProtectedRouter } from '../context';
|
||||
|
||||
export const questionsQuestionUserRouter = createProtectedRouter()
|
||||
.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,9 @@
|
||||
export {};
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
||||
interface Window {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
gtag: any;
|
||||
}
|
||||
}
|
@ -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,
|
||||
};
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
import { useRouter } from 'next/router';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export const useSearchParams = <T>(name: string, defaultValue: T) => {
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const [filters, setFilters] = useState(defaultValue);
|
||||
|
||||
useEffect(() => {
|
||||
if (router.isReady && !isInitialized) {
|
||||
// Initialize from url query params
|
||||
const query = router.query[name];
|
||||
if (query) {
|
||||
const parsedQuery =
|
||||
typeof query === 'string' ? JSON.parse(query) : query;
|
||||
setFilters(parsedQuery);
|
||||
}
|
||||
setIsInitialized(true);
|
||||
}
|
||||
}, [isInitialized, name, router]);
|
||||
|
||||
return [filters, setFilters, isInitialized] as const;
|
||||
};
|
||||
|
||||
export default useSearchParams;
|
@ -0,0 +1,53 @@
|
||||
import React, { useState } from 'react';
|
||||
import type { ComponentMeta } from '@storybook/react';
|
||||
import type { BannerSize } from '@tih/ui';
|
||||
import { Banner } from '@tih/ui';
|
||||
|
||||
const bannerSizes: ReadonlyArray<BannerSize> = ['xs', 'sm', 'md'];
|
||||
|
||||
export default {
|
||||
argTypes: {
|
||||
children: {
|
||||
control: 'text',
|
||||
},
|
||||
size: {
|
||||
control: { type: 'select' },
|
||||
options: bannerSizes,
|
||||
},
|
||||
},
|
||||
component: Banner,
|
||||
title: 'Banner',
|
||||
} as ComponentMeta<typeof Banner>;
|
||||
|
||||
export const Basic = {
|
||||
args: {
|
||||
children: 'This notice is going to change your life',
|
||||
size: 'md',
|
||||
},
|
||||
};
|
||||
|
||||
export function Sizes() {
|
||||
const [isShown, setIsShown] = useState(true);
|
||||
const [isShown2, setIsShown2] = useState(true);
|
||||
const [isShown3, setIsShown3] = useState(true);
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{isShown && (
|
||||
<Banner onHide={() => setIsShown(false)}>
|
||||
This notice is going to change your life unless you close it.
|
||||
</Banner>
|
||||
)}
|
||||
{isShown2 && (
|
||||
<Banner size="sm" onHide={() => setIsShown2(false)}>
|
||||
This smaller notice is going to change your life unless you close it.
|
||||
</Banner>
|
||||
)}
|
||||
{isShown3 && (
|
||||
<Banner size="xs" onHide={() => setIsShown3(false)}>
|
||||
This even smaller notice is going to change your life unless you close
|
||||
it.
|
||||
</Banner>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
import clsx from 'clsx';
|
||||
import React from 'react';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export type BannerSize = 'md' | 'sm' | 'xs';
|
||||
|
||||
type Props = Readonly<{
|
||||
children: React.ReactNode;
|
||||
onHide?: () => void;
|
||||
size?: BannerSize;
|
||||
}>;
|
||||
|
||||
export default function Banner({ children, size = 'md', onHide }: Props) {
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
'bg-primary-600 relative',
|
||||
size === 'sm' && 'text-sm',
|
||||
size === 'xs' && 'text-xs',
|
||||
)}>
|
||||
<div className="mx-auto max-w-7xl py-3 px-3 sm:px-6 lg:px-8">
|
||||
<div className="pr-16 sm:px-16 sm:text-center">
|
||||
<p className="font-medium text-white">{children}</p>
|
||||
</div>
|
||||
{onHide != null && (
|
||||
<div
|
||||
className={clsx(
|
||||
'absolute inset-y-0 right-0 flex items-start sm:items-start',
|
||||
size === 'md' && 'pt-2 pr-2',
|
||||
size === 'sm' && 'pt-2 pr-2',
|
||||
size === 'xs' && 'pt-1.5 pr-2',
|
||||
)}>
|
||||
<button
|
||||
className={clsx(
|
||||
'hover:bg-primary-400 flex rounded-md focus:outline-none focus:ring-2 focus:ring-white',
|
||||
size === 'md' && 'p-1',
|
||||
size === 'sm' && 'p-0.5',
|
||||
size === 'xs' && 'p-0.5',
|
||||
)}
|
||||
type="button"
|
||||
onClick={onHide}>
|
||||
<span className="sr-only">Dismiss</span>
|
||||
<XMarkIcon aria-hidden="true" className="h-6 w-6 text-white" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
Loading…
Reference in new issue