Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
Switch to tRPC (#173)
Luke Vella2c4157ea244a
diff --git a/README.md b/README.mdindex 3aeb08557..232b66f2d 100644--- a/README.md+++ b/README.md@@ -74,16 +74,17 @@ yarn start## ⚙️ Configuration-| Parameter | Default | Description |-| --------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |-| DATABASE_URL | postgres://postgres:postgres@rallly_db:5432/db | A postgres database URL. Leave out if using the docker-compose file since it will spin up and connect to its own database instance. |-| SECRET_PASSWORD | - | A long string (minimum 32 characters) that is used to encrypt session data. |-| SUPPORT_EMAIL | - | An email address that will appear as the FROM email for all emails being sent out. |-| SMTP_HOST | - | Host name of your SMTP server |-| SMTP_PORT | - | Port of your SMTP server |-| SMTP_SECURE | false | Set to "true" if SSL is enabled for your SMTP connection |-| SMTP_USER | - | Username to use for your SMTP connection |-| SMTP_PWD | - | Password to use for your SMTP connection |+| Parameter | Default | Description |+| -------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |+| NEXT_PUBLIC_BASE_URL | http://localhost:3000 | The hosting url of the server, used for creating links and making api calls from the client. |+| DATABASE_URL | postgres://postgres:postgres@rallly_db:5432/db | A postgres database URL. Leave out if using the docker-compose file since it will spin up and connect to its own database instance. |+| SECRET_PASSWORD | - | A long string (minimum 32 characters) that is used to encrypt session data. |+| SUPPORT_EMAIL | - | An email address that will appear as the FROM email for all emails being sent out. |+| SMTP_HOST | - | Host name of your SMTP server |+| SMTP_PORT | - | Port of your SMTP server |+| SMTP_SECURE | false | Set to "true" if SSL is enabled for your SMTP connection |+| SMTP_USER | - | Username to use for your SMTP connection |+| SMTP_PWD | - | Password to use for your SMTP connection |## 👨💻 Contributorsdiff --git a/api-client/add-participant.ts b/api-client/add-participant.tsdeleted file mode 100644index 535eea1de..000000000--- a/api-client/add-participant.ts+++ /dev/null@@ -1,23 +0,0 @@-import { Participant, Vote, VoteType } from "@prisma/client";-import axios from "axios";--export interface AddParticipantPayload {- pollId: string;- name: string;- votes: Array<{ optionId: string; type: VoteType }>;-}--export type AddParticipantResponse = Participant & {- votes: Vote[];-};--export const addParticipant = async (- payload: AddParticipantPayload,-): Promise<AddParticipantResponse> => {- const res = await axios.post<AddParticipantResponse>(- `/api/poll/${payload.pollId}/participant`,- payload,- );-- return res.data;-};diff --git a/api-client/create-comment.ts b/api-client/create-comment.tsdeleted file mode 100644index bc0b99783..000000000--- a/api-client/create-comment.ts+++ /dev/null@@ -1,18 +0,0 @@-import { Comment } from "@prisma/client";-import axios from "axios";--export interface CreateCommentPayload {- pollId: string;- content: string;- authorName: string;-}--export const createComment = async (- payload: CreateCommentPayload,-): Promise<Comment> => {- const { data } = await axios.post<Comment>(- `/api/poll/${payload.pollId}/comments`,- payload,- );- return data;-};diff --git a/api-client/create-demo.ts b/api-client/create-demo.tsdeleted file mode 100644index 785d68d01..000000000--- a/api-client/create-demo.ts+++ /dev/null@@ -1,7 +0,0 @@-import { Poll } from "@prisma/client";-import axios from "axios";--export const createDemo = async (): Promise<Poll> => {- const { data } = await axios.post<Poll>("/api/poll/demo");- return data;-};diff --git a/api-client/create-poll.ts b/api-client/create-poll.tsdeleted file mode 100644index 3aab17080..000000000--- a/api-client/create-poll.ts+++ /dev/null@@ -1,21 +0,0 @@-import { Poll } from "@prisma/client";-import axios from "axios";--export interface CreatePollPayload {- title: string;- type: "date";- timeZone?: string;- location?: string;- description?: string;- user: {- name: string;- email: string;- };- options: string[];- demo?: boolean;-}--export const createPoll = async (payload: CreatePollPayload): Promise<Poll> => {- const { data } = await axios.post<Poll>("/api/poll", payload);- return data;-};diff --git a/api-client/delete-participant.ts b/api-client/delete-participant.tsdeleted file mode 100644index b3e2715b9..000000000--- a/api-client/delete-participant.ts+++ /dev/null@@ -1,17 +0,0 @@-import axios from "axios";--export interface DeleteParticipantPayload {- pollId: string;- participantId: string;-}--export const deleteParticipant = async (- payload: DeleteParticipantPayload,-): Promise<void> => {- try {- const { pollId, participantId } = payload;- await axios.delete(`/api/poll/${pollId}/participant/${participantId}`);- } catch (err) {- throw err;- }-};diff --git a/api-client/get-poll.ts b/api-client/get-poll.tsdeleted file mode 100644index b1b3ba357..000000000--- a/api-client/get-poll.ts+++ /dev/null@@ -1,14 +0,0 @@-import { Link, Option, Participant, Poll, User, Vote } from "@prisma/client";--export interface GetPollApiResponse extends Omit<Poll, "verificationCode"> {- options: Option[];- participants: Array<Participant & { votes: Vote[] }>;- user: User;- role: "admin" | "participant";- links: Array<Link>;- pollId: string;-}--export interface GetPollResponse extends Omit<GetPollApiResponse, "createdAt"> {- createdAt: string;-}diff --git a/api-client/update-participant.ts b/api-client/update-participant.tsdeleted file mode 100644index 482776ee7..000000000--- a/api-client/update-participant.ts+++ /dev/null@@ -1,20 +0,0 @@-import { Participant, Vote, VoteType } from "@prisma/client";-import axios from "axios";--export interface UpdateParticipantPayload {- pollId: string;- participantId: string;- name: string;- votes: Array<{ optionId: string; type: VoteType }>;-}--export const updateParticipant = async (- payload: UpdateParticipantPayload,-): Promise<Participant & { votes: Vote[] }> => {- const { pollId, participantId, ...body } = payload;- const res = await axios.patch<Participant & { votes: Vote[] }>(- `/api/poll/${pollId}/participant/${participantId}`,- body,- );- return res.data;-};diff --git a/api-client/update-poll.ts b/api-client/update-poll.tsdeleted file mode 100644index 6ddca9c51..000000000--- a/api-client/update-poll.ts+++ /dev/null@@ -1,25 +0,0 @@-import { Poll } from "@prisma/client";-import axios from "axios";--export interface UpdatePollPayload {- title?: string;- timeZone?: string;- location?: string;- description?: string;- optionsToDelete?: string[];- optionsToAdd?: string[];- notifications?: boolean;- closed?: boolean;-}--export const updatePoll = async (- urlId: string,- payload: UpdatePollPayload,-): Promise<Poll> => {- try {- const { data } = await axios.patch<Poll>(`/api/poll/${urlId}`, payload);- return data;- } catch (err) {- throw err;- }-};diff --git a/components/poll/mutations.ts b/components/poll/mutations.tsdeleted file mode 100644index c4bcc97ed..000000000--- a/components/poll/mutations.ts+++ /dev/null@@ -1,145 +0,0 @@-import { updatePoll, UpdatePollPayload } from "api-client/update-poll";-import { usePlausible } from "next-plausible";-import { useMutation, useQueryClient } from "react-query";--import { addParticipant } from "../../api-client/add-participant";-import {- deleteParticipant,- DeleteParticipantPayload,-} from "../../api-client/delete-participant";-import { GetPollResponse } from "../../api-client/get-poll";-import { updateParticipant } from "../../api-client/update-participant";-import { usePoll } from "../poll-context";-import { useSession } from "../session";-import { ParticipantForm } from "./types";--export const useAddParticipantMutation = (pollId: string) => {- const queryClient = useQueryClient();- const session = useSession();- const plausible = usePlausible();- const { options } = usePoll();-- return useMutation(- (payload: ParticipantForm) =>- addParticipant({- pollId,- name: payload.name.trim(),- votes: options.map(- (option, i) =>- payload.votes[i] ?? { optionId: option.optionId, type: "no" },- ),- }),- {- onSuccess: (participant) => {- plausible("Add participant");- queryClient.setQueryData<GetPollResponse>(- ["getPoll", pollId],- (poll) => {- if (!poll) {- throw new Error(- "Tried to update poll but no result found in query cache",- );- }- poll.participants = [participant, ...poll.participants];- return poll;- },- );- session.refresh();- },- },- );-};--export const useUpdateParticipantMutation = (pollId: string) => {- const queryClient = useQueryClient();- const plausible = usePlausible();- const { options } = usePoll();-- return useMutation(- (payload: ParticipantForm & { participantId: string }) =>- updateParticipant({- pollId,- participantId: payload.participantId,- name: payload.name.trim(),- votes: options.map(- (option, i) =>- payload.votes[i] ?? { optionId: option.optionId, type: "no" },- ),- }),- {- onSuccess: (participant) => {- plausible("Update participant");- queryClient.setQueryData<GetPollResponse>(- ["getPoll", pollId],- (poll) => {- if (!poll) {- throw new Error(- "Tried to update poll but no result found in query cache",- );- }-- poll.participants = poll.participants.map((p) =>- p.id === participant.id ? participant : p,- );-- return poll;- },- );- },- onSettled: () => {- queryClient.invalidateQueries(["getPoll", pollId]);- },- },- );-};--export const useDeleteParticipantMutation = () => {- const queryClient = useQueryClient();- const plausible = usePlausible();- const { poll } = usePoll();- return useMutation(- (payload: DeleteParticipantPayload) => deleteParticipant(payload),- {- onMutate: ({ participantId }) => {- queryClient.setQueryData<GetPollResponse>(- ["getPoll", poll.urlId],- (poll) => {- if (!poll) {- throw new Error(- "Tried to update poll but no result found in query cache",- );- }-- poll.participants = poll.participants.filter(- ({ id }) => id !== participantId,- );-- return poll;- },- );- },- onSuccess: () => {- plausible("Remove participant");- },- onSettled: (_data, _error, { pollId }) => {- queryClient.invalidateQueries(["getPoll", pollId]);- },- },- );-};--export const useUpdatePollMutation = () => {- const { poll } = usePoll();- const plausible = usePlausible();- const queryClient = useQueryClient();-- return useMutation(- (payload: UpdatePollPayload) => updatePoll(poll.urlId, payload),- {- onSuccess: (data) => {- queryClient.setQueryData(["getPoll", poll.urlId], data);- plausible("Updated poll");- },- },- );-};diff --git a/components/user-profile/guest-session.tsx b/components/user-profile/guest-session.tsxdeleted file mode 100644index f35a87b3c..000000000--- a/components/user-profile/guest-session.tsx+++ /dev/null@@ -1,63 +0,0 @@-import axios from "axios";-import clsx from "clsx";-import * as React from "react";-import { useForm } from "react-hook-form";-import { validEmail } from "utils/form-validation";--import Button from "@/components/button";--const GuestSession: React.VoidFunctionComponent = () => {- const { handleSubmit, register, formState, getValues } = useForm<{- email: string;- }>({- defaultValues: {- email: "",- },- });- return (- <div className="card border-amber-500 ring-2 ring-amber-500/20">- <h2>Guest session</h2>- <p>- Guest sessions allow us to remember your device so that you can edit- your votes and comments later. However, these sessions are temporary and- when they end, cannot be resumed.{" "}- <a href="">Read more about guest sessions.</a>- </p>- <p>Login with your email to make sure you don't lose access:</p>- {formState.submitCount > 0 ? (- <div>- An email has been sent to <strong>{getValues("email")}</strong>.- Please check your inbox.- </div>- ) : (- <form- onSubmit={handleSubmit(({ email }) => {- axios.post("/api/login", { email });- })}- >- <input- {...register("email", {- validate: validEmail,- })}- className={clsx("input w-full", {- "input-error": formState.errors.email,- })}- placeholder="Email address"- />- {formState.errors.email ? (- <div className="mt-1 text-sm text-red-500">- Please enter a valid email address- </div>- ) : null}- <div className="mt-4 flex space-x-3">- <Button htmlType="submit" type="primary">- Login- </Button>- </div>- </form>- )}- </div>- );-};--export default GuestSession;diff --git a/declarations/environment.d.ts b/declarations/environment.d.tsindex 1c7ce4654..7d98e8fae 100644--- a/declarations/environment.d.ts+++ b/declarations/environment.d.ts@@ -4,6 +4,7 @@ declare global {DATABASE_URL: string;NODE_ENV: "development" | "production";SECRET_PASSWORD: string;+ NEXT_PUBLIC_LEGACY_POLLS?: string;NEXT_PUBLIC_MAINTENANCE_MODE?: string;PLAUSIBLE_DOMAIN?: string;NEXT_PUBLIC_CRISP_WEBSITE_ID?: string;diff --git a/declarations/i18next.d.ts b/declarations/i18next.d.tsindex 8e830d5f9..8f873263c 100644--- a/declarations/i18next.d.ts+++ b/declarations/i18next.d.ts@@ -1,8 +1,8 @@import "react-i18next";-import app from "../public/locales/en/app.json";-import homepage from "../public/locales/en/homepage.json";-import support from "../public/locales/en/support.json";+import app from "~/public/locales/en/app.json";+import homepage from "~/public/locales/en/homepage.json";+import support from "~/public/locales/en/support.json";declare module "next-i18next" {interface Resources {diff --git a/package.json b/package.jsonindex f0a965e1c..29a03ce11 100644--- a/package.json+++ b/package.json@@ -16,11 +16,15 @@"@floating-ui/react-dom-interactions": "^0.4.0","@headlessui/react": "^1.5.0","@next/bundle-analyzer": "^12.1.0",- "@prisma/client": "^3.13.0",+ "@prisma/client": "^3.14.0","@sentry/nextjs": "^6.19.3","@svgr/webpack": "^6.2.1","@tailwindcss/forms": "^0.4.0","@tailwindcss/typography": "^0.5.2",+ "@trpc/client": "^9.23.2",+ "@trpc/next": "^9.23.2",+ "@trpc/react": "^9.23.2",+ "@trpc/server": "^9.23.2","axios": "^0.24.0","clsx": "^1.1.1","date-fns": "^2.28.0",@@ -37,7 +41,7 @@"next-i18next": "^10.5.0","next-plausible": "^3.1.9","nodemailer": "^6.7.2",- "prisma": "^3.13.0",+ "prisma": "^3.14.0","react": "17.0.2","react-big-calendar": "^0.38.9","react-dom": "17.0.2",@@ -50,8 +54,10 @@"react-use": "^17.3.2","smoothscroll-polyfill": "^0.4.4","spacetime": "^7.1.2",+ "superjson": "^1.9.1","timezone-soft": "^1.3.1",- "typescript": "^4.5.2"+ "typescript": "^4.5.2",+ "zod": "^3.16.0"},"devDependencies": {"@playwright/test": "^1.20.1",diff --git a/pages/_app.tsx b/pages/_app.tsxdeleted file mode 100644index d31029279..000000000--- a/pages/_app.tsx+++ /dev/null@@ -1,66 +0,0 @@-import "react-big-calendar/lib/css/react-big-calendar.css";-import "tailwindcss/tailwind.css";-import "../style.css";--import axios from "axios";-import { NextPage } from "next";-import { AppProps } from "next/app";-import dynamic from "next/dynamic";-import Head from "next/head";-import { appWithTranslation } from "next-i18next";-import PlausibleProvider from "next-plausible";-import toast, { Toaster } from "react-hot-toast";-import { MutationCache, QueryClient, QueryClientProvider } from "react-query";--import Maintenance from "@/components/maintenance";-import ModalProvider from "@/components/modal/modal-provider";-import PreferencesProvider from "@/components/preferences/preferences-provider";--const CrispChat = dynamic(() => import("@/components/crisp-chat"), {- ssr: false,-});--const queryClient = new QueryClient({- mutationCache: new MutationCache({- onError: (error) => {- if (axios.isAxiosError(error) && error.response?.status === 500) {- toast.error(- "Uh oh! Something went wrong. The issue has been logged and we'll fix it as soon as possible. Please try again later.",- );- }- },- }),-});--const MyApp: NextPage<AppProps> = ({ Component, pageProps }) => {- if (process.env.NEXT_PUBLIC_MAINTENANCE_MODE === "1") {- return <Maintenance />;- }- return (- <PlausibleProvider- domain="rallly.co"- customDomain={process.env.PLAUSIBLE_DOMAIN}- trackOutboundLinks={true}- selfHosted={true}- enabled={!!process.env.PLAUSIBLE_DOMAIN}- >- <PreferencesProvider>- <QueryClientProvider client={queryClient}>- <Head>- <meta- name="viewport"- content="width=device-width, initial-scale=1"- />- </Head>- <CrispChat />- <Toaster />- <ModalProvider>- <Component {...pageProps} />- </ModalProvider>- </QueryClientProvider>- </PreferencesProvider>- </PlausibleProvider>- );-};--export default appWithTranslation(MyApp);diff --git a/pages/api/login.ts b/pages/api/login.tsdeleted file mode 100644index 1b0c2645d..000000000--- a/pages/api/login.ts+++ /dev/null@@ -1,35 +0,0 @@-import absoluteUrl from "utils/absolute-url";-import { sendEmailTemplate } from "utils/api-utils";-import { createToken, withSessionRoute } from "utils/auth";--export default withSessionRoute(async (req, res) => {- switch (req.method) {- case "POST": {- const email = req.body.email;- const homePageUrl = absoluteUrl(req).origin;- const token = await createToken({- email,- guestId: req.session.user?.isGuest ? req.session.user.id : undefined,- path: req.body.path,- });-- const loginUrl = `${homePageUrl}/login?code=${token}`;-- await sendEmailTemplate({- templateName: "login",- to: email,- subject: "Rallly - Login",- templateVars: {- loginUrl,- homePageUrl,- },- });-- res.end();- return;- }- default:- res.status(405);- return;- }-});diff --git a/pages/api/logout.ts b/pages/api/logout.tsdeleted file mode 100644index 284c0b9cd..000000000--- a/pages/api/logout.ts+++ /dev/null@@ -1,6 +0,0 @@-import { withSessionRoute } from "utils/auth";--export default withSessionRoute((req, res) => {- req.session.destroy();- res.send({ ok: true });-});diff --git a/pages/api/poll.ts b/pages/api/poll.tsdeleted file mode 100644index fdc3501f4..000000000--- a/pages/api/poll.ts+++ /dev/null@@ -1,108 +0,0 @@-import { sendEmailTemplate } from "utils/api-utils";-import { createToken, withSessionRoute } from "utils/auth";-import { nanoid } from "utils/nanoid";--import { CreatePollPayload } from "../../api-client/create-poll";-import { prisma } from "../../db";-import absoluteUrl from "../../utils/absolute-url";--export default withSessionRoute(async (req, res) => {- switch (req.method) {- case "POST": {- const adminUrlId = await nanoid();- const payload: CreatePollPayload = req.body;-- const poll = await prisma.poll.create({- data: {- urlId: await nanoid(),- title: payload.title,- type: payload.type,- timeZone: payload.timeZone,- location: payload.location,- description: payload.description,- authorName: payload.user.name,- demo: payload.demo,- verified:- req.session.user?.isGuest === false &&- req.session.user.email === payload.user.email,- user: {- connectOrCreate: {- where: {- email: payload.user.email,- },- create: {- id: await nanoid(),- ...payload.user,- },- },- },- options: {- createMany: {- data: payload.options.map((value) => ({- value,- })),- },- },- links: {- createMany: {- data: [- {- urlId: adminUrlId,- role: "admin",- },- {- urlId: await nanoid(),- role: "participant",- },- ],- },- },- },- });-- const homePageUrl = absoluteUrl(req).origin;- const pollUrl = `${homePageUrl}/admin/${adminUrlId}`;-- try {- if (poll.verified) {- await sendEmailTemplate({- templateName: "new-poll-verified",- to: payload.user.email,- subject: `Rallly: ${poll.title}`,- templateVars: {- title: poll.title,- name: payload.user.name,- pollUrl,- homePageUrl,- supportEmail: process.env.SUPPORT_EMAIL,- },- });- } else {- const verificationCode = await createToken({- pollId: poll.urlId,- });- const verifyEmailUrl = `${pollUrl}?code=${verificationCode}`;-- await sendEmailTemplate({- templateName: "new-poll",- to: payload.user.email,- subject: `Rallly: ${poll.title} - Verify your email address`,- templateVars: {- title: poll.title,- name: payload.user.name,- pollUrl,- verifyEmailUrl,- homePageUrl,- supportEmail: process.env.SUPPORT_EMAIL,- },- });- }- } catch (e) {- console.error(e);- }-- return res.json({ urlId: adminUrlId, authorName: poll.authorName });- }- default:- }-});diff --git a/pages/api/poll/[urlId].ts b/pages/api/poll/[urlId].tsdeleted file mode 100644index 9ff1cec7e..000000000--- a/pages/api/poll/[urlId].ts+++ /dev/null@@ -1,148 +0,0 @@-import { GetPollApiResponse } from "api-client/get-poll";-import { resetDates } from "utils/legacy-utils";--import { UpdatePollPayload } from "../../../api-client/update-poll";-import { prisma } from "../../../db";-import { withLink } from "../../../utils/api-utils";--export default withLink<- GetPollApiResponse | { status: number; message: string }->(async ({ req, res, link }) => {- const pollId = link.pollId;-- switch (req.method) {- case "GET": {- const poll = await prisma.poll.findUnique({- where: {- urlId: pollId,- },- include: {- options: {- orderBy: {- value: "asc",- },- },- participants: {- include: {- votes: true,- },- orderBy: [- {- createdAt: "desc",- },- { name: "desc" },- ],- },- user: true,- links: link.role === "admin",- },- });-- if (!poll) {- return res.status(404).json({ status: 404, message: "Poll not found" });- }-- if (- poll.legacy &&- // has converted options without timezone- poll.options.every(({ value }) => value.indexOf("T") === -1)- ) {- // We need to reset the dates for polls that lost their timezone data because some users- // of the old version will end up seeing the wrong dates- const fixedPoll = await resetDates(poll.urlId);-- if (fixedPoll) {- return res.json({- ...fixedPoll,- role: link.role,- urlId: link.urlId,- pollId: poll.urlId,- });- }- }-- return res.json({- ...poll,- role: link.role,- urlId: link.urlId,- pollId: poll.urlId,- });- }- case "PATCH": {- if (link.role !== "admin") {- return res- .status(401)- .json({ status: 401, message: "Permission denied" });- }-- const payload: Partial<UpdatePollPayload> = req.body;- if (payload.optionsToDelete && payload.optionsToDelete.length > 0) {- await prisma.option.deleteMany({- where: {- pollId,- id: {- in: payload.optionsToDelete,- },- },- });- }- if (payload.optionsToAdd && payload.optionsToAdd.length > 0) {- await prisma.option.createMany({- data: payload.optionsToAdd.map((optionValue) => ({- value: optionValue,- pollId,- })),- });- }- const poll = await prisma.poll.update({- where: {- urlId: pollId,- },- data: {- title: payload.title,- location: payload.location,- description: payload.description,- timeZone: payload.timeZone,- notifications: payload.notifications,- closed: payload.closed,- },- include: {- options: {- orderBy: {- value: "asc",- },- },- participants: {- include: {- votes: true,- },- orderBy: [- {- createdAt: "desc",- },- { name: "desc" },- ],- },- user: true,- links: true,- },- });-- if (!poll) {- return res.status(404).json({ status: 404, message: "Poll not found" });- }-- return res.json({- ...poll,- role: link.role,- urlId: link.urlId,- pollId: poll.urlId,- });- }-- default:- return res- .status(405)- .json({ status: 405, message: "Method not allowed" });- }-});diff --git a/pages/api/poll/[urlId]/comments.ts b/pages/api/poll/[urlId]/comments.tsdeleted file mode 100644index 228012ebd..000000000--- a/pages/api/poll/[urlId]/comments.ts+++ /dev/null@@ -1,56 +0,0 @@-import { createGuestUser, withSessionRoute } from "utils/auth";--import { prisma } from "../../../../db";-import { sendNotification, withLink } from "../../../../utils/api-utils";--export default withSessionRoute(- withLink(async ({ req, res, link }) => {- switch (req.method) {- case "GET": {- const comments = await prisma.comment.findMany({- where: {- pollId: link.pollId,- },- orderBy: [- {- createdAt: "asc",- },- ],- });-- return res.json({ comments });- }- case "POST": {- if (!req.session.user) {- await createGuestUser(req);- }-- const newComment = await prisma.comment.create({- data: {- content: req.body.content,- pollId: link.pollId,- authorName: req.body.authorName,- userId: req.session.user?.isGuest- ? undefined- : req.session.user?.id,- guestId: req.session.user?.isGuest- ? req.session.user.id- : undefined,- },- });-- await sendNotification(req, link.pollId, {- type: "newComment",- authorName: newComment.authorName,- });-- return res.json(newComment);- }-- default:- return res- .status(405)- .json({ status: 405, message: "Method not allowed" });- }- }),-);diff --git a/pages/api/poll/[urlId]/comments/[commentId].ts b/pages/api/poll/[urlId]/comments/[commentId].tsdeleted file mode 100644index 877180961..000000000--- a/pages/api/poll/[urlId]/comments/[commentId].ts+++ /dev/null@@ -1,36 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { prisma } from "../../../../../db";-import { getQueryParam } from "../../../../../utils/api-utils";--export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- const urlId = getQueryParam(req, "urlId");- const commentId = getQueryParam(req, "commentId");-- const link = await prisma.link.findUnique({ where: { urlId } });-- if (!link) {- return res.status(404).end();- }-- switch (req.method) {- case "DELETE":- await prisma.comment.delete({- where: {- id_pollId: {- id: commentId,- pollId: link.pollId,- },- },- });-- return res.end();- default:- return res- .status(405)- .json({ status: 405, message: "Method not allowed" });- }-}diff --git a/pages/api/poll/[urlId]/participant.ts b/pages/api/poll/[urlId]/participant.tsdeleted file mode 100644index 72b2296dd..000000000--- a/pages/api/poll/[urlId]/participant.ts+++ /dev/null@@ -1,55 +0,0 @@-import { createGuestUser, withSessionRoute } from "utils/auth";--import { AddParticipantPayload } from "../../../../api-client/add-participant";-import { prisma } from "../../../../db";-import { sendNotification, withLink } from "../../../../utils/api-utils";--export default withSessionRoute(- withLink(async ({ req, res, link }) => {- switch (req.method) {- case "POST": {- const payload: AddParticipantPayload = req.body;-- if (!req.session.user) {- await createGuestUser(req);- }-- const participant = await prisma.participant.create({- data: {- pollId: link.pollId,- name: payload.name,- userId:- req.session.user?.isGuest === false- ? req.session.user.id- : undefined,- guestId:- req.session.user?.isGuest === true- ? req.session.user.id- : undefined,- votes: {- createMany: {- data: payload.votes.map(({ optionId, type }) => ({- optionId,- type,- pollId: link.pollId,- })),- },- },- },- include: {- votes: true,- },- });-- await sendNotification(req, link.pollId, {- type: "newParticipant",- participantName: participant.name,- });-- return res.json(participant);- }- default:- return res.status(405).json({ ok: 1 });- }- }),-);diff --git a/pages/api/poll/[urlId]/participant/[participantId].ts b/pages/api/poll/[urlId]/participant/[participantId].tsdeleted file mode 100644index e22cfed30..000000000--- a/pages/api/poll/[urlId]/participant/[participantId].ts+++ /dev/null@@ -1,57 +0,0 @@-import { UpdateParticipantPayload } from "api-client/update-participant";--import { prisma } from "../../../../../db";-import { getQueryParam, withLink } from "../../../../../utils/api-utils";--export default withLink(async ({ req, res, link }) => {- const participantId = getQueryParam(req, "participantId");-- const pollId = link.pollId;- switch (req.method) {- case "PATCH":- const payload: UpdateParticipantPayload = req.body;-- const participant = await prisma.participant.update({- where: {- id_pollId: {- id: participantId,- pollId,- },- },- data: {- votes: {- deleteMany: {- pollId,- },- createMany: {- data: payload.votes.map(({ optionId, type }) => ({- optionId,- type,- pollId,- })),- },- },- name: req.body.name,- },- include: {- votes: true,- },- });-- return res.json(participant);-- case "DELETE":- await prisma.participant.delete({- where: {- id_pollId: {- id: participantId,- pollId,- },- },- });-- return res.end();- default:- return res.status(405);- }-});diff --git a/pages/api/poll/[urlId]/verify.ts b/pages/api/poll/[urlId]/verify.tsdeleted file mode 100644index 40a63eef1..000000000--- a/pages/api/poll/[urlId]/verify.ts+++ /dev/null@@ -1,109 +0,0 @@-import absoluteUrl from "utils/absolute-url";-import {- createToken,- decryptToken,- mergeGuestsIntoUser as mergeUsersWithGuests,- withSessionRoute,-} from "utils/auth";--import { prisma } from "../../../../db";-import { sendEmailTemplate, withLink } from "../../../../utils/api-utils";--export default withSessionRoute(- withLink(async ({ req, res, link }) => {- if (req.method === "POST") {- if (link.role !== "admin") {- return res- .status(401)- .json({ status: 401, message: "Only admins can verify polls" });- }- const verificationCode = req.body ? req.body.verificationCode : undefined;- if (!verificationCode) {- const poll = await prisma.poll.findUnique({- where: {- urlId: link.pollId,- },- include: {- user: true,- },- });-- if (!poll) {- return res- .status(404)- .json({ status: 404, message: "Poll not found" });- }-- const homePageUrl = absoluteUrl(req).origin;- const pollUrl = `${homePageUrl}/admin/${link.urlId}`;- const token = await createToken({- pollId: link.pollId,- });- const verifyEmailUrl = `${pollUrl}?code=${token}`;-- await sendEmailTemplate({- templateName: "new-poll",- to: poll.user.email,- subject: `Rallly: ${poll.title} - Verify your email address`,- templateVars: {- title: poll.title,- name: poll.user.name,- pollUrl,- verifyEmailUrl,- homePageUrl,- supportEmail: process.env.SUPPORT_EMAIL,- },- });-- return res.send("ok");- }- try {- const { pollId } = await decryptToken<{- pollId: string;- }>(verificationCode);-- if (pollId !== link.pollId) {- res.status(401).json({- status: 401,- message: "Invalid token",- });- return;- }- const poll = await prisma.poll.update({- where: {- urlId: pollId,- },- data: {- verified: true,- },- include: { user: true },- });-- // If logged in as guest, we update all participants- // and comments by this guest to the user that we just authenticated- if (req.session.user?.isGuest) {- await mergeUsersWithGuests(poll.user.id, [req.session.user.id]);- }-- req.session.user = {- id: poll.user.id,- isGuest: false,- name: poll.user.name,- email: poll.user.email,- };- await req.session.save();-- return res.send("ok");- } catch (e) {- console.error(e);- return res- .status(500)- .json({ status: 500, message: "Could not verify poll" });- }- }-- return res- .status(405)- .json({ status: 405, message: "Invalid http method" });- }),-);diff --git a/pages/api/poll/demo.ts b/pages/api/poll/demo.tsdeleted file mode 100644index b0b426adb..000000000--- a/pages/api/poll/demo.ts+++ /dev/null@@ -1,135 +0,0 @@-import { VoteType } from "@prisma/client";-import { addMinutes } from "date-fns";-import { NextApiRequest, NextApiResponse } from "next";-import absoluteUrl from "utils/absolute-url";-import { nanoid } from "utils/nanoid";--import { prisma } from "../../../db";--const participantData: Array<{ name: string; votes: VoteType[] }> = [- {- name: "Reed",- votes: ["yes", "no", "ifNeedBe", "no"],- },- {- name: "Susan",- votes: ["yes", "yes", "yes", "no"],- },- {- name: "Johnny",- votes: ["no", "no", "yes", "yes"],- },- {- name: "Ben",- votes: ["yes", "yes", "yes", "yes"],- },-];--const optionValues = ["2022-12-14", "2022-12-15", "2022-12-16", "2022-12-17"];--export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- switch (req.method) {- case "POST": {- const adminUrlId = await nanoid();- const demoUser = { name: "John Example", email: "[email protected]" };- const today = new Date();-- const options: Array<{ value: string; id: string }> = [];-- for (let i = 0; i < optionValues.length; i++) {- options.push({ id: await nanoid(), value: optionValues[i] });- }-- const participants: Array<{- name: string;- id: string;- guestId: string;- createdAt: Date;- }> = [];-- const votes: Array<{- optionId: string;- participantId: string;- type: VoteType;- }> = [];-- for (let i = 0; i < participantData.length; i++) {- const { name, votes: participantVotes } = participantData[i];- const participantId = await nanoid();- participants.push({- id: participantId,- name,- guestId: "user-demo",- createdAt: addMinutes(today, i * -1),- });-- options.forEach((option, index) => {- votes.push({- optionId: option.id,- participantId,- type: participantVotes[index],- });- });- }-- const homePageUrl = absoluteUrl(req).origin;-- await prisma.poll.create({- data: {- urlId: await nanoid(),- title: "Lunch Meeting Demo",- type: "date",- location: "Starbucks, 901 New York Avenue",- description: `This poll has been automatically generated just for you! Feel free to try out all the different features and when you're ready, you can go to ${homePageUrl}/new to make a new poll.`,- authorName: "Johnny",- verified: true,- demo: true,- user: {- connectOrCreate: {- where: {- email: demoUser.email,- },- create: demoUser,- },- },- options: {- createMany: {- data: options,- },- },- links: {- createMany: {- data: [- {- role: "admin",- urlId: adminUrlId,- },- {- role: "participant",- urlId: await nanoid(),- },- ],- },- },- participants: {- createMany: {- data: participants,- },- },- votes: {- createMany: {- data: votes,- },- },- },- });-- return res.json({ urlId: adminUrlId });- }- default:- return res.status(405).json({ ok: 1 });- }-}diff --git a/pages/api/user.ts b/pages/api/user.tsdeleted file mode 100644index 1bf37d75b..000000000--- a/pages/api/user.ts+++ /dev/null@@ -1,20 +0,0 @@-import { withSessionRoute } from "utils/auth";--import { prisma } from "../../db";--export default withSessionRoute(async (req, res) => {- if (req.session.user?.isGuest === false) {- const user = await prisma.user.findUnique({- where: { id: req.session.user.id },- });-- res.json({- user: user- ? { id: user.id, name: user.name, email: user.email, isGuest: false }- : null,- });-- return;- }- res.json({ user: req.session.user ?? null });-});diff --git a/pages/poll.tsx b/pages/poll.tsxdeleted file mode 100644index 033ff4f6e..000000000--- a/pages/poll.tsx+++ /dev/null@@ -1,107 +0,0 @@-import axios from "axios";-import { GetServerSideProps, NextPage } from "next";-import dynamic from "next/dynamic";-import { useRouter } from "next/router";-import { useTranslation } from "next-i18next";-import { serverSideTranslations } from "next-i18next/serverSideTranslations";-import { usePlausible } from "next-plausible";-import React from "react";-import { useQuery } from "react-query";-import { withSessionSsr } from "utils/auth";--import ErrorPage from "@/components/error-page";-import FullPageLoader from "@/components/full-page-loader";-import { PollContextProvider } from "@/components/poll-context";-import { SessionProps, withSession } from "@/components/session";--import { GetPollResponse } from "../api-client/get-poll";-import Custom404 from "./404";--const PollPage = dynamic(() => import("@/components/poll"), { ssr: false });--const PollPageLoader: NextPage<SessionProps> = () => {- const { query } = useRouter();- const { t } = useTranslation("app");- const urlId = query.urlId as string;-- const [didError, setDidError] = React.useState(false);- const [didFailToConvertLegacyPoll, setDidFailToConvertLegacyPoll] =- React.useState(false);-- const plausible = usePlausible();-- const { data: poll } = useQuery<GetPollResponse | null>(- ["getPoll", urlId],- async () => {- try {- const { data } = await axios.get<GetPollResponse>(`/api/poll/${urlId}`);- return data;- } catch (error) {- if (axios.isAxiosError(error) && error.response?.status === 404) {- try {- // check if poll exists from the legacy endpoint and convert it if it does- const { data } = await axios.get<GetPollResponse>(- `/api/legacy/${urlId}`,- );- plausible("Converted legacy event");- return data;- } catch (err) {- if (axios.isAxiosError(err) && err.response?.status === 500) {- // failed to convert legacy poll- setDidFailToConvertLegacyPoll(true);- }- throw err;- }- } else {- throw error;- }- }- },- {- onError: () => {- setDidError(true);- },- retry: false,- },- );-- if (didFailToConvertLegacyPoll) {- return (- <ErrorPage- title="Server error"- description="There was a problem retrieving your poll. Please contact support."- />- );- }-- if (poll) {- return (- <PollContextProvider value={poll}>- <PollPage />- </PollContextProvider>- );- }-- if (didError) {- return <Custom404 />;- }-- return <FullPageLoader>{t("loading")}</FullPageLoader>;-};--export const getServerSideProps: GetServerSideProps = withSessionSsr(- async ({ locale = "en", req }) => {- try {- return {- props: {- ...(await serverSideTranslations(locale, ["app"])),- user: req.session.user ?? null,- },- };- } catch {- return { notFound: true };- }- },-);--export default withSession(PollPageLoader);diff --git a/db.ts b/prisma/db.tssimilarity index 100%rename from db.tsrename to prisma/db.tsdiff --git a/migrations/20220315143815_init/migration.sql b/prisma/migrations/20220315143815_init/migration.sqlsimilarity index 100%rename from migrations/20220315143815_init/migration.sqlrename to prisma/migrations/20220315143815_init/migration.sqldiff --git a/migrations/20220322193753_add_comments/migration.sql b/prisma/migrations/20220322193753_add_comments/migration.sqlsimilarity index 100%rename from migrations/20220322193753_add_comments/migration.sqlrename to prisma/migrations/20220322193753_add_comments/migration.sqldiff --git a/migrations/20220329102907_add_links/migration.sql b/prisma/migrations/20220329102907_add_links/migration.sqlsimilarity index 100%rename from migrations/20220329102907_add_links/migration.sqlrename to prisma/migrations/20220329102907_add_links/migration.sqldiff --git a/migrations/20220330085423_add_notifications_column/migration.sql b/prisma/migrations/20220330085423_add_notifications_column/migration.sqlsimilarity index 100%rename from migrations/20220330085423_add_notifications_column/migration.sqlrename to prisma/migrations/20220330085423_add_notifications_column/migration.sqldiff --git a/migrations/20220408120721_legacy_column/migration.sql b/prisma/migrations/20220408120721_legacy_column/migration.sqlsimilarity index 100%rename from migrations/20220408120721_legacy_column/migration.sqlrename to prisma/migrations/20220408120721_legacy_column/migration.sqldiff --git a/migrations/20220412112814_cascade_delete/migration.sql b/prisma/migrations/20220412112814_cascade_delete/migration.sqlsimilarity index 100%rename from migrations/20220412112814_cascade_delete/migration.sqlrename to prisma/migrations/20220412112814_cascade_delete/migration.sqldiff --git a/migrations/20220412115407_cascade_delete_participants/migration.sql b/prisma/migrations/20220412115407_cascade_delete_participants/migration.sqlsimilarity index 100%rename from migrations/20220412115407_cascade_delete_participants/migration.sqlrename to prisma/migrations/20220412115407_cascade_delete_participants/migration.sqldiff --git a/migrations/20220412115744_cascade_delete_votes/migration.sql b/prisma/migrations/20220412115744_cascade_delete_votes/migration.sqlsimilarity index 100%rename from migrations/20220412115744_cascade_delete_votes/migration.sqlrename to prisma/migrations/20220412115744_cascade_delete_votes/migration.sqldiff --git a/migrations/20220414101318_remove_duplicate_emails/migration.sql b/prisma/migrations/20220414101318_remove_duplicate_emails/migration.sqlsimilarity index 100%rename from migrations/20220414101318_remove_duplicate_emails/migration.sqlrename to prisma/migrations/20220414101318_remove_duplicate_emails/migration.sqldiff --git a/migrations/20220506105524_sessions_update/migration.sql b/prisma/migrations/20220506105524_sessions_update/migration.sqlsimilarity index 100%rename from migrations/20220506105524_sessions_update/migration.sqlrename to prisma/migrations/20220506105524_sessions_update/migration.sqldiff --git a/migrations/20220511113020_add_if_need_be/migration.sql b/prisma/migrations/20220511113020_add_if_need_be/migration.sqlsimilarity index 100%rename from migrations/20220511113020_add_if_need_be/migration.sqlrename to prisma/migrations/20220511113020_add_if_need_be/migration.sqldiff --git a/migrations/20220511180705_naming_convention_update/migration.sql b/prisma/migrations/20220511180705_naming_convention_update/migration.sqlsimilarity index 100%rename from migrations/20220511180705_naming_convention_update/migration.sqlrename to prisma/migrations/20220511180705_naming_convention_update/migration.sqldiff --git a/migrations/20220512093441_add_no_votes/migration.sql b/prisma/migrations/20220512093441_add_no_votes/migration.sqlsimilarity index 100%rename from migrations/20220512093441_add_no_votes/migration.sqlrename to prisma/migrations/20220512093441_add_no_votes/migration.sqldiff --git a/migrations/migration_lock.toml b/prisma/migrations/migration_lock.tomlsimilarity index 100%rename from migrations/migration_lock.tomlrename to prisma/migrations/migration_lock.tomldiff --git a/schema.prisma b/prisma/schema.prismasimilarity index 100%rename from schema.prismarename to prisma/schema.prismadiff --git a/public/locales/en/app.json b/public/locales/en/app.jsonindex 888ad888d..37d8665ab 100644--- a/public/locales/en/app.json+++ b/public/locales/en/app.json@@ -36,6 +36,7 @@"creatingDemo": "Creating demo poll…","ok": "Ok","loading": "Loading…",+ "loadingParticipants": "Loading participants…","admin": "Admin","adminDescription": "Full access to edit this poll.","participant": "Participant",diff --git a/sample.env b/sample.envindex 7492c7566..761518c96 100644--- a/sample.env+++ b/sample.env@@ -1,3 +1,4 @@+NEXT_PUBLIC_BASE_URL=http://localhost:3000DATABASE_URL=postgres://your-database/dbSECRET_PASSWORD=minimum-32-charactersdiff --git a/sentry.properties b/sentry.propertiesdeleted file mode 100644index 5cbecfcd8..000000000--- a/sentry.properties+++ /dev/null@@ -1,4 +0,0 @@-defaults.url=https://sentry.io/-defaults.org=stack-snap-defaults.project=rallly-cli.executable=../../.npm/_npx/a8388072043b4cbc/node_modules/@sentry/cli/bin/sentry-clidiff --git a/components/badge.tsx b/src/components/badge.tsxsimilarity index 100%rename from components/badge.tsxrename to src/components/badge.tsxdiff --git a/components/button/button.tsx b/src/components/button/button.tsxsimilarity index 100%rename from components/button/button.tsxrename to src/components/button/button.tsxdiff --git a/components/button/index.ts b/src/components/button/index.tssimilarity index 100%rename from components/button/index.tsrename to src/components/button/index.tsdiff --git a/components/compact-button.tsx b/src/components/compact-button.tsxsimilarity index 100%rename from components/compact-button.tsxrename to src/components/compact-button.tsxdiff --git a/components/confirm-prompt.tsx b/src/components/confirm-prompt.tsxsimilarity index 100%rename from components/confirm-prompt.tsxrename to src/components/confirm-prompt.tsxdiff --git a/components/cookie-consent.tsx b/src/components/cookie-consent.tsxsimilarity index 97%rename from components/cookie-consent.tsxrename to src/components/cookie-consent.tsxindex 124b21e13..7b0a5c0be 100644--- a/components/cookie-consent.tsx+++ b/src/components/cookie-consent.tsx@@ -3,7 +3,8 @@ import Cookies from "js-cookie";import Link from "next/link";import * as React from "react";import ReactDOM from "react-dom";-import { getPortal } from "utils/selectors";++import { getPortal } from "@/utils/selectors";import CookiesIllustration from "./cookie-consent/cookies.svg";diff --git a/components/cookie-consent/cookies.svg b/src/components/cookie-consent/cookies.svgsimilarity index 100%rename from components/cookie-consent/cookies.svgrename to src/components/cookie-consent/cookies.svgdiff --git a/components/create-poll.tsx b/src/components/create-poll.tsxsimilarity index 79%rename from components/create-poll.tsxrename to src/components/create-poll.tsxindex 302dec090..bd39b994b 100644--- a/components/create-poll.tsx+++ b/src/components/create-poll.tsx@@ -4,11 +4,11 @@ import { useRouter } from "next/router";import { useTranslation } from "next-i18next";import { usePlausible } from "next-plausible";import React from "react";-import { useMutation } from "react-query";import { useSessionStorage } from "react-use";-import { createPoll } from "../api-client/create-poll";-import Button from "../components/button";+import { encodeDateOption } from "../utils/date-time-utils";+import { trpc } from "../utils/trpc";+import Button from "./button";import {NewEventData,PollDetailsData,@@ -17,11 +17,10 @@ import {PollOptionsForm,UserDetailsData,UserDetailsForm,-} from "../components/forms";-import StandardLayout from "../components/standard-layout";-import Steps from "../components/steps";-import { encodeDateOption } from "../utils/date-time-utils";+} from "./forms";import { SessionProps, useSession, withSession } from "./session";+import StandardLayout from "./standard-layout";+import Steps from "./steps";type StepName = "eventDetails" | "options" | "userDetails";@@ -95,41 +94,23 @@ const Page: NextPage<CreatePollPageProps> = ({const plausible = usePlausible();- const { mutate: createEventMutation, isLoading: isCreatingPoll } =- useMutation(- () => {- const title = required(formData?.eventDetails?.title);- return createPoll({- title: title,- type: "date",- location: formData?.eventDetails?.location,- description: formData?.eventDetails?.description,- user: {- name: required(formData?.userDetails?.name),- email: required(formData?.userDetails?.contact),- },- timeZone: formData?.options?.timeZone,- options: required(formData?.options?.options).map(encodeDateOption),- });- },- {- onSuccess: (poll) => {- setIsRedirecting(true);- plausible("Created poll", {- props: {- numberOfOptions: formData.options?.options?.length,- optionsView: formData?.options?.view,- },- });- setPersistedFormData(initialNewEventData);- router.replace(`/admin/${poll.urlId}`);+ const createPoll = trpc.useMutation(["polls.create"], {+ onSuccess: (poll) => {+ setIsRedirecting(true);+ plausible("Created poll", {+ props: {+ numberOfOptions: formData.options?.options?.length,+ optionsView: formData?.options?.view,},- },- );+ });+ setPersistedFormData(initialNewEventData);+ router.replace(`/admin/${poll.urlId}`);+ },+ });- const isBusy = isRedirecting || isCreatingPoll;+ const isBusy = isRedirecting || createPoll.isLoading;- const handleSubmit = (+ const handleSubmit = async (data: PollDetailsData | PollOptionsData | UserDetailsData,) => {if (currentStepIndex < steps.length - 1) {@@ -140,7 +121,20 @@ const Page: NextPage<CreatePollPageProps> = ({});} else {// last step- createEventMutation();+ const title = required(formData?.eventDetails?.title);++ await createPoll.mutateAsync({+ title: title,+ type: "date",+ location: formData?.eventDetails?.location,+ description: formData?.eventDetails?.description,+ user: {+ name: required(formData?.userDetails?.name),+ email: required(formData?.userDetails?.contact),+ },+ timeZone: formData?.options?.timeZone,+ options: required(formData?.options?.options).map(encodeDateOption),+ });}};diff --git a/components/crisp-chat.tsx b/src/components/crisp-chat.tsxsimilarity index 100%rename from components/crisp-chat.tsxrename to src/components/crisp-chat.tsxdiff --git a/components/date-card.tsx b/src/components/date-card.tsxsimilarity index 100%rename from components/date-card.tsxrename to src/components/date-card.tsxdiff --git a/components/discussion/discussion.tsx b/src/components/discussion/discussion.tsxsimilarity index 68%rename from components/discussion/discussion.tsxrename to src/components/discussion/discussion.tsxindex eebdab186..efe95d277 100644--- a/components/discussion/discussion.tsx+++ b/src/components/discussion/discussion.tsx@@ -1,18 +1,12 @@-import { Comment } from "@prisma/client";-import axios from "axios";import clsx from "clsx";import { formatRelative } from "date-fns";import { AnimatePresence, motion } from "framer-motion";import { usePlausible } from "next-plausible";import * as React from "react";import { Controller, useForm } from "react-hook-form";-import { useMutation, useQuery, useQueryClient } from "react-query";-import {- createComment,- CreateCommentPayload,-} from "../../api-client/create-comment";import { requiredString } from "../../utils/form-validation";+import { trpc } from "../../utils/trpc";import Button from "../button";import CompactButton from "../compact-button";import Dropdown, { DropdownItem } from "../dropdown";@@ -25,29 +19,20 @@ import { usePoll } from "../poll-context";import { usePreferences } from "../preferences/use-preferences";import { isUnclaimed, useSession } from "../session";-export interface DiscussionProps {- pollId: string;-}-interface CommentForm {authorName: string;content: string;}-const Discussion: React.VoidFunctionComponent<DiscussionProps> = ({- pollId,-}) => {+const Discussion: React.VoidFunctionComponent = () => {const { locale } = usePreferences();- const getCommentsQueryKey = ["poll", pollId, "comments"];- const queryClient = useQueryClient();- const { data: comments } = useQuery(- getCommentsQueryKey,- async () => {- const res = await axios.get<{- comments: Array<Omit<Comment, "createdAt"> & { createdAt: string }>;- }>(`/api/poll/${pollId}/comments`);- return res.data.comments;- },+ const queryClient = trpc.useContext();+ const {+ poll: { pollId },+ } = usePoll();++ const { data: comments } = trpc.useQuery(+ ["polls.comments.list", { pollId }],{refetchInterval: 10000, // refetch every 10 seconds},@@ -55,44 +40,38 @@ const Discussion: React.VoidFunctionComponent<DiscussionProps> = ({const plausible = usePlausible();- const { mutate: createCommentMutation } = useMutation(- (payload: CreateCommentPayload) => {- // post comment- return createComment(payload);+ const addComment = trpc.useMutation("polls.comments.add", {+ onSuccess: (newComment) => {+ session.refresh();+ queryClient.setQueryData(+ ["polls.comments.list", { pollId }],+ (existingComments = []) => {+ return [...existingComments, newComment];+ },+ );+ plausible("Created comment");},- {- onSuccess: (newComment) => {- session.refresh();- queryClient.setQueryData(getCommentsQueryKey, (comments) => {- if (Array.isArray(comments)) {- return [...comments, newComment];- }- return [newComment];- });- plausible("Created comment");- },- },- );+ });const { poll } = usePoll();- const { mutate: deleteCommentMutation } = useMutation(- async (payload: { pollId: string; commentId: string }) => {- await axios.delete(`/api/poll/${pollId}/comments/${payload.commentId}`);+ const deleteComment = trpc.useMutation("polls.comments.delete", {+ onMutate: ({ commentId }) => {+ queryClient.setQueryData(+ ["polls.comments.list", { pollId }],+ (existingComments = []) => {+ return [...existingComments].filter(({ id }) => id !== commentId);+ },+ );},- {- onMutate: () => {- plausible("Deleted comment");- },- onSuccess: () => {- queryClient.invalidateQueries(getCommentsQueryKey);- },+ onSuccess: () => {+ plausible("Deleted comment");},- );+ });const session = useSession();- const { register, setValue, control, handleSubmit, formState } =+ const { register, reset, control, handleSubmit, formState } =useForm<CommentForm>({defaultValues: {authorName: "",@@ -100,13 +79,6 @@ const Discussion: React.VoidFunctionComponent<DiscussionProps> = ({},});- const handleDelete = React.useCallback(- (commentId: string) => {- deleteCommentMutation({ pollId, commentId });- },- [deleteCommentMutation, pollId],- );-if (!comments) {return null;}@@ -130,6 +102,7 @@ const Discussion: React.VoidFunctionComponent<DiscussionProps> = ({return (<motion.div+ layoutId={comment.id}transition={{ duration: 0.2 }}initial={{ opacity: 0 }}animate={{ opacity: 1 }}@@ -171,7 +144,10 @@ const Discussion: React.VoidFunctionComponent<DiscussionProps> = ({icon={Trash}label="Delete comment"onClick={() => {- handleDelete(comment.id);+ deleteComment.mutate({+ commentId: comment.id,+ pollId,+ });}}/></Dropdown>@@ -188,22 +164,9 @@ const Discussion: React.VoidFunctionComponent<DiscussionProps> = ({</div><formclassName="bg-white p-4"- onSubmit={handleSubmit((data) => {- return new Promise((resolve, reject) => {- createCommentMutation(- {- ...data,- pollId,- },- {- onSuccess: () => {- setValue("content", "");- resolve(data);- },- onError: reject,- },- );- });+ onSubmit={handleSubmit(async ({ authorName, content }) => {+ await addComment.mutateAsync({ authorName, content, pollId });+ reset({ authorName, content: "" });})}><textareadiff --git a/components/discussion/index.ts b/src/components/discussion/index.tssimilarity index 100%rename from components/discussion/index.tsrename to src/components/discussion/index.tsdiff --git a/components/dropdown.tsx b/src/components/dropdown.tsxsimilarity index 96%rename from components/dropdown.tsxrename to src/components/dropdown.tsxindex bb2f9aeff..182bd67b8 100644--- a/components/dropdown.tsx+++ b/src/components/dropdown.tsx@@ -10,8 +10,9 @@ import { Menu } from "@headlessui/react";import clsx from "clsx";import { motion } from "framer-motion";import * as React from "react";-import { transformOriginByPlacement } from "utils/constants";-import { stopPropagation } from "utils/stop-propagation";++import { transformOriginByPlacement } from "@/utils/constants";+import { stopPropagation } from "@/utils/stop-propagation";const MotionMenuItems = motion(Menu.Items);diff --git a/components/error-page.tsx b/src/components/error-page.tsxsimilarity index 100%rename from components/error-page.tsxrename to src/components/error-page.tsxdiff --git a/components/forms/index.ts b/src/components/forms/index.tssimilarity index 100%rename from components/forms/index.tsrename to src/components/forms/index.tsdiff --git a/components/forms/poll-details-form.tsx b/src/components/forms/poll-details-form.tsxsimilarity index 100%rename from components/forms/poll-details-form.tsxrename to src/components/forms/poll-details-form.tsxdiff --git a/components/forms/poll-options-form/date-navigation-toolbar.tsx b/src/components/forms/poll-options-form/date-navigation-toolbar.tsxsimilarity index 100%rename from components/forms/poll-options-form/date-navigation-toolbar.tsxrename to src/components/forms/poll-options-form/date-navigation-toolbar.tsxdiff --git a/components/forms/poll-options-form/index.ts b/src/components/forms/poll-options-form/index.tssimilarity index 100%rename from components/forms/poll-options-form/index.tsrename to src/components/forms/poll-options-form/index.tsdiff --git a/components/forms/poll-options-form/month-calendar/index.ts b/src/components/forms/poll-options-form/month-calendar/index.tssimilarity index 100%rename from components/forms/poll-options-form/month-calendar/index.tsrename to src/components/forms/poll-options-form/month-calendar/index.tsdiff --git a/components/forms/poll-options-form/month-calendar/month-calendar.tsx b/src/components/forms/poll-options-form/month-calendar/month-calendar.tsxsimilarity index 100%rename from components/forms/poll-options-form/month-calendar/month-calendar.tsxrename to src/components/forms/poll-options-form/month-calendar/month-calendar.tsxdiff --git a/components/forms/poll-options-form/month-calendar/time-picker.tsx b/src/components/forms/poll-options-form/month-calendar/time-picker.tsxsimilarity index 98%rename from components/forms/poll-options-form/month-calendar/time-picker.tsxrename to src/components/forms/poll-options-form/month-calendar/time-picker.tsxindex 534e929bc..11f6fcf87 100644--- a/components/forms/poll-options-form/month-calendar/time-picker.tsx+++ b/src/components/forms/poll-options-form/month-calendar/time-picker.tsx@@ -9,9 +9,9 @@ import { Listbox } from "@headlessui/react";import clsx from "clsx";import { addMinutes, format, isSameDay, setHours, setMinutes } from "date-fns";import * as React from "react";-import { stopPropagation } from "utils/stop-propagation";import { usePreferences } from "@/components/preferences/use-preferences";+import { stopPropagation } from "@/utils/stop-propagation";import ChevronDown from "../../../icons/chevron-down.svg";import { styleMenuItem } from "../../../menu-styles";diff --git a/components/forms/poll-options-form/poll-options-form.tsx b/src/components/forms/poll-options-form/poll-options-form.tsxsimilarity index 100%rename from components/forms/poll-options-form/poll-options-form.tsxrename to src/components/forms/poll-options-form/poll-options-form.tsxdiff --git a/components/forms/poll-options-form/types.ts b/src/components/forms/poll-options-form/types.tssimilarity index 100%rename from components/forms/poll-options-form/types.tsrename to src/components/forms/poll-options-form/types.tsdiff --git a/components/forms/poll-options-form/utils.ts b/src/components/forms/poll-options-form/utils.tssimilarity index 100%rename from components/forms/poll-options-form/utils.tsrename to src/components/forms/poll-options-form/utils.tsdiff --git a/components/forms/poll-options-form/week-calendar.tsx b/src/components/forms/poll-options-form/week-calendar.tsxsimilarity index 100%rename from components/forms/poll-options-form/week-calendar.tsxrename to src/components/forms/poll-options-form/week-calendar.tsxdiff --git a/components/forms/types.ts b/src/components/forms/types.tssimilarity index 100%rename from components/forms/types.tsrename to src/components/forms/types.tsdiff --git a/components/forms/user-details-form.tsx b/src/components/forms/user-details-form.tsxsimilarity index 100%rename from components/forms/user-details-form.tsxrename to src/components/forms/user-details-form.tsxdiff --git a/components/full-page-loader.tsx b/src/components/full-page-loader.tsxsimilarity index 100%rename from components/full-page-loader.tsxrename to src/components/full-page-loader.tsxdiff --git a/components/headless-date-picker.tsx b/src/components/headless-date-picker.tsxsimilarity index 100%rename from components/headless-date-picker.tsxrename to src/components/headless-date-picker.tsxdiff --git a/components/home.tsx b/src/components/home.tsxsimilarity index 100%rename from components/home.tsxrename to src/components/home.tsxdiff --git a/components/home/ban-ads.svg b/src/components/home/ban-ads.svgsimilarity index 100%rename from components/home/ban-ads.svgrename to src/components/home/ban-ads.svgdiff --git a/components/home/bonus.tsx b/src/components/home/bonus.tsxsimilarity index 100%rename from components/home/bonus.tsxrename to src/components/home/bonus.tsxdiff --git a/components/home/features.tsx b/src/components/home/features.tsxsimilarity index 100%rename from components/home/features.tsxrename to src/components/home/features.tsxdiff --git a/components/home/hero.tsx b/src/components/home/hero.tsxsimilarity index 100%rename from components/home/hero.tsxrename to src/components/home/hero.tsxdiff --git a/components/home/how-it-works.tsx b/src/components/home/how-it-works.tsxsimilarity index 100%rename from components/home/how-it-works.tsxrename to src/components/home/how-it-works.tsxdiff --git a/components/home/poll-demo.tsx b/src/components/home/poll-demo.tsxsimilarity index 100%rename from components/home/poll-demo.tsxrename to src/components/home/poll-demo.tsxdiff --git a/components/home/scribble-arrow.svg b/src/components/home/scribble-arrow.svgsimilarity index 100%rename from components/home/scribble-arrow.svgrename to src/components/home/scribble-arrow.svgdiff --git a/components/home/stats.tsx b/src/components/home/stats.tsxsimilarity index 100%rename from components/home/stats.tsxrename to src/components/home/stats.tsxdiff --git a/components/icons/adjustments.svg b/src/components/icons/adjustments.svgsimilarity index 100%rename from components/icons/adjustments.svgrename to src/components/icons/adjustments.svgdiff --git a/components/icons/annotation.svg b/src/components/icons/annotation.svgsimilarity index 100%rename from components/icons/annotation.svgrename to src/components/icons/annotation.svgdiff --git a/components/icons/arrow-left.svg b/src/components/icons/arrow-left.svgsimilarity index 100%rename from components/icons/arrow-left.svgrename to src/components/icons/arrow-left.svgdiff --git a/components/icons/arrow-right.svg b/src/components/icons/arrow-right.svgsimilarity index 100%rename from components/icons/arrow-right.svgrename to src/components/icons/arrow-right.svgdiff --git a/components/icons/ban.svg b/src/components/icons/ban.svgsimilarity index 100%rename from components/icons/ban.svgrename to src/components/icons/ban.svgdiff --git a/components/icons/bell-crossed.svg b/src/components/icons/bell-crossed.svgsimilarity index 100%rename from components/icons/bell-crossed.svgrename to src/components/icons/bell-crossed.svgdiff --git a/components/icons/bell.svg b/src/components/icons/bell.svgsimilarity index 100%rename from components/icons/bell.svgrename to src/components/icons/bell.svgdiff --git a/components/icons/calendar.svg b/src/components/icons/calendar.svgsimilarity index 100%rename from components/icons/calendar.svgrename to src/components/icons/calendar.svgdiff --git a/components/icons/cash.svg b/src/components/icons/cash.svgsimilarity index 100%rename from components/icons/cash.svgrename to src/components/icons/cash.svgdiff --git a/components/icons/chat.svg b/src/components/icons/chat.svgsimilarity index 100%rename from components/icons/chat.svgrename to src/components/icons/chat.svgdiff --git a/components/icons/check-circle.svg b/src/components/icons/check-circle.svgsimilarity index 100%rename from components/icons/check-circle.svgrename to src/components/icons/check-circle.svgdiff --git a/components/icons/check.svg b/src/components/icons/check.svgsimilarity index 100%rename from components/icons/check.svgrename to src/components/icons/check.svgdiff --git a/components/icons/chevron-down.svg b/src/components/icons/chevron-down.svgsimilarity index 100%rename from components/icons/chevron-down.svgrename to src/components/icons/chevron-down.svgdiff --git a/components/icons/chevron-left.svg b/src/components/icons/chevron-left.svgsimilarity index 100%rename from components/icons/chevron-left.svgrename to src/components/icons/chevron-left.svgdiff --git a/components/icons/chevron-right.svg b/src/components/icons/chevron-right.svgsimilarity index 100%rename from components/icons/chevron-right.svgrename to src/components/icons/chevron-right.svgdiff --git a/components/icons/clock.svg b/src/components/icons/clock.svgsimilarity index 100%rename from components/icons/clock.svgrename to src/components/icons/clock.svgdiff --git a/components/icons/code.svg b/src/components/icons/code.svgsimilarity index 100%rename from components/icons/code.svgrename to src/components/icons/code.svgdiff --git a/components/icons/cog.svg b/src/components/icons/cog.svgsimilarity index 100%rename from components/icons/cog.svgrename to src/components/icons/cog.svgdiff --git a/components/icons/currency-dollar.svg b/src/components/icons/currency-dollar.svgsimilarity index 100%rename from components/icons/currency-dollar.svgrename to src/components/icons/currency-dollar.svgdiff --git a/components/icons/cursor-click.svg b/src/components/icons/cursor-click.svgsimilarity index 100%rename from components/icons/cursor-click.svgrename to src/components/icons/cursor-click.svgdiff --git a/components/icons/device-mobile.svg b/src/components/icons/device-mobile.svgsimilarity index 100%rename from components/icons/device-mobile.svgrename to src/components/icons/device-mobile.svgdiff --git a/components/icons/document-search.svg b/src/components/icons/document-search.svgsimilarity index 100%rename from components/icons/document-search.svgrename to src/components/icons/document-search.svgdiff --git a/components/icons/document.svg b/src/components/icons/document.svgsimilarity index 100%rename from components/icons/document.svgrename to src/components/icons/document.svgdiff --git a/components/icons/dots-horizontal.svg b/src/components/icons/dots-horizontal.svgsimilarity index 100%rename from components/icons/dots-horizontal.svgrename to src/components/icons/dots-horizontal.svgdiff --git a/components/icons/dots-vertical.svg b/src/components/icons/dots-vertical.svgsimilarity index 100%rename from components/icons/dots-vertical.svgrename to src/components/icons/dots-vertical.svgdiff --git a/components/icons/duplicate.svg b/src/components/icons/duplicate.svgsimilarity index 100%rename from components/icons/duplicate.svgrename to src/components/icons/duplicate.svgdiff --git a/components/icons/emoji-sad.svg b/src/components/icons/emoji-sad.svgsimilarity index 100%rename from components/icons/emoji-sad.svgrename to src/components/icons/emoji-sad.svgdiff --git a/components/icons/exclamation.svg b/src/components/icons/exclamation.svgsimilarity index 100%rename from components/icons/exclamation.svgrename to src/components/icons/exclamation.svgdiff --git a/components/icons/fire.svg b/src/components/icons/fire.svgsimilarity index 100%rename from components/icons/fire.svgrename to src/components/icons/fire.svgdiff --git a/components/icons/github.svg b/src/components/icons/github.svgsimilarity index 100%rename from components/icons/github.svgrename to src/components/icons/github.svgdiff --git a/components/icons/graph1.svg b/src/components/icons/graph1.svgsimilarity index 100%rename from components/icons/graph1.svgrename to src/components/icons/graph1.svgdiff --git a/components/icons/hand.svg b/src/components/icons/hand.svgsimilarity index 100%rename from components/icons/hand.svgrename to src/components/icons/hand.svgdiff --git a/components/icons/home.svg b/src/components/icons/home.svgsimilarity index 100%rename from components/icons/home.svgrename to src/components/icons/home.svgdiff --git a/components/icons/if-need-be.svg b/src/components/icons/if-need-be.svgsimilarity index 100%rename from components/icons/if-need-be.svgrename to src/components/icons/if-need-be.svgdiff --git a/components/icons/location-marker.svg b/src/components/icons/location-marker.svgsimilarity index 100%rename from components/icons/location-marker.svgrename to src/components/icons/location-marker.svgdiff --git a/components/icons/lock-closed.svg b/src/components/icons/lock-closed.svgsimilarity index 100%rename from components/icons/lock-closed.svgrename to src/components/icons/lock-closed.svgdiff --git a/components/icons/lock-open.svg b/src/components/icons/lock-open.svgsimilarity index 100%rename from components/icons/lock-open.svgrename to src/components/icons/lock-open.svgdiff --git a/components/icons/login.svg b/src/components/icons/login.svgsimilarity index 100%rename from components/icons/login.svgrename to src/components/icons/login.svgdiff --git a/components/icons/logout.svg b/src/components/icons/logout.svgsimilarity index 100%rename from components/icons/logout.svgrename to src/components/icons/logout.svgdiff --git a/components/icons/magic.svg b/src/components/icons/magic.svgsimilarity index 100%rename from components/icons/magic.svgrename to src/components/icons/magic.svgdiff --git a/components/icons/menu.svg b/src/components/icons/menu.svgsimilarity index 100%rename from components/icons/menu.svgrename to src/components/icons/menu.svgdiff --git a/components/icons/newspaper.svg b/src/components/icons/newspaper.svgsimilarity index 100%rename from components/icons/newspaper.svgrename to src/components/icons/newspaper.svgdiff --git a/components/icons/pencil-alt.svg b/src/components/icons/pencil-alt.svgsimilarity index 100%rename from components/icons/pencil-alt.svgrename to src/components/icons/pencil-alt.svgdiff --git a/components/icons/pencil.svg b/src/components/icons/pencil.svgsimilarity index 100%rename from components/icons/pencil.svgrename to src/components/icons/pencil.svgdiff --git a/components/icons/plus-circle.svg b/src/components/icons/plus-circle.svgsimilarity index 100%rename from components/icons/plus-circle.svgrename to src/components/icons/plus-circle.svgdiff --git a/components/icons/plus-sm.svg b/src/components/icons/plus-sm.svgsimilarity index 100%rename from components/icons/plus-sm.svgrename to src/components/icons/plus-sm.svgdiff --git a/components/icons/question-mark-circle.svg b/src/components/icons/question-mark-circle.svgsimilarity index 100%rename from components/icons/question-mark-circle.svgrename to src/components/icons/question-mark-circle.svgdiff --git a/components/icons/refresh.svg b/src/components/icons/refresh.svgsimilarity index 100%rename from components/icons/refresh.svgrename to src/components/icons/refresh.svgdiff --git a/components/icons/save.svg b/src/components/icons/save.svgsimilarity index 100%rename from components/icons/save.svgrename to src/components/icons/save.svgdiff --git a/components/icons/server.svg b/src/components/icons/server.svgsimilarity index 100%rename from components/icons/server.svgrename to src/components/icons/server.svgdiff --git a/components/icons/share.svg b/src/components/icons/share.svgsimilarity index 100%rename from components/icons/share.svgrename to src/components/icons/share.svgdiff --git a/components/icons/smile.svg b/src/components/icons/smile.svgsimilarity index 100%rename from components/icons/smile.svgrename to src/components/icons/smile.svgdiff --git a/components/icons/speakerphone.svg b/src/components/icons/speakerphone.svgsimilarity index 100%rename from components/icons/speakerphone.svgrename to src/components/icons/speakerphone.svgdiff --git a/components/icons/spinner.svg b/src/components/icons/spinner.svgsimilarity index 100%rename from components/icons/spinner.svgrename to src/components/icons/spinner.svgdiff --git a/components/icons/star.svg b/src/components/icons/star.svgsimilarity index 100%rename from components/icons/star.svgrename to src/components/icons/star.svgdiff --git a/components/icons/support.svg b/src/components/icons/support.svgsimilarity index 100%rename from components/icons/support.svgrename to src/components/icons/support.svgdiff --git a/components/icons/table.svg b/src/components/icons/table.svgsimilarity index 100%rename from components/icons/table.svgrename to src/components/icons/table.svgdiff --git a/components/icons/trash.svg b/src/components/icons/trash.svgsimilarity index 100%rename from components/icons/trash.svgrename to src/components/icons/trash.svgdiff --git a/components/icons/twitter.svg b/src/components/icons/twitter.svgsimilarity index 100%rename from components/icons/twitter.svgrename to src/components/icons/twitter.svgdiff --git a/components/icons/user-solid.svg b/src/components/icons/user-solid.svgsimilarity index 100%rename from components/icons/user-solid.svgrename to src/components/icons/user-solid.svgdiff --git a/components/icons/user.svg b/src/components/icons/user.svgsimilarity index 100%rename from components/icons/user.svgrename to src/components/icons/user.svgdiff --git a/components/icons/x-circle.svg b/src/components/icons/x-circle.svgsimilarity index 100%rename from components/icons/x-circle.svgrename to src/components/icons/x-circle.svgdiff --git a/components/icons/x.svg b/src/components/icons/x.svgsimilarity index 100%rename from components/icons/x.svgrename to src/components/icons/x.svgdiff --git a/components/login-form.tsx b/src/components/login-form.tsxsimilarity index 92%rename from components/login-form.tsxrename to src/components/login-form.tsxindex 196a322e1..1e50d0803 100644--- a/components/login-form.tsx+++ b/src/components/login-form.tsx@@ -1,18 +1,21 @@-import axios from "axios";import clsx from "clsx";import { useRouter } from "next/router";import { usePlausible } from "next-plausible";import * as React from "react";import { useForm } from "react-hook-form";-import { validEmail } from "utils/form-validation";import Button from "@/components/button";import Magic from "@/components/icons/magic.svg";+import { validEmail } from "@/utils/form-validation";++import { trpc } from "../utils/trpc";const LoginForm: React.VoidFunctionComponent = () => {const { register, formState, handleSubmit, getValues } =useForm<{ email: string }>();+ const login = trpc.useMutation(["login"]);+const plausible = usePlausible();const router = useRouter();return (@@ -26,7 +29,7 @@ const LoginForm: React.VoidFunctionComponent = () => {<formonSubmit={handleSubmit(async ({ email }) => {plausible("Login requested");- await axios.post("/api/login", { email, path: router.asPath });+ await login.mutateAsync({ email, path: router.asPath });})}><div className="mb-2 text-slate-500">diff --git a/components/maintenance.tsx b/src/components/maintenance.tsxsimilarity index 95%rename from components/maintenance.tsxrename to src/components/maintenance.tsxindex 4ac0ec207..2d3afad4a 100644--- a/components/maintenance.tsx+++ b/src/components/maintenance.tsx@@ -2,8 +2,7 @@ import { NextPage } from "next";import Head from "next/head";import Clock from "@/components/icons/clock.svg";--import Logo from "../public/logo.svg";+import Logo from "~/public/logo.svg";const Maintenance: NextPage = () => {return (diff --git a/components/menu-styles.ts b/src/components/menu-styles.tssimilarity index 100%rename from components/menu-styles.tsrename to src/components/menu-styles.tsdiff --git a/components/modal/index.ts b/src/components/modal/index.tssimilarity index 100%rename from components/modal/index.tsrename to src/components/modal/index.tsdiff --git a/components/modal/modal-provider.tsx b/src/components/modal/modal-provider.tsxsimilarity index 100%rename from components/modal/modal-provider.tsxrename to src/components/modal/modal-provider.tsxdiff --git a/components/modal/modal.tsx b/src/components/modal/modal.tsxsimilarity index 100%rename from components/modal/modal.tsxrename to src/components/modal/modal.tsxdiff --git a/components/modal/use-modal.tsx b/src/components/modal/use-modal.tsxsimilarity index 100%rename from components/modal/use-modal.tsxrename to src/components/modal/use-modal.tsxdiff --git a/components/name-input.tsx b/src/components/name-input.tsxsimilarity index 100%rename from components/name-input.tsxrename to src/components/name-input.tsxdiff --git a/components/no-ssr.tsx b/src/components/no-ssr.tsxsimilarity index 100%rename from components/no-ssr.tsxrename to src/components/no-ssr.tsxdiff --git a/components/page-layout.tsx b/src/components/page-layout.tsxsimilarity index 98%rename from components/page-layout.tsxrename to src/components/page-layout.tsxindex c9a24e3f5..8f048d944 100644--- a/components/page-layout.tsx+++ b/src/components/page-layout.tsx@@ -8,8 +8,8 @@ import { createBreakpoint } from "react-use";import DotsVertical from "@/components/icons/dots-vertical.svg";import Github from "@/components/icons/github.svg";+import Logo from "~/public/logo.svg";-import Logo from "../public/logo.svg";import Footer from "./page-layout/footer";const Popover = dynamic(() => import("./popover"), { ssr: false });diff --git a/components/page-layout/footer.tsx b/src/components/page-layout/footer.tsxsimilarity index 97%rename from components/page-layout/footer.tsxrename to src/components/page-layout/footer.tsxindex 932fe30e8..6f1df5d58 100644--- a/components/page-layout/footer.tsx+++ b/src/components/page-layout/footer.tsx@@ -3,8 +3,8 @@ import { Trans, useTranslation } from "next-i18next";import * as React from "react";import GitHubButton from "react-github-btn";-import Logo from "../../public/logo.svg";-import Vercel from "../../public/vercel-logotype-dark.svg";+import Logo from "~/public/logo.svg";+import Vercel from "~/public/vercel-logotype-dark.svg";const Footer: React.VoidFunctionComponent = () => {const { t } = useTranslation("homepage");diff --git a/src/components/participants-provider.tsx b/src/components/participants-provider.tsxnew file mode 100644index 000000000..8c34eac6b--- /dev/null+++ b/src/components/participants-provider.tsx@@ -0,0 +1,40 @@+import { Participant, Vote } from "@prisma/client";+import { useTranslation } from "next-i18next";+import * as React from "react";++import { trpc } from "../utils/trpc";+import FullPageLoader from "./full-page-loader";+import { useRequiredContext } from "./use-required-context";++const ParticipantsContext =+ React.createContext<{+ participants: Array<Participant & { votes: Vote[] }>;+ } | null>(null);++export const useParticipants = () => {+ return useRequiredContext(ParticipantsContext);+};++export const ParticipantsProvider: React.VoidFunctionComponent<{+ children?: React.ReactNode;+ pollId: string;+}> = ({ children, pollId }) => {+ const { t } = useTranslation("app");++ const { data: participants } = trpc.useQuery([+ "polls.participants.list",+ { pollId },+ ]);++ // TODO (Luke Vella) [2022-05-18]: Add mutations here++ if (!participants) {+ return <FullPageLoader>{t("loadingParticipants")}</FullPageLoader>;+ }++ return (+ <ParticipantsContext.Provider value={{ participants }}>+ {children}+ </ParticipantsContext.Provider>+ );+};diff --git a/components/poll-context.tsx b/src/components/poll-context.tsxsimilarity index 71%rename from components/poll-context.tsxrename to src/components/poll-context.tsxindex 70c02a757..7c01f4a71 100644--- a/components/poll-context.tsx+++ b/src/components/poll-context.tsx@@ -1,25 +1,29 @@import { Participant, Vote, VoteType } from "@prisma/client";-import { GetPollResponse } from "api-client/get-poll";import { keyBy } from "lodash";import React from "react";+import {decodeOptions,getBrowserTimeZone,ParsedDateOption,ParsedTimeSlotOption,-} from "utils/date-time-utils";+} from "@/utils/date-time-utils";+import { GetPollApiResponse } from "@/utils/trpc/types";+import { useParticipants } from "./participants-provider";import { usePreferences } from "./preferences/use-preferences";import { useSession } from "./session";import { useRequiredContext } from "./use-required-context";type PollContextValue = {userAlreadyVoted: boolean;- poll: GetPollResponse;+ poll: GetPollApiResponse;targetTimeZone: string;setTargetTimeZone: (timeZone: string) => void;pollType: "date" | "timeSlot";highScore: number;+ optionIds: string[];+ // TODO (Luke Vella) [2022-05-18]: Move this stuff to participants providergetParticipantsWhoVotedForOption: (optionId: string) => Participant[]; // maybe just attach votes to parsed optionsgetScore: (optionId: string) => { yes: number; ifNeedBe: number };getParticipantById: (@@ -41,35 +45,20 @@ export const usePoll = () => {};export const PollContextProvider: React.VoidFunctionComponent<{- value: GetPollResponse;+ value: GetPollApiResponse;children?: React.ReactNode;}> = ({ value: poll, children }) => {+ const { participants } = useParticipants();+const { user } = useSession();const [targetTimeZone, setTargetTimeZone] =React.useState(getBrowserTimeZone);- const participantById = React.useMemo(- () => keyBy(poll.participants, (participant) => participant.id),- [poll.participants],- );-- const participantsByOptionId = React.useMemo(() => {- const res: Record<string, Participant[]> = {};- poll.options.forEach((option) => {- res[option.id] = poll.participants.filter((participant) =>- participant.votes.some(- ({ type, optionId }) => optionId === option.id && type !== "no",- ),- );- });- return res;- }, [poll.options, poll.participants]);-const { locale } = usePreferences();const getScore = React.useCallback((optionId: string) => {- return poll.participants.reduce(+ return (participants ?? []).reduce((acc, curr) => {curr.votes.forEach((vote) => {if (vote.optionId !== optionId) {@@ -87,7 +76,7 @@ export const PollContextProvider: React.VoidFunctionComponent<{{ yes: 0, ifNeedBe: 0 },);},- [poll.participants],+ [participants],);const contextValue = React.useMemo<PollContextValue>(() => {@@ -105,22 +94,39 @@ export const PollContextProvider: React.VoidFunctionComponent<{);const getParticipantById = (participantId: string) => {// TODO (Luke Vella) [2022-04-16]: Build an index instead- const participant = poll.participants.find(- ({ id }) => id === participantId,- );+ const participant = participants?.find(({ id }) => id === participantId);return participant;};- const userAlreadyVoted = user- ? poll.participants.some((participant) =>- user.isGuest- ? participant.guestId === user.id- : participant.userId === user.id,- )- : false;+ const userAlreadyVoted =+ user && participants+ ? participants.some((participant) =>+ user.isGuest+ ? participant.guestId === user.id+ : participant.userId === user.id,+ )+ : false;++ const optionIds = parsedOptions.options.map(({ optionId }) => optionId);++ const participantById = keyBy(+ participants,+ (participant) => participant.id,+ );++ const participantsByOptionId: Record<string, Participant[]> = {};+ poll.options.forEach((option) => {+ participantsByOptionId[option.id] = (participants ?? []).filter(+ (participant) =>+ participant.votes.some(+ ({ type, optionId }) => optionId === option.id && type !== "no",+ ),+ );+ });return {+ optionIds,userAlreadyVoted,poll,getParticipantById: (participantId) => {@@ -140,15 +146,8 @@ export const PollContextProvider: React.VoidFunctionComponent<{targetTimeZone,setTargetTimeZone,};- }, [- getScore,- locale,- participantById,- participantsByOptionId,- poll,- targetTimeZone,- user,- ]);+ }, [getScore, locale, participants, poll, targetTimeZone, user]);+return (<PollContext.Provider value={contextValue}>{children}</PollContext.Provider>);diff --git a/components/poll.tsx b/src/components/poll.tsxsimilarity index 80%rename from components/poll.tsxrename to src/components/poll.tsxindex 6a45fd47a..d6dad2341 100644--- a/components/poll.tsx+++ b/src/components/poll.tsx@@ -1,19 +1,19 @@-import axios from "axios";import { NextPage } from "next";import Head from "next/head";import { useRouter } from "next/router";import { usePlausible } from "next-plausible";import React from "react";import toast from "react-hot-toast";-import { useMutation, useQueryClient } from "react-query";import { useMount } from "react-use";-import { preventWidows } from "utils/prevent-widows";import Button from "@/components/button";import LocationMarker from "@/components/icons/location-marker.svg";import LockClosed from "@/components/icons/lock-closed.svg";import Share from "@/components/icons/share.svg";+import { preventWidows } from "@/utils/prevent-widows";+import { trpc } from "../utils/trpc";+import { useParticipants } from "./participants-provider";import ManagePoll from "./poll/manage-poll";import { useUpdatePollMutation } from "./poll/mutations";import NotificationsToggle from "./poll/notifications-toggle";@@ -34,7 +34,7 @@ const MobilePoll = React.lazy(() => import("@/components/poll/mobile-poll"));const PollPage: NextPage = () => {const { poll } = usePoll();-+ const { participants } = useParticipants();const router = useRouter();useMount(() => {@@ -47,51 +47,42 @@ const PollPage: NextPage = () => {const session = useSession();- const queryClient = useQueryClient();+ const queryClient = trpc.useContext();const plausible = usePlausible();const { mutate: updatePollMutation } = useUpdatePollMutation();- const { mutate: verifyEmail } = useMutation(- async (verificationCode: string) => {- await axios.post(`/api/poll/${poll.urlId}/verify`, {- verificationCode,+ const verifyEmail = trpc.useMutation(["polls.verification.verify"], {+ onSuccess: () => {+ toast.success("Your poll has been verified");+ queryClient.setQueryData(["polls.get", { urlId: poll.urlId }], {+ ...poll,+ verified: true,});+ session.refresh();+ plausible("Verified email");},- {- onSuccess: () => {- toast.success("Your poll has been verified");- queryClient.setQueryData(["getPoll", poll.urlId], {- ...poll,- verified: true,- });- session.refresh();- plausible("Verified email");- },- onSettled: () => {- router.replace(`/admin/${router.query.urlId}`, undefined, {- shallow: true,- });- },- onError: () => {- toast.error("Your link has expired or is no longer valid");- },+ onError: () => {+ toast.error("Your link has expired or is no longer valid");},- );+ onSettled: () => {+ router.replace(`/admin/${router.query.urlId}`, undefined, {+ shallow: true,+ });+ },+ });- React.useEffect(() => {- // TODO (Luke Vella) [2022-03-29]: stop looking for "verificationCode". We switched to- // "code" for compatability with v1 and it's generally better since it's more concise- const verificationCode = router.query.verificationCode ?? router.query.code;- if (typeof verificationCode === "string") {- verifyEmail(verificationCode);+ useMount(() => {+ const { code } = router.query;+ if (typeof code === "string" && !poll.verified) {+ verifyEmail.mutate({ code, pollId: poll.pollId });}- }, [router, verifyEmail]);+ });React.useEffect(() => {if (router.query.unsubscribe) {updatePollMutation(- { notifications: false },+ { urlId: poll.urlId, notifications: false },{onSuccess: () => {toast.success("Notifications have been disabled");@@ -103,7 +94,7 @@ const PollPage: NextPage = () => {shallow: true,});}- }, [plausible, router, updatePollMutation]);+ }, [plausible, poll.urlId, router, updatePollMutation]);const checkIfWideScreen = () => window.innerWidth > 640;@@ -122,8 +113,8 @@ const PollPage: NextPage = () => {const PollComponent = isWideScreen ? DesktopPoll : MobilePoll;const names = React.useMemo(- () => poll.participants.map(({ name }) => name),- [poll.participants],+ () => participants?.map(({ name }) => name) ?? [],+ [participants],);return (@@ -222,11 +213,13 @@ const PollPage: NextPage = () => {<span className="text-xs text-slate-500">No</span></span></div>- <React.Suspense fallback={<div>Loading…</div>}>- <div className="mb-4 lg:mb-8">- <PollComponent pollId={poll.urlId} />- </div>- <Discussion pollId={poll.urlId} />+ <React.Suspense fallback={<div className="p-4">Loading…</div>}>+ {participants ? (+ <div className="mb-4 lg:mb-8">+ <PollComponent />+ </div>+ ) : null}+ <Discussion /></React.Suspense></div></div>diff --git a/components/poll/desktop-poll.tsx b/src/components/poll/desktop-poll.tsxsimilarity index 91%rename from components/poll/desktop-poll.tsxrename to src/components/poll/desktop-poll.tsxindex ee47dea3d..efa248832 100644--- a/components/poll/desktop-poll.tsx+++ b/src/components/poll/desktop-poll.tsx@@ -8,6 +8,7 @@ import Button from "../button";import ArrowLeft from "../icons/arrow-left.svg";import ArrowRight from "../icons/arrow-right.svg";import PlusCircle from "../icons/plus-circle.svg";+import { useParticipants } from "../participants-provider";import { usePoll } from "../poll-context";import TimeZonePicker from "../time-zone-picker";import ParticipantRow from "./desktop-poll/participant-row";@@ -15,7 +16,6 @@ import ParticipantRowForm from "./desktop-poll/participant-row-form";import { PollContext } from "./desktop-poll/poll-context";import PollHeader from "./desktop-poll/poll-header";import { useAddParticipantMutation } from "./mutations";-import { PollProps } from "./types";if (typeof window !== "undefined") {smoothscroll.polyfill();@@ -27,13 +27,15 @@ const MotionParticipantFormRow = motion(ParticipantRowForm);const minSidebarWidth = 180;-const Poll: React.VoidFunctionComponent<PollProps> = ({ pollId }) => {+const Poll: React.VoidFunctionComponent = () => {const { t } = useTranslation("app");const { poll, targetTimeZone, setTargetTimeZone, options, userAlreadyVoted } =usePoll();- const { timeZone, participants } = poll;+ const { participants } = useParticipants();++ const { timeZone } = poll;const [ref, { width }] = useMeasure<HTMLDivElement>();const [editingParticipantId, setEditingParticipantId] =@@ -79,7 +81,7 @@ const Poll: React.VoidFunctionComponent<PollProps> = ({ pollId }) => {const pollWidth =sidebarWidth + options.length * columnWidth + actionColumnWidth;- const { mutate: addParticipant } = useAddParticipantMutation(pollId);+ const addParticipant = useAddParticipantMutation();const goToNextPage = () => {setScrollPosition(@@ -206,18 +208,14 @@ const Poll: React.VoidFunctionComponent<PollProps> = ({ pollId }) => {initial={{ opacity: 0, height: 0 }}animate={{ opacity: 1, height: 55, y: 0 }}className="border-t bg-slate-100 bg-opacity-0"- onSubmit={(data) => {- return new Promise((resolve, reject) => {- addParticipant(data, {- onSuccess: () => {- setShouldShowNewParticipantForm(false);- resolve();- },- onError: reject,- });+ onSubmit={async ({ name, votes }) => {+ await addParticipant.mutateAsync({+ name,+ votes,+ pollId: poll.pollId,});+ setShouldShowNewParticipantForm(false);}}- options={poll.options}onCancel={() => {setShouldShowNewParticipantForm(false);}}@@ -229,10 +227,8 @@ const Poll: React.VoidFunctionComponent<PollProps> = ({ pollId }) => {{participants.map((participant, i) => {return (<ParticipantRow- urlId={pollId}key={i}participant={participant}- options={poll.options}editMode={editingParticipantId === participant.id}onChangeEditMode={(isEditing) => {setEditingParticipantId(isEditing ? participant.id : null);diff --git a/components/poll/desktop-poll/controlled-scroll-area.tsx b/src/components/poll/desktop-poll/controlled-scroll-area.tsxsimilarity index 100%rename from components/poll/desktop-poll/controlled-scroll-area.tsxrename to src/components/poll/desktop-poll/controlled-scroll-area.tsxdiff --git a/components/poll/desktop-poll/participant-row-form.tsx b/src/components/poll/desktop-poll/participant-row-form.tsxsimilarity index 86%rename from components/poll/desktop-poll/participant-row-form.tsxrename to src/components/poll/desktop-poll/participant-row-form.tsxindex 4da7f7428..ae3a4d113 100644--- a/components/poll/desktop-poll/participant-row-form.tsx+++ b/src/components/poll/desktop-poll/participant-row-form.tsx@@ -1,4 +1,3 @@-import { Option } from "@prisma/client";import clsx from "clsx";import * as React from "react";import { Controller, useForm } from "react-hook-form";@@ -10,23 +9,24 @@ import X from "@/components/icons/x.svg";import { requiredString } from "../../../utils/form-validation";import Button from "../../button";import NameInput from "../../name-input";-import { ParticipantForm } from "../types";+import { usePoll } from "../../poll-context";+import { normalizeVotes } from "../mutations";+import { ParticipantForm, ParticipantFormSubmitted } from "../types";import { VoteSelector } from "../vote-selector";import ControlledScrollArea from "./controlled-scroll-area";import { usePollContext } from "./poll-context";export interface ParticipantRowFormProps {defaultValues?: Partial<ParticipantForm>;- onSubmit: (data: ParticipantForm) => Promise<void>;+ onSubmit: (data: ParticipantFormSubmitted) => Promise<void>;className?: string;- options: Option[];onCancel?: () => void;}const ParticipantRowForm: React.ForwardRefRenderFunction<HTMLFormElement,ParticipantRowFormProps-> = ({ defaultValues, onSubmit, className, options, onCancel }, ref) => {+> = ({ defaultValues, onSubmit, className, onCancel }, ref) => {const {setActiveOptionId,activeOptionId,@@ -38,12 +38,13 @@ const ParticipantRowForm: React.ForwardRefRenderFunction<setScrollPosition,} = usePollContext();+ const { options, optionIds } = usePoll();const {handleSubmit,control,formState: { errors, submitCount, isSubmitting },reset,- } = useForm<ParticipantForm>({+ } = useForm({defaultValues: {name: "",votes: [],@@ -71,8 +72,7 @@ const ParticipantRowForm: React.ForwardRefRenderFunction<onSubmit={handleSubmit(async ({ name, votes }) => {await onSubmit({name,- // no need to create votes for "no"- votes,+ votes: normalizeVotes(optionIds, votes),});reset();})}@@ -114,20 +114,20 @@ const ParticipantRowForm: React.ForwardRefRenderFunction<render={({ field }) => {return (<ControlledScrollArea>- {options.map((option, index) => {+ {options.map(({ optionId }, index) => {const value = field.value[index];return (<div- key={option.id}+ key={optionId}className={clsx("flex shrink-0 items-center justify-center transition-colors",{- "bg-gray-50": activeOptionId === option.id,+ "bg-gray-50": activeOptionId === optionId,},)}style={{ width: columnWidth }}- onMouseOver={() => setActiveOptionId(option.id)}+ onMouseOver={() => setActiveOptionId(optionId)}onMouseOut={() => setActiveOptionId(null)}><VoteSelector@@ -147,14 +147,14 @@ const ParticipantRowForm: React.ForwardRefRenderFunction<}}onChange={(vote) => {const newValue = [...field.value];- newValue[index] = { optionId: option.id, type: vote };+ newValue[index] = { optionId, type: vote };field.onChange(newValue);}}ref={(el) => {checkboxRefs.current[index] = el;}}onFocus={() => {- setActiveOptionId(option.id);+ setActiveOptionId(optionId);}}/></div>diff --git a/components/poll/desktop-poll/participant-row.tsx b/src/components/poll/desktop-poll/participant-row.tsxsimilarity index 74%rename from components/poll/desktop-poll/participant-row.tsxrename to src/components/poll/desktop-poll/participant-row.tsxindex 24f1d1726..d1332918d 100644--- a/components/poll/desktop-poll/participant-row.tsx+++ b/src/components/poll/desktop-poll/participant-row.tsx@@ -1,4 +1,4 @@-import { Option, Participant, Vote } from "@prisma/client";+import { Participant, Vote } from "@prisma/client";import clsx from "clsx";import * as React from "react";@@ -17,30 +17,25 @@ import ParticipantRowForm from "./participant-row-form";import { usePollContext } from "./poll-context";export interface ParticipantRowProps {- urlId: string;participant: Participant & { votes: Vote[] };- options: Option[];editMode: boolean;onChangeEditMode?: (value: boolean) => void;}const ParticipantRow: React.VoidFunctionComponent<ParticipantRowProps> = ({- urlId,participant,- options,editMode,onChangeEditMode,}) => {const { setActiveOptionId, activeOptionId, columnWidth, sidebarWidth } =usePollContext();- const { mutate: updateParticipantMutation } =- useUpdateParticipantMutation(urlId);+ const updateParticipant = useUpdateParticipantMutation();const confirmDeleteParticipant = useDeleteParticipantModal();const session = useSession();- const { poll, getVote } = usePoll();+ const { poll, getVote, options } = usePoll();const isYou = session.user && session.ownsObject(participant) ? true : false;@@ -54,30 +49,20 @@ const ParticipantRow: React.VoidFunctionComponent<ParticipantRowProps> = ({<ParticipantRowFormdefaultValues={{name: participant.name,- votes: options.map(({ id }) => {- const type = getVote(participant.id, id);- return type ? { optionId: id, type } : undefined;+ votes: options.map(({ optionId }) => {+ const type = getVote(participant.id, optionId);+ return type ? { optionId, type } : undefined;}),}}onSubmit={async ({ name, votes }) => {- return new Promise((resolve, reject) => {- updateParticipantMutation(- {- participantId: participant.id,- votes,- name,- },- {- onSuccess: () => {- onChangeEditMode?.(false);- resolve();- },- onError: reject,- },- );+ await updateParticipant.mutateAsync({+ participantId: participant.id,+ pollId: poll.pollId,+ votes,+ name,});+ onChangeEditMode?.(false);}}- options={options}onCancel={() => onChangeEditMode?.(false)}/>);@@ -117,19 +102,19 @@ const ParticipantRow: React.VoidFunctionComponent<ParticipantRowProps> = ({) : null}</div><ControlledScrollArea>- {options.map((option) => {- const vote = getVote(participant.id, option.id);+ {options.map(({ optionId }) => {+ const vote = getVote(participant.id, optionId);return (<div- key={option.id}+ key={optionId}className={clsx("flex shrink-0 items-center justify-center transition-colors",{- "bg-gray-50": activeOptionId === option.id,+ "bg-gray-50": activeOptionId === optionId,},)}style={{ width: columnWidth }}- onMouseOver={() => setActiveOptionId(option.id)}+ onMouseOver={() => setActiveOptionId(optionId)}onMouseOut={() => setActiveOptionId(null)}><VoteIcon type={vote} />diff --git a/components/poll/desktop-poll/poll-context.ts b/src/components/poll/desktop-poll/poll-context.tssimilarity index 100%rename from components/poll/desktop-poll/poll-context.tsrename to src/components/poll/desktop-poll/poll-context.tsdiff --git a/components/poll/desktop-poll/poll-header.tsx b/src/components/poll/desktop-poll/poll-header.tsxsimilarity index 100%rename from components/poll/desktop-poll/poll-header.tsxrename to src/components/poll/desktop-poll/poll-header.tsxdiff --git a/components/poll/legacy-poll-notice.tsx b/src/components/poll/legacy-poll-notice.tsxsimilarity index 100%rename from components/poll/legacy-poll-notice.tsxrename to src/components/poll/legacy-poll-notice.tsxdiff --git a/components/poll/manage-poll.tsx b/src/components/poll/manage-poll.tsxsimilarity index 92%rename from components/poll/manage-poll.tsxrename to src/components/poll/manage-poll.tsxindex 2efc948fd..43a60a13f 100644--- a/components/poll/manage-poll.tsx+++ b/src/components/poll/manage-poll.tsx@@ -1,7 +1,6 @@import { Placement } from "@floating-ui/react-dom-interactions";import { Trans, useTranslation } from "next-i18next";import * as React from "react";-import { encodeDateOption } from "utils/date-time-utils";import Button from "@/components/button";import Cog from "@/components/icons/cog.svg";@@ -10,6 +9,7 @@ import LockOpen from "@/components/icons/lock-open.svg";import Pencil from "@/components/icons/pencil-alt.svg";import Save from "@/components/icons/save.svg";import Table from "@/components/icons/table.svg";+import { encodeDateOption } from "@/utils/date-time-utils";import Dropdown, { DropdownItem } from "../dropdown";import { PollDetailsForm } from "../forms";@@ -96,6 +96,7 @@ const ManagePoll: React.VoidFunctionComponent<{const onOk = () => {updatePollMutation({+ urlId: poll.urlId,timeZone: data.timeZone,optionsToDelete: optionsToDelete.map(({ id }) => id),optionsToAdd,@@ -161,7 +162,10 @@ const ManagePoll: React.VoidFunctionComponent<{className="p-4"onSubmit={(data) => {//submit- updatePollMutation(data, { onSuccess: closePollDetailsModal });+ updatePollMutation(+ { urlId: poll.urlId, ...data },+ { onSuccess: closePollDetailsModal },+ );}}/>),@@ -189,13 +193,17 @@ const ManagePoll: React.VoidFunctionComponent<{<DropdownItemicon={LockOpen}label="Unlock poll"- onClick={() => updatePollMutation({ closed: false })}+ onClick={() =>+ updatePollMutation({ urlId: poll.urlId, closed: false })+ }/>) : (<DropdownItemicon={LockClosed}label="Lock poll"- onClick={() => updatePollMutation({ closed: true })}+ onClick={() =>+ updatePollMutation({ urlId: poll.urlId, closed: true })+ }/>)}</Dropdown>diff --git a/components/poll/manage-poll/use-csv-exporter.ts b/src/components/poll/manage-poll/use-csv-exporter.tssimilarity index 89%rename from components/poll/manage-poll/use-csv-exporter.tsrename to src/components/poll/manage-poll/use-csv-exporter.tsindex 0c5f6867a..bb49b2e9b 100644--- a/components/poll/manage-poll/use-csv-exporter.ts+++ b/src/components/poll/manage-poll/use-csv-exporter.ts@@ -3,15 +3,17 @@ import { useTranslation } from "next-i18next";import { usePoll } from "@/components/poll-context";+import { useParticipants } from "../../participants-provider";+export const useCsvExporter = () => {const { poll, options } = usePoll();const { t } = useTranslation("app");-+ const { participants } = useParticipants();return {exportToCsv: () => {const header = [t("participantCount", {- count: poll.participants.length,+ count: participants.length,}),...options.map((decodedOption) => {const day = `${decodedOption.dow} ${decodedOption.day} ${decodedOption.month}`;@@ -20,7 +22,7 @@ export const useCsvExporter = () => {: `${day} ${decodedOption.startTime} - ${decodedOption.endTime}`;}),].join(",");- const rows = poll.participants.map((participant) => {+ const rows = participants.map((participant) => {return [participant.name,...poll.options.map((option) => {diff --git a/components/poll/mobile-poll.tsx b/src/components/poll/mobile-poll.tsxsimilarity index 89%rename from components/poll/mobile-poll.tsxrename to src/components/poll/mobile-poll.tsxindex 4d2e420b5..e8a66de11 100644--- a/components/poll/mobile-poll.tsx+++ b/src/components/poll/mobile-poll.tsx@@ -18,15 +18,17 @@ import { requiredString } from "../../utils/form-validation";import Button from "../button";import { styleMenuItem } from "../menu-styles";import NameInput from "../name-input";+import { useParticipants } from "../participants-provider";import { isUnclaimed, useSession } from "../session";import TimeZonePicker from "../time-zone-picker";import PollOptions from "./mobile-poll/poll-options";import TimeSlotOptions from "./mobile-poll/time-slot-options";import {+ normalizeVotes,useAddParticipantMutation,useUpdateParticipantMutation,} from "./mutations";-import { ParticipantForm, PollProps } from "./types";+import { ParticipantForm } from "./types";import { useDeleteParticipantModal } from "./use-delete-participant-modal";import UserAvatar from "./user-avatar";@@ -34,13 +36,19 @@ if (typeof window !== "undefined") {smoothscroll.polyfill();}-const MobilePoll: React.VoidFunctionComponent<PollProps> = ({ pollId }) => {+const MobilePoll: React.VoidFunctionComponent = () => {const pollContext = usePoll();- const { poll, targetTimeZone, setTargetTimeZone, getParticipantById } =- pollContext;+ const {+ poll,+ targetTimeZone,+ setTargetTimeZone,+ getParticipantById,+ optionIds,+ } = pollContext;- const { timeZone, participants, role } = poll;+ const { participants } = useParticipants();+ const { timeZone, role } = poll;const session = useSession();@@ -86,10 +94,9 @@ const MobilePoll: React.VoidFunctionComponent<PollProps> = ({ pollId }) => {const { t } = useTranslation("app");- const { mutate: updateParticipantMutation } =- useUpdateParticipantMutation(pollId);+ const updateParticipant = useUpdateParticipantMutation();- const { mutate: addParticipantMutation } = useAddParticipantMutation(pollId);+ const addParticipant = useAddParticipantMutation();const confirmDeleteParticipant = useDeleteParticipantModal();const submitContainerRef = React.useRef<HTMLDivElement>(null);@@ -111,33 +118,24 @@ const MobilePoll: React.VoidFunctionComponent<PollProps> = ({ pollId }) => {<formref={formRef}className="border-t border-b bg-white shadow-sm"- onSubmit={handleSubmit((data) => {- return new Promise<ParticipantForm>((resolve, reject) => {- if (selectedParticipant) {- updateParticipantMutation(- {- participantId: selectedParticipant.id,- ...data,- },- {- onSuccess: () => {- resolve(data);- setIsEditing(false);- },- onError: reject,- },- );- } else {- addParticipantMutation(data, {- onSuccess: (newParticipant) => {- setSelectedParticipantId(newParticipant.id);- resolve(data);- setIsEditing(false);- },- onError: reject,- });- }- });+ onSubmit={handleSubmit(async ({ name, votes }) => {+ if (selectedParticipant) {+ await updateParticipant.mutateAsync({+ pollId: poll.pollId,+ participantId: selectedParticipant.id,+ name,+ votes: normalizeVotes(optionIds, votes),+ });+ setIsEditing(false);+ } else {+ const newParticipant = await addParticipant.mutateAsync({+ pollId: poll.pollId,+ name,+ votes: normalizeVotes(optionIds, votes),+ });+ setSelectedParticipantId(newParticipant.id);+ setIsEditing(false);+ }})}><div className="sticky top-12 z-30 flex flex-col space-y-2 border-b bg-gray-50 p-3">diff --git a/components/poll/mobile-poll/date-option.tsx b/src/components/poll/mobile-poll/date-option.tsxsimilarity index 100%rename from components/poll/mobile-poll/date-option.tsxrename to src/components/poll/mobile-poll/date-option.tsxdiff --git a/components/poll/mobile-poll/poll-option.tsx b/src/components/poll/mobile-poll/poll-option.tsxsimilarity index 100%rename from components/poll/mobile-poll/poll-option.tsxrename to src/components/poll/mobile-poll/poll-option.tsxdiff --git a/components/poll/mobile-poll/poll-options.tsx b/src/components/poll/mobile-poll/poll-options.tsxsimilarity index 98%rename from components/poll/mobile-poll/poll-options.tsxrename to src/components/poll/mobile-poll/poll-options.tsxindex 3b25579c7..918915e82 100644--- a/components/poll/mobile-poll/poll-options.tsx+++ b/src/components/poll/mobile-poll/poll-options.tsx@@ -1,9 +1,9 @@import { VoteType } from "@prisma/client";import * as React from "react";import { Controller, useFormContext } from "react-hook-form";-import { ParsedDateTimeOpton } from "utils/date-time-utils";import { usePoll } from "@/components/poll-context";+import { ParsedDateTimeOpton } from "@/utils/date-time-utils";import { ParticipantForm } from "../types";import DateOption from "./date-option";diff --git a/components/poll/mobile-poll/time-slot-option.tsx b/src/components/poll/mobile-poll/time-slot-option.tsxsimilarity index 100%rename from components/poll/mobile-poll/time-slot-option.tsxrename to src/components/poll/mobile-poll/time-slot-option.tsxdiff --git a/components/poll/mobile-poll/time-slot-options.tsx b/src/components/poll/mobile-poll/time-slot-options.tsxsimilarity index 94%rename from components/poll/mobile-poll/time-slot-options.tsxrename to src/components/poll/mobile-poll/time-slot-options.tsxindex c03fc1500..a03b38116 100644--- a/components/poll/mobile-poll/time-slot-options.tsx+++ b/src/components/poll/mobile-poll/time-slot-options.tsx@@ -1,6 +1,7 @@import { groupBy } from "lodash";import * as React from "react";-import { ParsedTimeSlotOption } from "utils/date-time-utils";++import { ParsedTimeSlotOption } from "@/utils/date-time-utils";import PollOptions from "./poll-options";diff --git a/src/components/poll/mutations.ts b/src/components/poll/mutations.tsnew file mode 100644index 000000000..32b452d4e--- /dev/null+++ b/src/components/poll/mutations.ts@@ -0,0 +1,90 @@+import { usePlausible } from "next-plausible";++import { trpc } from "../../utils/trpc";+import { usePoll } from "../poll-context";+import { useSession } from "../session";+import { ParticipantForm } from "./types";++export const normalizeVotes = (+ optionIds: string[],+ votes: ParticipantForm["votes"],+) => {+ return optionIds.map(+ (optionId, i) => votes[i] ?? { optionId, type: "no" as const },+ );+};++export const useAddParticipantMutation = () => {+ const queryClient = trpc.useContext();+ const session = useSession();+ const plausible = usePlausible();++ return trpc.useMutation(["polls.participants.add"], {+ onSuccess: (participant) => {+ plausible("Add participant");+ queryClient.setQueryData(+ ["polls.participants.list", { pollId: participant.pollId }],+ (existingParticipants = []) => {+ return [participant, ...existingParticipants];+ },+ );+ session.refresh();+ },+ });+};++export const useUpdateParticipantMutation = () => {+ const queryClient = trpc.useContext();+ const plausible = usePlausible();+ return trpc.useMutation("polls.participants.update", {+ onSuccess: (participant) => {+ plausible("Update participant");+ queryClient.setQueryData(+ ["polls.participants.list", { pollId: participant.pollId }],+ (existingParticipants = []) => {+ const newParticipants = [...existingParticipants];++ const index = newParticipants.findIndex(+ ({ id }) => id === participant.id,+ );++ if (index !== -1) {+ newParticipants[index] = participant;+ }++ return newParticipants;+ },+ );+ },+ });+};++export const useDeleteParticipantMutation = () => {+ const queryClient = trpc.useContext();+ const plausible = usePlausible();+ return trpc.useMutation("polls.participants.delete", {+ onMutate: ({ participantId, pollId }) => {+ queryClient.setQueryData(+ ["polls.participants.list", { pollId: pollId }],+ (existingParticipants = []) => {+ return existingParticipants.filter(({ id }) => id !== participantId);+ },+ );+ },+ onSuccess: () => {+ plausible("Remove participant");+ },+ });+};++export const useUpdatePollMutation = () => {+ const { poll } = usePoll();+ const plausible = usePlausible();+ const queryClient = trpc.useContext();+ return trpc.useMutation(["polls.update"], {+ onSuccess: (data) => {+ queryClient.setQueryData(["polls.get", { urlId: poll.urlId }], data);+ plausible("Updated poll");+ },+ });+};diff --git a/components/poll/notifications-toggle.tsx b/src/components/poll/notifications-toggle.tsxsimilarity index 98%rename from components/poll/notifications-toggle.tsxrename to src/components/poll/notifications-toggle.tsxindex d4fe49fd7..a2bd284e1 100644--- a/components/poll/notifications-toggle.tsx+++ b/src/components/poll/notifications-toggle.tsx@@ -59,6 +59,7 @@ const NotificationsToggle: React.VoidFunctionComponent = () => {setIsUpdatingNotifications(true);updatePollMutation({+ urlId: poll.urlId,notifications: !poll.notifications,},{diff --git a/components/poll/poll-subheader.tsx b/src/components/poll/poll-subheader.tsxsimilarity index 86%rename from components/poll/poll-subheader.tsxrename to src/components/poll/poll-subheader.tsxindex ca3c02415..b3819fc78 100644--- a/components/poll/poll-subheader.tsx+++ b/src/components/poll/poll-subheader.tsx@@ -1,9 +1,8 @@-import axios from "axios";import { formatRelative } from "date-fns";import { Trans, useTranslation } from "next-i18next";import * as React from "react";-import { useMutation } from "react-query";+import { trpc } from "../../utils/trpc";import Badge from "../badge";import Button from "../button";import { usePoll } from "../poll-context";@@ -15,13 +14,10 @@ const PollSubheader: React.VoidFunctionComponent = () => {const { poll } = usePoll();const { t } = useTranslation("app");const { locale } = usePreferences();- const {- mutate: sendVerificationEmail,- isLoading: isSendingVerificationEmail,- isSuccess: didSendVerificationEmail,- } = useMutation(async () => {- await axios.post(`/api/poll/${poll.urlId}/verify`);- });+ const requestVerificationEmail = trpc.useMutation(+ "polls.verification.request",+ );+return (<div className="text-slate-500"><div className="md:inline">@@ -61,16 +57,19 @@ const PollSubheader: React.VoidFunctionComponent = () => {}}/></div>- {didSendVerificationEmail ? (+ {requestVerificationEmail.isSuccess ? (<div className="text-green-500">Verification email sent.</div>) : (<ButtononClick={() => {- sendVerificationEmail();+ requestVerificationEmail.mutate({+ pollId: poll.pollId,+ adminUrlId: poll.urlId,+ });}}- loading={isSendingVerificationEmail}+ loading={requestVerificationEmail.isLoading}>Resend verification email</Button>diff --git a/components/poll/score-summary.tsx b/src/components/poll/score-summary.tsxsimilarity index 100%rename from components/poll/score-summary.tsxrename to src/components/poll/score-summary.tsxdiff --git a/components/poll/truncated-linkify.tsx b/src/components/poll/truncated-linkify.tsxsimilarity index 100%rename from components/poll/truncated-linkify.tsxrename to src/components/poll/truncated-linkify.tsxdiff --git a/components/poll/types.ts b/src/components/poll/types.tssimilarity index 86%rename from components/poll/types.tsrename to src/components/poll/types.tsindex ec0cc9d4d..422adb094 100644--- a/components/poll/types.ts+++ b/src/components/poll/types.ts@@ -15,6 +15,3 @@ export interface ParticipantFormSubmitted {name: string;votes: Array<{ optionId: string; type: VoteType }>;}-export interface PollProps {- pollId: string;-}diff --git a/components/poll/use-delete-participant-modal.ts b/src/components/poll/use-delete-participant-modal.tssimilarity index 81%rename from components/poll/use-delete-participant-modal.tsrename to src/components/poll/use-delete-participant-modal.tsindex 719272be3..e06918a03 100644--- a/components/poll/use-delete-participant-modal.ts+++ b/src/components/poll/use-delete-participant-modal.ts@@ -5,9 +5,9 @@ import { useDeleteParticipantMutation } from "./mutations";export const useDeleteParticipantModal = () => {const { render } = useModalContext();- const { mutate: deleteParticipant } = useDeleteParticipantMutation();+ const deleteParticipant = useDeleteParticipantMutation();const {- poll: { urlId },+ poll: { pollId },} = usePoll();return (participantId: string) => {@@ -20,8 +20,8 @@ export const useDeleteParticipantModal = () => {},okText: "Delete",onOk: () => {- deleteParticipant({- pollId: urlId,+ deleteParticipant.mutate({+ pollId,participantId,});},diff --git a/components/poll/user-avatar.tsx b/src/components/poll/user-avatar.tsxsimilarity index 98%rename from components/poll/user-avatar.tsxrename to src/components/poll/user-avatar.tsxindex 96001e54d..1d8854e9c 100644--- a/components/poll/user-avatar.tsx+++ b/src/components/poll/user-avatar.tsx@@ -1,6 +1,7 @@import clsx from "clsx";import * as React from "react";-import { stringToValue } from "utils/string-to-value";++import { stringToValue } from "@/utils/string-to-value";import Badge from "../badge";diff --git a/components/poll/vote-icon.tsx b/src/components/poll/vote-icon.tsxsimilarity index 100%rename from components/poll/vote-icon.tsxrename to src/components/poll/vote-icon.tsxdiff --git a/components/poll/vote-selector.tsx b/src/components/poll/vote-selector.tsxsimilarity index 100%rename from components/poll/vote-selector.tsxrename to src/components/poll/vote-selector.tsxdiff --git a/components/popover.tsx b/src/components/popover.tsxsimilarity index 96%rename from components/popover.tsxrename to src/components/popover.tsxindex bd92b7b06..e07acb5a0 100644--- a/components/popover.tsx+++ b/src/components/popover.tsx@@ -10,7 +10,8 @@ import { Popover as HeadlessPopover } from "@headlessui/react";import clsx from "clsx";import { motion } from "framer-motion";import React from "react";-import { transformOriginByPlacement } from "utils/constants";++import { transformOriginByPlacement } from "@/utils/constants";interface PopoverProps {trigger: React.ReactElement;diff --git a/components/preferences.tsx b/src/components/preferences.tsxsimilarity index 100%rename from components/preferences.tsxrename to src/components/preferences.tsxdiff --git a/components/preferences/preferences-provider.tsx b/src/components/preferences/preferences-provider.tsxsimilarity index 100%rename from components/preferences/preferences-provider.tsxrename to src/components/preferences/preferences-provider.tsxdiff --git a/components/preferences/use-preferences.tsx b/src/components/preferences/use-preferences.tsxsimilarity index 100%rename from components/preferences/use-preferences.tsxrename to src/components/preferences/use-preferences.tsxdiff --git a/components/session.tsx b/src/components/session.tsxsimilarity index 85%rename from components/session.tsxrename to src/components/session.tsxindex 4820f28ef..9e332313c 100644--- a/components/session.tsx+++ b/src/components/session.tsx@@ -1,7 +1,7 @@-import axios from "axios";import { IronSessionData } from "iron-session";import React from "react";-import { useQuery, useQueryClient } from "react-query";++import { trpc } from "@/utils/trpc";import { useRequiredContext } from "./use-required-context";@@ -17,7 +17,7 @@ type ParticipantOrComment = {};type SessionContextValue = {- logout: () => Promise<void>;+ logout: () => void;user: (UserSessionData & { shortName: string }) | null;refresh: () => void;ownsObject: (obj: ParticipantOrComment) => boolean;@@ -33,14 +33,17 @@ export const SessionProvider: React.VoidFunctionComponent<{children?: React.ReactNode;session: UserSessionData | null;}> = ({ children, session }) => {- const queryClient = useQueryClient();+ const queryClient = trpc.useContext();const {data: user = session,refetch,isLoading,- } = useQuery(["user"], async () => {- const res = await axios.get<{ user: UserSessionData | null }>("/api/user");- return res.data.user;+ } = trpc.useQuery(["session.get"]);++ const { mutate: logout } = trpc.useMutation(["session.destroy"], {+ onMutate: () => {+ queryClient.setQueryData(["session.get"], null);+ },});const sessionData: SessionContextValue = {@@ -61,9 +64,8 @@ export const SessionProvider: React.VoidFunctionComponent<{refetch();},isLoading,- logout: async () => {- queryClient.setQueryData(["user"], null);- await axios.post("/api/logout");+ logout: () => {+ logout();},ownsObject: (obj) => {if (!user) {diff --git a/components/sharing.tsx b/src/components/sharing.tsxsimilarity index 100%rename from components/sharing.tsxrename to src/components/sharing.tsxdiff --git a/components/standard-layout.tsx b/src/components/standard-layout.tsxsimilarity index 99%rename from components/standard-layout.tsxrename to src/components/standard-layout.tsxindex d6e9e9eab..bff625784 100644--- a/components/standard-layout.tsx+++ b/src/components/standard-layout.tsx@@ -5,8 +5,8 @@ import React from "react";import Menu from "@/components/icons/menu.svg";import User from "@/components/icons/user.svg";+import Logo from "~/public/logo.svg";-import Logo from "../public/logo.svg";import Dropdown, { DropdownItem, DropdownProps } from "./dropdown";import Adjustments from "./icons/adjustments.svg";import Cash from "./icons/cash.svg";diff --git a/components/steps/index.ts b/src/components/steps/index.tssimilarity index 100%rename from components/steps/index.tsrename to src/components/steps/index.tsdiff --git a/components/steps/step.tsx b/src/components/steps/step.tsxsimilarity index 100%rename from components/steps/step.tsxrename to src/components/steps/step.tsxdiff --git a/components/steps/steps.tsx b/src/components/steps/steps.tsxsimilarity index 100%rename from components/steps/steps.tsxrename to src/components/steps/steps.tsxdiff --git a/components/switch.tsx b/src/components/switch.tsxsimilarity index 100%rename from components/switch.tsxrename to src/components/switch.tsxdiff --git a/components/time-zone-picker/index.ts b/src/components/time-zone-picker/index.tssimilarity index 100%rename from components/time-zone-picker/index.tsrename to src/components/time-zone-picker/index.tsdiff --git a/components/time-zone-picker/time-zone-picker.tsx b/src/components/time-zone-picker/time-zone-picker.tsxsimilarity index 100%rename from components/time-zone-picker/time-zone-picker.tsxrename to src/components/time-zone-picker/time-zone-picker.tsxdiff --git a/components/time-zone-picker/time-zones.json b/src/components/time-zone-picker/time-zones.jsonsimilarity index 100%rename from components/time-zone-picker/time-zones.jsonrename to src/components/time-zone-picker/time-zones.jsondiff --git a/components/tooltip.tsx b/src/components/tooltip.tsxsimilarity index 98%rename from components/tooltip.tsxrename to src/components/tooltip.tsxindex 001dd6f3b..0ed21c155 100644--- a/components/tooltip.tsx+++ b/src/components/tooltip.tsx@@ -14,7 +14,8 @@ import {import clsx from "clsx";import { AnimatePresence, motion } from "framer-motion";import * as React from "react";-import { preventWidows } from "utils/prevent-widows";++import { preventWidows } from "@/utils/prevent-widows";export interface TooltipProps {placement?: Placement;diff --git a/components/use-required-context.ts b/src/components/use-required-context.tssimilarity index 100%rename from components/use-required-context.tsrename to src/components/use-required-context.tsdiff --git a/pages/404.tsx b/src/pages/404.tsxsimilarity index 100%rename from pages/404.tsxrename to src/pages/404.tsxdiff --git a/src/pages/_app.tsx b/src/pages/_app.tsxnew file mode 100644index 000000000..e8c0611d1--- /dev/null+++ b/src/pages/_app.tsx@@ -0,0 +1,78 @@+import "react-big-calendar/lib/css/react-big-calendar.css";+import "tailwindcss/tailwind.css";+import "~/style.css";++import { withTRPC } from "@trpc/next";+import axios from "axios";+import { NextPage } from "next";+import { AppProps } from "next/app";+import dynamic from "next/dynamic";+import Head from "next/head";+import { appWithTranslation } from "next-i18next";+import PlausibleProvider from "next-plausible";+import toast, { Toaster } from "react-hot-toast";+import { MutationCache } from "react-query";+import superjson from "superjson";++import Maintenance from "@/components/maintenance";+import ModalProvider from "@/components/modal/modal-provider";+import PreferencesProvider from "@/components/preferences/preferences-provider";+import { absoluteUrl } from "@/utils/absolute-url";++import { AppRouter } from "./api/trpc/[trpc]";++const CrispChat = dynamic(() => import("@/components/crisp-chat"), {+ ssr: false,+});++const MyApp: NextPage<AppProps> = ({ Component, pageProps }) => {+ if (process.env.NEXT_PUBLIC_MAINTENANCE_MODE === "1") {+ return <Maintenance />;+ }+ return (+ <PlausibleProvider+ domain="rallly.co"+ customDomain={process.env.PLAUSIBLE_DOMAIN}+ trackOutboundLinks={true}+ selfHosted={true}+ enabled={!!process.env.PLAUSIBLE_DOMAIN}+ >+ <PreferencesProvider>+ <Head>+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ </Head>+ <CrispChat />+ <Toaster />+ <ModalProvider>+ <Component {...pageProps} />+ </ModalProvider>+ </PreferencesProvider>+ </PlausibleProvider>+ );+};++export default withTRPC<AppRouter>({+ config() {+ const url = `${absoluteUrl()}/api/trpc`;++ return {+ transformer: superjson,+ url,+ /**+ * @link https://react-query.tanstack.com/reference/QueryClient+ */+ queryClientConfig: {+ mutationCache: new MutationCache({+ onError: (error) => {+ if (axios.isAxiosError(error) && error.response?.status === 500) {+ toast.error(+ "Uh oh! Something went wrong. The issue has been logged and we'll fix it as soon as possible. Please try again later.",+ );+ }+ },+ }),+ },+ };+ },+ ssr: false, // doesn't play well with how we're fetching legacy endpoints. consider switching it on when we don't need to get legacy polls+})(appWithTranslation(MyApp));diff --git a/pages/_document.tsx b/src/pages/_document.tsxsimilarity index 100%rename from pages/_document.tsxrename to src/pages/_document.tsxdiff --git a/pages/_error.tsx b/src/pages/_error.tsxsimilarity index 100%rename from pages/_error.tsxrename to src/pages/_error.tsxdiff --git a/pages/api/legacy/[urlId].ts b/src/pages/api/legacy/[urlId].tssimilarity index 92%rename from pages/api/legacy/[urlId].tsrename to src/pages/api/legacy/[urlId].tsindex 0c38c9539..e18254f7e 100644--- a/pages/api/legacy/[urlId].ts+++ b/src/pages/api/legacy/[urlId].ts@@ -1,12 +1,12 @@import { VoteType } from "@prisma/client";-import { GetPollApiResponse } from "api-client/get-poll";import { NextApiRequest, NextApiResponse } from "next";-import { getQueryParam } from "utils/api-utils";-import { LegacyPoll } from "utils/legacy-utils";-import { getMongoClient } from "utils/mongodb-client";-import { nanoid } from "utils/nanoid";-import { prisma } from "../../../db";+import { getQueryParam } from "@/utils/api-utils";+import { LegacyPoll } from "@/utils/legacy-utils";+import { getMongoClient } from "@/utils/mongodb-client";+import { nanoid } from "@/utils/nanoid";+import { GetPollApiResponse } from "@/utils/trpc/types";+import { prisma } from "~/prisma/db";export default async function handler(req: NextApiRequest,diff --git a/src/pages/api/trpc/[trpc].ts b/src/pages/api/trpc/[trpc].tsnew file mode 100644index 000000000..15a717b20--- /dev/null+++ b/src/pages/api/trpc/[trpc].ts@@ -0,0 +1,31 @@+import * as trpcNext from "@trpc/server/adapters/next";+import superjson from "superjson";++import { createContext } from "../../../server/context";+import { createRouter } from "../../../server/createRouter";+import { login } from "../../../server/routers/login";+import { polls } from "../../../server/routers/polls";+import { session } from "../../../server/routers/session";+import { withSessionRoute } from "../../../utils/auth";++export const appRouter = createRouter()+ .transformer(superjson)+ .merge("session.", session)+ .merge("polls.", polls)+ .merge(login);++// export type definition of API+export type AppRouter = typeof appRouter;++export const config = {+ api: {+ externalResolver: true,+ },+};+// export API handler+export default withSessionRoute(+ trpcNext.createNextApiHandler({+ router: appRouter,+ createContext,+ }),+);diff --git a/pages/demo.tsx b/src/pages/demo.tsxsimilarity index 81%rename from pages/demo.tsxrename to src/pages/demo.tsxindex c8adf0844..fc4f5ec2d 100644--- a/pages/demo.tsx+++ b/src/pages/demo.tsx@@ -6,18 +6,20 @@ import { usePlausible } from "next-plausible";import React from "react";import { useMount } from "react-use";-import { createDemo } from "../api-client/create-demo";import FullPageLoader from "../components/full-page-loader";+import { trpc } from "../utils/trpc";const Demo: NextPage = () => {const { t } = useTranslation("app");const router = useRouter();const plausible = usePlausible();+ const createDemo = trpc.useMutation(["polls.demo.create"]);+useMount(async () => {- const poll = await createDemo();+ const urlId = await createDemo.mutateAsync();plausible("Create demo poll");- router.replace(`/admin/${poll.urlId}`);+ router.replace(`/admin/${urlId}`);});return <FullPageLoader>{t("creatingDemo")}</FullPageLoader>;diff --git a/pages/home.tsx b/src/pages/home.tsxsimilarity index 100%rename from pages/home.tsxrename to src/pages/home.tsxdiff --git a/pages/login.tsx b/src/pages/login.tsxsimilarity index 93%rename from pages/login.tsxrename to src/pages/login.tsxindex f87299339..0d26e819a 100644--- a/pages/login.tsx+++ b/src/pages/login.tsx@@ -5,12 +5,15 @@ import { usePlausible } from "next-plausible";import React from "react";import toast from "react-hot-toast";import { useTimeoutFn } from "react-use";-import { decryptToken, mergeGuestsIntoUser, withSessionSsr } from "utils/auth";-import { nanoid } from "utils/nanoid";import FullPageLoader from "@/components/full-page-loader";--import { prisma } from "../db";+import {+ decryptToken,+ mergeGuestsIntoUser,+ withSessionSsr,+} from "@/utils/auth";+import { nanoid } from "@/utils/nanoid";+import { prisma } from "~/prisma/db";const Page: NextPage<{ success: boolean; redirectTo: string }> = ({success,diff --git a/pages/new.tsx b/src/pages/new.tsxsimilarity index 93%rename from pages/new.tsxrename to src/pages/new.tsxindex 9364ef7fe..1cd5c87ed 100644--- a/pages/new.tsx+++ b/src/pages/new.tsx@@ -1,9 +1,9 @@import { GetServerSideProps } from "next";import dynamic from "next/dynamic";import { serverSideTranslations } from "next-i18next/serverSideTranslations";-import { withSessionSsr } from "utils/auth";import { CreatePollPageProps } from "@/components/create-poll";+import { withSessionSsr } from "@/utils/auth";const getProps: GetServerSideProps<CreatePollPageProps> = async ({locale = "en",diff --git a/src/pages/poll.tsx b/src/pages/poll.tsxnew file mode 100644index 000000000..f706c8612--- /dev/null+++ b/src/pages/poll.tsx@@ -0,0 +1,77 @@+import axios from "axios";+import { GetServerSideProps, NextPage } from "next";+import dynamic from "next/dynamic";+import { useRouter } from "next/router";+import { useTranslation } from "next-i18next";+import { serverSideTranslations } from "next-i18next/serverSideTranslations";+import { usePlausible } from "next-plausible";+import React from "react";++import FullPageLoader from "@/components/full-page-loader";+import { PollContextProvider } from "@/components/poll-context";+import { SessionProps, withSession } from "@/components/session";++import { ParticipantsProvider } from "../components/participants-provider";+import { withSessionSsr } from "../utils/auth";+import { trpc } from "../utils/trpc";+import { GetPollApiResponse } from "../utils/trpc/types";+import Custom404 from "./404";++const PollPage = dynamic(() => import("@/components/poll"), { ssr: false });++const PollPageLoader: NextPage<SessionProps> = () => {+ const { query } = useRouter();+ const { t } = useTranslation("app");+ const urlId = query.urlId as string;+ const plausible = usePlausible();+ const [notFound, setNotFound] = React.useState(false);+ const [legacyPoll, setLegacyPoll] = React.useState<GetPollApiResponse>();++ const pollQuery = trpc.useQuery(["polls.get", { urlId }], {+ onError: () => {+ if (process.env.NEXT_PUBLIC_LEGACY_POLLS === "1") {+ axios+ .get<GetPollApiResponse>(`/api/legacy/${urlId}`)+ .then(({ data }) => {+ plausible("Converted legacy event");+ setLegacyPoll(data);+ })+ .catch(() => setNotFound(true));+ } else {+ setNotFound(true);+ }+ },+ retry: false,+ });++ const poll = pollQuery.data ?? legacyPoll;++ if (poll) {+ return (+ <ParticipantsProvider pollId={poll.pollId}>+ <PollContextProvider value={poll}>+ <PollPage />+ </PollContextProvider>+ </ParticipantsProvider>+ );+ }++ if (notFound) {+ return <Custom404 />;+ }++ return <FullPageLoader>{t("loading")}</FullPageLoader>;+};++export const getServerSideProps: GetServerSideProps = withSessionSsr(+ async ({ locale = "en", req }) => {+ return {+ props: {+ ...(await serverSideTranslations(locale, ["app"])),+ user: req.session.user ?? null,+ },+ };+ },+);++export default withSession(PollPageLoader);diff --git a/pages/privacy-policy.tsx b/src/pages/privacy-policy.tsxsimilarity index 100%rename from pages/privacy-policy.tsxrename to src/pages/privacy-policy.tsxdiff --git a/src/server/context.ts b/src/server/context.tsnew file mode 100644index 000000000..ce70a736e--- /dev/null+++ b/src/server/context.ts@@ -0,0 +1,9 @@+import * as trpcNext from "@trpc/server/adapters/next";++export async function createContext(opts: trpcNext.CreateNextContextOptions) {+ const session = opts.req.session;++ return {+ session,+ };+}diff --git a/src/server/createRouter.ts b/src/server/createRouter.tsnew file mode 100644index 000000000..ab0fffdae--- /dev/null+++ b/src/server/createRouter.ts@@ -0,0 +1,11 @@+import { inferAsyncReturnType } from "@trpc/server";+import * as trpc from "@trpc/server";++import { createContext } from "./context";++type Context = inferAsyncReturnType<typeof createContext>;++// Helper function to create a router with your app's context+export function createRouter() {+ return trpc.router<Context>();+}diff --git a/src/server/routers/login.ts b/src/server/routers/login.tsnew file mode 100644index 000000000..c4412c0f2--- /dev/null+++ b/src/server/routers/login.ts@@ -0,0 +1,34 @@+import { z } from "zod";++import { absoluteUrl } from "../../utils/absolute-url";+import { sendEmailTemplate } from "../../utils/api-utils";+import { createToken } from "../../utils/auth";+import { createRouter } from "../createRouter";++export const login = createRouter().mutation("login", {+ input: z.object({+ email: z.string(),+ path: z.string(),+ }),+ resolve: async ({ ctx, input }) => {+ const { email, path } = input;+ const homePageUrl = absoluteUrl();+ const token = await createToken({+ email,+ guestId: ctx.session.user?.isGuest ? ctx.session.user.id : undefined,+ path,+ });++ const loginUrl = `${homePageUrl}/login?code=${token}`;++ await sendEmailTemplate({+ templateName: "login",+ to: email,+ subject: "Rallly - Login",+ templateVars: {+ loginUrl,+ homePageUrl,+ },+ });+ },+});diff --git a/src/server/routers/polls.ts b/src/server/routers/polls.tsnew file mode 100644index 000000000..6a89391f1--- /dev/null+++ b/src/server/routers/polls.ts@@ -0,0 +1,202 @@+import { z } from "zod";++import { prisma } from "~/prisma/db";+import { absoluteUrl } from "../../utils/absolute-url";+import { sendEmailTemplate } from "../../utils/api-utils";+import { createToken } from "../../utils/auth";+import { nanoid } from "../../utils/nanoid";+import {+ createPollResponse,+ getDefaultPollInclude,+ getLink,+ getPollFromLink,+} from "../../utils/queries";+import { GetPollApiResponse } from "../../utils/trpc/types";+import { createRouter } from "../createRouter";+import { comments } from "./polls/comments";+import { demo } from "./polls/demo";+import { participants } from "./polls/participants";+import { verification } from "./polls/verification";++export const polls = createRouter()+ .merge("demo.", demo)+ .merge("participants.", participants)+ .merge("comments.", comments)+ .merge("verification.", verification)+ .mutation("create", {+ input: z.object({+ title: z.string(),+ type: z.literal("date"),+ timeZone: z.string().optional(),+ location: z.string().optional(),+ description: z.string().optional(),+ user: z.object({+ name: z.string(),+ email: z.string(),+ }),+ options: z.string().array(),+ demo: z.boolean().optional(),+ }),+ resolve: async ({ ctx, input }) => {+ const adminUrlId = await nanoid();++ const poll = await prisma.poll.create({+ data: {+ urlId: await nanoid(),+ title: input.title,+ type: input.type,+ timeZone: input.timeZone,+ location: input.location,+ description: input.description,+ authorName: input.user.name,+ demo: input.demo,+ verified:+ ctx.session.user?.isGuest === false &&+ ctx.session.user.email === input.user.email,+ user: {+ connectOrCreate: {+ where: {+ email: input.user.email,+ },+ create: {+ id: await nanoid(),+ ...input.user,+ },+ },+ },+ options: {+ createMany: {+ data: input.options.map((value) => ({+ value,+ })),+ },+ },+ links: {+ createMany: {+ data: [+ {+ urlId: adminUrlId,+ role: "admin",+ },+ {+ urlId: await nanoid(),+ role: "participant",+ },+ ],+ },+ },+ },+ });++ const homePageUrl = absoluteUrl();+ const pollUrl = `${homePageUrl}/admin/${adminUrlId}`;++ try {+ if (poll.verified) {+ await sendEmailTemplate({+ templateName: "new-poll-verified",+ to: input.user.email,+ subject: `Rallly: ${poll.title}`,+ templateVars: {+ title: poll.title,+ name: input.user.name,+ pollUrl,+ homePageUrl,+ supportEmail: process.env.SUPPORT_EMAIL,+ },+ });+ } else {+ const verificationCode = await createToken({+ pollId: poll.urlId,+ });+ const verifyEmailUrl = `${pollUrl}?code=${verificationCode}`;++ await sendEmailTemplate({+ templateName: "new-poll",+ to: input.user.email,+ subject: `Rallly: ${poll.title} - Verify your email address`,+ templateVars: {+ title: poll.title,+ name: input.user.name,+ pollUrl,+ verifyEmailUrl,+ homePageUrl,+ supportEmail: process.env.SUPPORT_EMAIL,+ },+ });+ }+ } catch (e) {+ console.error(e);+ }++ return { urlId: adminUrlId, authorName: poll.authorName };+ },+ })+ .query("get", {+ input: z.object({+ urlId: z.string(),+ }),+ resolve: async ({ input }): Promise<GetPollApiResponse> => {+ const link = await getLink(input.urlId);+ return await getPollFromLink(link);+ },+ })+ .mutation("update", {+ input: z.object({+ urlId: z.string(),+ title: z.string().optional(),+ timeZone: z.string().optional(),+ location: z.string().optional(),+ description: z.string().optional(),+ optionsToDelete: z.string().array().optional(),+ optionsToAdd: z.string().array().optional(),+ notifications: z.boolean().optional(),+ closed: z.boolean().optional(),+ }),+ resolve: async ({ input }): Promise<GetPollApiResponse> => {+ const link = await getLink(input.urlId);++ if (link.role !== "admin") {+ throw new Error("Use admin link to update poll");+ }++ const { pollId } = link;++ if (input.optionsToDelete && input.optionsToDelete.length > 0) {+ await prisma.option.deleteMany({+ where: {+ pollId,+ id: {+ in: input.optionsToDelete,+ },+ },+ });+ }++ if (input.optionsToAdd && input.optionsToAdd.length > 0) {+ await prisma.option.createMany({+ data: input.optionsToAdd.map((optionValue) => ({+ value: optionValue,+ pollId,+ })),+ });+ }++ const poll = await prisma.poll.update({+ where: {+ urlId: pollId,+ },+ data: {+ title: input.title,+ location: input.location,+ description: input.description,+ timeZone: input.timeZone,+ notifications: input.notifications,+ closed: input.closed,+ },+ include: getDefaultPollInclude(link.role === "admin"),+ });++ return createPollResponse(poll, link);+ },+ });diff --git a/src/server/routers/polls/comments.ts b/src/server/routers/polls/comments.tsnew file mode 100644index 000000000..3f3543930--- /dev/null+++ b/src/server/routers/polls/comments.ts@@ -0,0 +1,68 @@+import { z } from "zod";++import { prisma } from "~/prisma/db";+import { sendNotification } from "../../../utils/api-utils";+import { createGuestUser } from "../../../utils/auth";+import { createRouter } from "../../createRouter";++export const comments = createRouter()+ .query("list", {+ input: z.object({+ pollId: z.string(),+ }),+ resolve: async ({ input: { pollId } }) => {+ return await prisma.comment.findMany({+ where: { pollId },+ orderBy: [+ {+ createdAt: "asc",+ },+ ],+ });+ },+ })+ .mutation("add", {+ input: z.object({+ pollId: z.string(),+ authorName: z.string(),+ content: z.string(),+ }),+ resolve: async ({ ctx, input: { pollId, authorName, content } }) => {+ if (!ctx.session.user) {+ await createGuestUser(ctx.session);+ }++ const newComment = await prisma.comment.create({+ data: {+ content,+ pollId,+ authorName,+ userId: ctx.session.user?.isGuest ? undefined : ctx.session.user?.id,+ guestId: ctx.session.user?.isGuest ? ctx.session.user.id : undefined,+ },+ });++ await sendNotification(pollId, {+ type: "newComment",+ authorName: newComment.authorName,+ });++ return newComment;+ },+ })+ .mutation("delete", {+ input: z.object({+ pollId: z.string(),+ commentId: z.string(),+ }),+ resolve: async ({ input: { pollId, commentId } }) => {+ await prisma.comment.delete({+ where: {+ id_pollId: {+ id: commentId,+ pollId,+ },+ },+ });+ },+ });diff --git a/src/server/routers/polls/demo.ts b/src/server/routers/polls/demo.tsnew file mode 100644index 000000000..854027f8c--- /dev/null+++ b/src/server/routers/polls/demo.ts@@ -0,0 +1,128 @@+import { VoteType } from "@prisma/client";+import addMinutes from "date-fns/addMinutes";++import { prisma } from "~/prisma/db";+import { absoluteUrl } from "../../../utils/absolute-url";+import { nanoid } from "../../../utils/nanoid";+import { createRouter } from "../../createRouter";++const participantData: Array<{ name: string; votes: VoteType[] }> = [+ {+ name: "Reed",+ votes: ["yes", "no", "ifNeedBe", "no"],+ },+ {+ name: "Susan",+ votes: ["yes", "yes", "yes", "no"],+ },+ {+ name: "Johnny",+ votes: ["no", "no", "yes", "yes"],+ },+ {+ name: "Ben",+ votes: ["yes", "yes", "yes", "yes"],+ },+];++const optionValues = ["2022-12-14", "2022-12-15", "2022-12-16", "2022-12-17"];++export const demo = createRouter().mutation("create", {+ resolve: async () => {+ const adminUrlId = await nanoid();+ const demoUser = { name: "John Example", email: "[email protected]" };+ const today = new Date();++ const options: Array<{ value: string; id: string }> = [];++ for (let i = 0; i < optionValues.length; i++) {+ options.push({ id: await nanoid(), value: optionValues[i] });+ }++ const participants: Array<{+ name: string;+ id: string;+ guestId: string;+ createdAt: Date;+ }> = [];++ const votes: Array<{+ optionId: string;+ participantId: string;+ type: VoteType;+ }> = [];++ for (let i = 0; i < participantData.length; i++) {+ const { name, votes: participantVotes } = participantData[i];+ const participantId = await nanoid();+ participants.push({+ id: participantId,+ name,+ guestId: "user-demo",+ createdAt: addMinutes(today, i * -1),+ });++ options.forEach((option, index) => {+ votes.push({+ optionId: option.id,+ participantId,+ type: participantVotes[index],+ });+ });+ }++ const homePageUrl = absoluteUrl();++ await prisma.poll.create({+ data: {+ urlId: await nanoid(),+ title: "Lunch Meeting Demo",+ type: "date",+ location: "Starbucks, 901 New York Avenue",+ description: `This poll has been automatically generated just for you! Feel free to try out all the different features and when you're ready, you can go to ${homePageUrl}/new to make a new poll.`,+ authorName: "Johnny",+ verified: true,+ demo: true,+ user: {+ connectOrCreate: {+ where: {+ email: demoUser.email,+ },+ create: demoUser,+ },+ },+ options: {+ createMany: {+ data: options,+ },+ },+ links: {+ createMany: {+ data: [+ {+ role: "admin",+ urlId: adminUrlId,+ },+ {+ role: "participant",+ urlId: await nanoid(),+ },+ ],+ },+ },+ participants: {+ createMany: {+ data: participants,+ },+ },+ votes: {+ createMany: {+ data: votes,+ },+ },+ },+ });++ return adminUrlId;+ },+});diff --git a/src/server/routers/polls/participants.ts b/src/server/routers/polls/participants.tsnew file mode 100644index 000000000..8cd747df6--- /dev/null+++ b/src/server/routers/polls/participants.ts@@ -0,0 +1,140 @@+import { z } from "zod";++import { prisma } from "~/prisma/db";+import { sendNotification } from "../../../utils/api-utils";+import { createGuestUser } from "../../../utils/auth";+import { createRouter } from "../../createRouter";++export const participants = createRouter()+ .query("list", {+ input: z.object({+ pollId: z.string(),+ }),+ resolve: async ({ input: { pollId } }) => {+ const participants = await prisma.participant.findMany({+ where: {+ pollId,+ },+ include: {+ votes: true,+ },+ orderBy: [+ {+ createdAt: "desc",+ },+ { name: "desc" },+ ],+ });+ return participants;+ },+ })+ .mutation("delete", {+ input: z.object({+ pollId: z.string(),+ participantId: z.string(),+ }),+ resolve: async ({ input: { participantId, pollId } }) => {+ await prisma.participant.delete({+ where: {+ id_pollId: {+ id: participantId,+ pollId: pollId,+ },+ },+ });+ },+ })+ .mutation("add", {+ input: z.object({+ pollId: z.string(),+ name: z.string(),+ votes: z+ .object({+ optionId: z.string(),+ type: z.enum(["yes", "no", "ifNeedBe"]),+ })+ .array(),+ }),+ resolve: async ({ ctx, input: { pollId, votes, name } }) => {+ if (!ctx.session.user) {+ await createGuestUser(ctx.session);+ }++ const participant = await prisma.participant.create({+ data: {+ pollId: pollId,+ name: name,+ userId:+ ctx.session.user?.isGuest === false+ ? ctx.session.user.id+ : undefined,+ guestId:+ ctx.session.user?.isGuest === true+ ? ctx.session.user.id+ : undefined,+ votes: {+ createMany: {+ data: votes.map(({ optionId, type }) => ({+ optionId,+ type,+ pollId: pollId,+ })),+ },+ },+ },+ include: {+ votes: true,+ },+ });++ await sendNotification(pollId, {+ type: "newParticipant",+ participantName: participant.name,+ });++ return participant;+ },+ })+ .mutation("update", {+ input: z.object({+ pollId: z.string(),+ participantId: z.string(),+ name: z.string(),+ votes: z+ .object({+ optionId: z.string(),+ type: z.enum(["yes", "no", "ifNeedBe"]),+ })+ .array(),+ }),+ resolve: async ({ input: { pollId, participantId, votes, name } }) => {+ const participant = await prisma.participant.update({+ where: {+ id_pollId: {+ id: participantId,+ pollId: pollId,+ },+ },+ data: {+ votes: {+ deleteMany: {+ pollId: pollId,+ },+ createMany: {+ data: votes.map(({ optionId, type }) => ({+ optionId,+ type,+ pollId,+ })),+ },+ },+ name,+ },+ include: {+ votes: true,+ },+ });++ return participant;+ },+ });diff --git a/src/server/routers/polls/verification.ts b/src/server/routers/polls/verification.tsnew file mode 100644index 000000000..9b0702dd8--- /dev/null+++ b/src/server/routers/polls/verification.ts@@ -0,0 +1,101 @@+import { TRPCError } from "@trpc/server";+import { z } from "zod";++import { prisma } from "~/prisma/db";+import { absoluteUrl } from "../../../utils/absolute-url";+import { sendEmailTemplate } from "../../../utils/api-utils";+import {+ createToken,+ decryptToken,+ mergeGuestsIntoUser,+} from "../../../utils/auth";+import { createRouter } from "../../createRouter";++export const verification = createRouter()+ .mutation("verify", {+ input: z.object({+ pollId: z.string(),+ code: z.string(),+ }),+ resolve: async ({ ctx, input }) => {+ const { pollId } = await decryptToken<{+ pollId: string;+ }>(input.code);++ if (pollId !== input.pollId) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Poll id in token (${pollId}) did not match: ${input.pollId}`,+ });+ }++ const poll = await prisma.poll.update({+ where: {+ urlId: pollId,+ },+ data: {+ verified: true,+ },+ include: { user: true },+ });++ // If logged in as guest, we update all participants+ // and comments by this guest to the user that we just authenticated+ if (ctx.session.user?.isGuest) {+ await mergeGuestsIntoUser(poll.user.id, [ctx.session.user.id]);+ }++ ctx.session.user = {+ id: poll.user.id,+ isGuest: false,+ name: poll.user.name,+ email: poll.user.email,+ };+ await ctx.session.save();+ },+ })+ .mutation("request", {+ input: z.object({+ pollId: z.string(),+ adminUrlId: z.string(),+ }),+ resolve: async ({ input: { pollId, adminUrlId } }) => {+ const poll = await prisma.poll.findUnique({+ where: {+ urlId: pollId,+ },+ include: {+ user: true,+ links: true,+ },+ });++ if (!poll) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Poll with id ${pollId} not found`,+ });+ }++ const homePageUrl = absoluteUrl();+ const pollUrl = `${homePageUrl}/admin/${adminUrlId}`;+ const token = await createToken({+ pollId,+ });+ const verifyEmailUrl = `${pollUrl}?code=${token}`;++ await sendEmailTemplate({+ templateName: "new-poll",+ to: poll.user.email,+ subject: `Rallly: ${poll.title} - Verify your email address`,+ templateVars: {+ title: poll.title,+ name: poll.user.name,+ pollUrl,+ verifyEmailUrl,+ homePageUrl,+ supportEmail: process.env.SUPPORT_EMAIL,+ },+ });+ },+ });diff --git a/src/server/routers/session.ts b/src/server/routers/session.tsnew file mode 100644index 000000000..a28d31bf8--- /dev/null+++ b/src/server/routers/session.ts@@ -0,0 +1,23 @@+import { prisma } from "~/prisma/db";+import { createRouter } from "../createRouter";++export const session = createRouter()+ .query("get", {+ async resolve({ ctx }) {+ if (ctx.session.user?.isGuest === false) {+ const user = await prisma.user.findUnique({+ where: { id: ctx.session.user.id },+ });++ return user+ ? { id: user.id, name: user.name, email: user.email, isGuest: false }+ : null;+ }+ return ctx.session.user;+ },+ })+ .mutation("destroy", {+ async resolve({ ctx }) {+ ctx.session.destroy();+ },+ });diff --git a/src/utils/absolute-url.ts b/src/utils/absolute-url.tsnew file mode 100644index 000000000..d4f96c7fb--- /dev/null+++ b/src/utils/absolute-url.ts@@ -0,0 +1,13 @@+const getVercelUrl = () => {+ return process.env.NEXT_PUBLIC_VERCEL_URL+ ? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`+ : null;+};++export function absoluteUrl() {+ return (+ process.env.NEXT_PUBLIC_BASE_URL ??+ getVercelUrl() ??+ "http://localhost:3000"+ );+}diff --git a/utils/api-utils.ts b/src/utils/api-utils.tssimilarity index 93%rename from utils/api-utils.tsrename to src/utils/api-utils.tsindex 59aa53767..d33a73950 100644--- a/utils/api-utils.ts+++ b/src/utils/api-utils.ts@@ -4,8 +4,8 @@ import { readFileSync } from "fs";import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";import path from "path";-import { prisma } from "../db";-import absoluteUrl from "./absolute-url";+import { prisma } from "~/prisma/db";+import { absoluteUrl } from "./absolute-url";import { sendEmail } from "./send-email";export const getQueryParam = (req: NextApiRequest, queryKey: string) => {@@ -56,7 +56,6 @@ type NotificationAction =};export const sendNotification = async (- req: NextApiRequest,pollId: string,action: NotificationAction,): Promise<void> => {@@ -83,7 +82,7 @@ export const sendNotification = async (if (!adminLink) {throw new Error(`Missing admin link for poll: ${pollId}`);}- const homePageUrl = absoluteUrl(req).origin;+ const homePageUrl = absoluteUrl();const pollUrl = `${homePageUrl}/admin/${adminLink.urlId}`;const unsubscribeUrl = `${pollUrl}?unsubscribe=true`;@@ -98,7 +97,7 @@ export const sendNotification = async (name: poll.authorName,participantName: action.participantName,pollUrl,- homePageUrl: absoluteUrl(req).origin,+ homePageUrl: absoluteUrl(),supportEmail: process.env.SUPPORT_EMAIL,unsubscribeUrl,},@@ -114,7 +113,7 @@ export const sendNotification = async (name: poll.authorName,author: action.authorName,pollUrl,- homePageUrl: absoluteUrl(req).origin,+ homePageUrl: absoluteUrl(),supportEmail: process.env.SUPPORT_EMAIL,unsubscribeUrl,},diff --git a/utils/auth.ts b/src/utils/auth.tssimilarity index 84%rename from utils/auth.tsrename to src/utils/auth.tsindex 82a8d4645..fccdfa613 100644--- a/utils/auth.ts+++ b/src/utils/auth.ts@@ -1,8 +1,13 @@-import { IronSessionOptions, sealData, unsealData } from "iron-session";+import {+ IronSession,+ IronSessionOptions,+ sealData,+ unsealData,+} from "iron-session";import { withIronSessionApiRoute, withIronSessionSsr } from "iron-session/next";-import { GetServerSideProps, NextApiHandler, NextApiRequest } from "next";+import { GetServerSideProps, NextApiHandler } from "next";-import { prisma } from "../db";+import { prisma } from "~/prisma/db";import { randomid } from "./nanoid";const sessionOptions: IronSessionOptions = {@@ -37,12 +42,12 @@ export const createToken = async <T extends Record<string, unknown>>(});};-export const createGuestUser = async (req: NextApiRequest) => {- req.session.user = {+export const createGuestUser = async (session: IronSession) => {+ session.user = {id: `user-${await randomid()}`,isGuest: true,};- await req.session.save();+ await session.save();};// assigns participants and comments created by guests to a userdiff --git a/utils/constants.ts b/src/utils/constants.tssimilarity index 100%rename from utils/constants.tsrename to src/utils/constants.tsdiff --git a/utils/date-time-utils.ts b/src/utils/date-time-utils.tssimilarity index 100%rename from utils/date-time-utils.tsrename to src/utils/date-time-utils.tsdiff --git a/utils/form-validation.ts b/src/utils/form-validation.tssimilarity index 100%rename from utils/form-validation.tsrename to src/utils/form-validation.tsdiff --git a/utils/legacy-utils.ts b/src/utils/legacy-utils.tssimilarity index 98%rename from utils/legacy-utils.tsrename to src/utils/legacy-utils.tsindex 28ae8a57e..b261b0940 100644--- a/utils/legacy-utils.ts+++ b/src/utils/legacy-utils.ts@@ -1,6 +1,6 @@import { ObjectId } from "mongodb";-import { prisma } from "../db";+import { prisma } from "~/prisma/db";import { getMongoClient } from "./mongodb-client";export interface LegacyPoll {diff --git a/utils/mongodb-client.ts b/src/utils/mongodb-client.tssimilarity index 100%rename from utils/mongodb-client.tsrename to src/utils/mongodb-client.tsdiff --git a/utils/nanoid.ts b/src/utils/nanoid.tssimilarity index 100%rename from utils/nanoid.tsrename to src/utils/nanoid.tsdiff --git a/utils/prevent-widows.ts b/src/utils/prevent-widows.tssimilarity index 100%rename from utils/prevent-widows.tsrename to src/utils/prevent-widows.tsdiff --git a/src/utils/queries.ts b/src/utils/queries.tsnew file mode 100644index 000000000..f7fd1eeae--- /dev/null+++ b/src/utils/queries.ts@@ -0,0 +1,80 @@+import { Link, Option, Poll, User } from "@prisma/client";+import { TRPCError } from "@trpc/server";++import { prisma } from "~/prisma/db";+import { GetPollApiResponse } from "./trpc/types";++export const getDefaultPollInclude = <V extends boolean>(+ includeLinks: V,+): {+ options: {+ orderBy: {+ value: "asc";+ };+ };+ user: true;+ links: V;+} => {+ return {+ options: {+ orderBy: {+ value: "asc",+ },+ },+ user: true,+ links: includeLinks,+ };+};++export const getLink = async (urlId: string) => {+ const link = await prisma.link.findUnique({+ where: {+ urlId,+ },+ });++ if (!link) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Link not found with id: ${urlId}`,+ });+ }++ return link;+};++export const getPollFromLink = async (+ link: Link,+): Promise<GetPollApiResponse> => {+ const poll = await prisma.poll.findUnique({+ where: {+ urlId: link.pollId,+ },+ include: getDefaultPollInclude(link.role === "admin"),+ });++ if (!poll) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: `Poll not found with id: ${link.pollId}`,+ });+ }++ return createPollResponse(poll, link);+};++export const createPollResponse = (+ poll: Poll & {+ options: Option[];+ user: User;+ links: Link[];+ },+ link: Link,+): GetPollApiResponse => {+ return {+ ...poll,+ role: link.role,+ urlId: link.urlId,+ pollId: poll.urlId,+ };+};diff --git a/utils/selectors.ts b/src/utils/selectors.tssimilarity index 100%rename from utils/selectors.tsrename to src/utils/selectors.tsdiff --git a/utils/send-email.ts b/src/utils/send-email.tssimilarity index 100%rename from utils/send-email.tsrename to src/utils/send-email.tsdiff --git a/utils/stop-propagation.ts b/src/utils/stop-propagation.tssimilarity index 100%rename from utils/stop-propagation.tsrename to src/utils/stop-propagation.tsdiff --git a/utils/string-to-value.ts b/src/utils/string-to-value.tssimilarity index 100%rename from utils/string-to-value.tsrename to src/utils/string-to-value.tsdiff --git a/utils/theme.json b/src/utils/theme.jsonsimilarity index 100%rename from utils/theme.jsonrename to src/utils/theme.jsondiff --git a/src/utils/trpc.ts b/src/utils/trpc.tsnew file mode 100644index 000000000..1247ab392--- /dev/null+++ b/src/utils/trpc.ts@@ -0,0 +1,5 @@+import { createReactQueryHooks } from "@trpc/react";++import type { AppRouter } from "../pages/api/trpc/[trpc]";++export const trpc = createReactQueryHooks<AppRouter>();diff --git a/src/utils/trpc/types.ts b/src/utils/trpc/types.tsnew file mode 100644index 000000000..e634a678c--- /dev/null+++ b/src/utils/trpc/types.ts@@ -0,0 +1,9 @@+import { Link, Option, Poll, Role, User } from "@prisma/client";++export interface GetPollApiResponse extends Poll {+ options: Option[];+ user: User;+ role: Role;+ links: Array<Link>;+ pollId: string;+}diff --git a/tailwind.config.js b/tailwind.config.jsindex 9f3ecddbb..733b8e33c 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -2,7 +2,7 @@ const colors = require("tailwindcss/colors");const defaultTheme = require("tailwindcss/defaultTheme");module.exports = {- content: ["./pages/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}"],+ content: ["./src/pages/**/*.{ts,tsx}", "./src/components/**/*.{ts,tsx}"],theme: {extend: {primary: colors.indigo,diff --git a/tsconfig.json b/tsconfig.jsonindex 1ace81e19..78affc127 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -23,7 +23,8 @@"incremental": true,"baseUrl": ".","paths": {- "@/components/*": ["components/*"]+ "@/*": ["src/*"],+ "~/*": ["./*"]}},"exclude": ["node_modules", "**/.*/", "**/*.js"],diff --git a/utils/absolute-url.ts b/utils/absolute-url.tsdeleted file mode 100644index 8f369bf0c..000000000--- a/utils/absolute-url.ts+++ /dev/null@@ -1,36 +0,0 @@-// Source: https://github.com/jakeburden/next-absolute-url/blob/1d96d1d2a2a2308db60ce53a130b5d47aab3ee25/index.ts-import { IncomingMessage } from "http";--function absoluteUrl(- req?: IncomingMessage,- localhostAddress = "localhost:3000",-) {- let host =- (req?.headers ? req.headers.host : window.location.host) ||- localhostAddress;- let protocol = /^localhost(:\d+)?$/.test(host) ? "http:" : "https:";-- if (- req &&- req.headers["x-forwarded-host"] &&- typeof req.headers["x-forwarded-host"] === "string"- ) {- host = req.headers["x-forwarded-host"];- }-- if (- req &&- req.headers["x-forwarded-proto"] &&- typeof req.headers["x-forwarded-proto"] === "string"- ) {- protocol = `${req.headers["x-forwarded-proto"]}:`;- }-- return {- protocol,- host,- origin: protocol + "//" + host,- };-}--export default absoluteUrl;diff --git a/yarn.lock b/yarn.lockindex 384fd2565..0e6af4f06 100644--- a/yarn.lock+++ b/yarn.lock@@ -1062,6 +1062,13 @@dependencies:regenerator-runtime "^0.13.4"+"@babel/runtime@^7.9.0":+ version "7.17.9"+ resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.17.9.tgz#d19fbf802d01a8cb6cf053a64e472d42c434ba72"+ integrity sha512-lSiBBvodq29uShpWGNbgFdKYNiFDo5/HIYsaCEY9ff4sb10x9jizo2+pRrSyF4jKZCXqgzuqBOQKbUm90gQwJg==+ dependencies:+ regenerator-runtime "^0.13.4"+"@babel/template@^7.16.7":version "7.16.7"resolved "https://registry.npmjs.org/@babel/template/-/template-7.16.7.tgz"@@ -1395,22 +1402,22 @@resolved "https://registry.npmjs.org/@popperjs/core/-/core-2.9.2.tgz"integrity sha512-VZMYa7+fXHdwIq1TDhSXoVmSPEGM/aa+6Aiq3nVVJ9bXr24zScr+NlKFKC3iPljA7ho/GAZr+d2jOf5GIRC30Q==-"@prisma/client@^3.13.0":- version "3.13.0"- resolved "https://registry.yarnpkg.com/@prisma/client/-/client-3.13.0.tgz#84511ebdf6ba75f77ca08495b9f73f22c4255654"- integrity sha512-lnEA2tTyVbO5mS1ehmHJQKBDiKB8shaR6s3azwj3Azfi5XHIfnqmkolLCvUeFYnkDCNVzGXJpUgKwQt/UOOYVQ==+"@prisma/client@^3.14.0":+ version "3.14.0"+ resolved "https://registry.yarnpkg.com/@prisma/client/-/client-3.14.0.tgz#bb90405c012fcca11f4647d91153ed4c58f3bd48"+ integrity sha512-atb41UpgTR1MCst0VIbiHTMw8lmXnwUvE1KyUCAkq08+wJyjRE78Due+nSf+7uwqQn+fBFYVmoojtinhlLOSaA==dependencies:- "@prisma/engines-version" "3.13.0-17.efdf9b1183dddfd4258cd181a72125755215ab7b"+ "@prisma/engines-version" "3.14.0-36.2b0c12756921c891fec4f68d9444e18c7d5d4a6a"-"@prisma/engines-version@3.13.0-17.efdf9b1183dddfd4258cd181a72125755215ab7b":- version "3.13.0-17.efdf9b1183dddfd4258cd181a72125755215ab7b"- resolved "https://registry.yarnpkg.com/@prisma/engines-version/-/engines-version-3.13.0-17.efdf9b1183dddfd4258cd181a72125755215ab7b.tgz#676aca309d66d9be2aad8911ca31f1ee5561041c"- integrity sha512-TGp9rvgJIKo8NgvAHSwOosbut9mTA7VC6/rpQI9gh+ySSRjdQFhbGyNUiOcQrlI9Ob2DWeO7y4HEnhdKxYiECg==+"@prisma/engines-version@3.14.0-36.2b0c12756921c891fec4f68d9444e18c7d5d4a6a":+ version "3.14.0-36.2b0c12756921c891fec4f68d9444e18c7d5d4a6a"+ resolved "https://registry.yarnpkg.com/@prisma/engines-version/-/engines-version-3.14.0-36.2b0c12756921c891fec4f68d9444e18c7d5d4a6a.tgz#4edae57cf6527f35e22cebe75e49214fc0e99ac9"+ integrity sha512-D+yHzq4a2r2Rrd0ZOW/mTZbgDIkUkD8ofKgusEI1xPiZz60Daks+UM7Me2ty5FzH3p/TgyhBpRrfIHx+ha20RQ==-"@prisma/[email protected]":- version "3.13.0-17.efdf9b1183dddfd4258cd181a72125755215ab7b"- resolved "https://registry.yarnpkg.com/@prisma/engines/-/engines-3.13.0-17.efdf9b1183dddfd4258cd181a72125755215ab7b.tgz#d3a457cec4ef7a3b3412c45b1f2eac68c974474b"- integrity sha512-Ip9CcCeUocH61eXu4BUGpvl5KleQyhcUVLpWCv+0ZmDv44bFaDpREqjGHHdRupvPN/ugB6gTlD9b9ewdj02yVA==+"@prisma/[email protected]":+ version "3.14.0-36.2b0c12756921c891fec4f68d9444e18c7d5d4a6a"+ resolved "https://registry.yarnpkg.com/@prisma/engines/-/engines-3.14.0-36.2b0c12756921c891fec4f68d9444e18c7d5d4a6a.tgz#7fa11bc26a51d450185c816cc0ab8cac673fb4bf"+ integrity sha512-LwZvI3FY6f43xFjQNRuE10JM5R8vJzFTSmbV9X0Wuhv9kscLkjRlZt0BEoiHmO+2HA3B3xxbMfB5du7ZoSFXGg=="@restart/hooks@^0.3.25":version "0.3.26"@@ -1696,6 +1703,33 @@lodash.isplainobject "^4.0.6"lodash.merge "^4.6.2"+"@trpc/client@^9.23.2":+ version "9.23.2"+ resolved "https://registry.yarnpkg.com/@trpc/client/-/client-9.23.2.tgz#db833db0884b5121b355ae70e6f7b36e66e58814"+ integrity sha512-L4ZajhrrupESQXE565UekQH6SDXoL4zCRTF5+/tZ+Y0YkE1DUdBmwBUwWSFIco/QkkMdzNovjZU1xEEWMc+0rw==+ dependencies:+ "@babel/runtime" "^7.9.0"++"@trpc/next@^9.23.2":+ version "9.23.2"+ resolved "https://registry.yarnpkg.com/@trpc/next/-/next-9.23.2.tgz#4148098a22e4aa2284f667df9fe1cafbaec1e4f1"+ integrity sha512-8i89WDpxQcGqsohTjZ5JnA/JAZXH+yTsHnabaHckGYqXP/BPyE6TrRVhbmftiF7ljdLYFidSEiP5FP+U8kWK5Q==+ dependencies:+ "@babel/runtime" "^7.9.0"+ react-ssr-prepass "^1.5.0"++"@trpc/react@^9.23.2":+ version "9.23.2"+ resolved "https://registry.yarnpkg.com/@trpc/react/-/react-9.23.2.tgz#35ac7bf7b1129813b8f741ca71384f405d2734b0"+ integrity sha512-T30BCRUNPt5BcVqZMSrqhF1qBIUrSOxwLvyp6pr8CXYmnypPLHvdPm3cgxjddeMuVZg8aggU8lhfPkTuAZBpEw==+ dependencies:+ "@babel/runtime" "^7.9.0"++"@trpc/server@^9.23.2":+ version "9.23.2"+ resolved "https://registry.yarnpkg.com/@trpc/server/-/server-9.23.2.tgz#ed2703d5b3c1e27a2749459458b248b07be07b87"+ integrity sha512-uFvn2pFV+wJWLtvH3sqwF+1xfMp1m3Irq4S9MkNtUIFER9k3o6RN6FU2yUA+nefeCDkGsptPE7R4RbxojtpNXw==+"@trysound/[email protected]":version "0.2.0"resolved "https://registry.npmjs.org/@trysound/sax/-/sax-0.2.0.tgz"@@ -2587,6 +2621,13 @@ cookie@^0.5.0:resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b"integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==+copy-anything@^3.0.2:+ version "3.0.2"+ resolved "https://registry.yarnpkg.com/copy-anything/-/copy-anything-3.0.2.tgz#7189171ff5e1893b2287e8bf574b8cd448ed50b1"+ integrity sha512-CzATjGXzUQ0EvuvgOCI6A4BGOo2bcVx8B+eC2nF862iv9fopnPQwlrbACakNCHRIJbCSBj+J/9JeDf60k64MkA==+ dependencies:+ is-what "^4.1.6"+copy-to-clipboard@^3.3.1:version "3.3.1"resolved "https://registry.npmjs.org/copy-to-clipboard/-/copy-to-clipboard-3.3.1.tgz"@@ -3958,6 +3999,11 @@ is-weakref@^1.0.1:dependencies:call-bind "^1.0.2"+is-what@^4.1.6:+ version "4.1.7"+ resolved "https://registry.yarnpkg.com/is-what/-/is-what-4.1.7.tgz#c41dc1d2d2d6a9285c624c2505f61849c8b1f9cc"+ integrity sha512-DBVOQNiPKnGMxRMLIYSwERAS5MVY1B7xYiGnpgctsOFvVDz9f9PFXXxMcTOHuoqYp4NK9qFYQaIC1NRRxLMpBQ==+is-wsl@^2.2.0:version "2.2.0"resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-2.2.0.tgz#74a4c76e77ca9fd3f932f290c17ea326cd157271"@@ -4922,13 +4968,12 @@ pretty-format@^27.2.5, pretty-format@^27.5.1:ansi-styles "^5.0.0"react-is "^17.0.1"-prisma@^3.13.0:- version "3.13.0"- resolved "https://registry.yarnpkg.com/prisma/-/prisma-3.13.0.tgz#b11edd5631222ff1bf1d5324732d47801386aa8c"- integrity sha512-oO1auBnBtieGdiN+57IgsA9Vr7Sy4HkILi1KSaUG4mpKfEbnkTGnLOxAqjLed+K2nsG/GtE1tJBtB7JxN1a78Q==+prisma@^3.14.0:+ version "3.14.0"+ resolved "https://registry.yarnpkg.com/prisma/-/prisma-3.14.0.tgz#dd67ece37d7b5373e9fd9588971de0024b49be81"+ integrity sha512-l9MOgNCn/paDE+i1K2fp9NZ+Du4trzPTJsGkaQHVBufTGqzoYHuNk8JfzXuIn0Gte6/ZjyKj652Jq/Lc1tp2yw==dependencies:- "@prisma/engines" "3.13.0-17.efdf9b1183dddfd4258cd181a72125755215ab7b"- ts-pattern "^4.0.1"+ "@prisma/engines" "3.14.0-36.2b0c12756921c891fec4f68d9444e18c7d5d4a6a"process-nextick-args@~2.0.0:version "2.0.1"@@ -5104,6 +5149,11 @@ react-query@^3.34.12:broadcast-channel "^3.4.1"match-sorter "^6.0.2"+react-ssr-prepass@^1.5.0:+ version "1.5.0"+ resolved "https://registry.yarnpkg.com/react-ssr-prepass/-/react-ssr-prepass-1.5.0.tgz#bc4ca7fcb52365e6aea11cc254a3d1bdcbd030c5"+ integrity sha512-yFNHrlVEReVYKsLI5lF05tZoHveA5pGzjFbFJY/3pOqqjGOmMmqx83N4hIjN2n6E1AOa+eQEUxs3CgRnPmT0RQ==+react-universal-interface@^0.6.2:version "0.6.2"resolved "https://registry.npmjs.org/react-universal-interface/-/react-universal-interface-0.6.2.tgz"@@ -5711,6 +5761,13 @@ stylis@^4.0.6:resolved "https://registry.npmjs.org/stylis/-/stylis-4.0.13.tgz"integrity sha512-xGPXiFVl4YED9Jh7Euv2V220mriG9u4B2TA6Ybjc1catrstKD2PpIdU3U0RKpkVBC2EhmL/F0sPCr9vrFTNRag==+superjson@^1.9.1:+ version "1.9.1"+ resolved "https://registry.yarnpkg.com/superjson/-/superjson-1.9.1.tgz#e23bd2e8cf0f4ade131d6d769754cac7eaa8ab34"+ integrity sha512-oT3HA2nPKlU1+5taFgz/HDy+GEaY+CWEbLzaRJVD4gZ7zMVVC4GDNFdgvAZt6/VuIk6D2R7RtPAiCHwmdzlMmg==+ dependencies:+ copy-anything "^3.0.2"+supports-color@^5.3.0:version "5.5.0"resolved "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz"@@ -5846,11 +5903,6 @@ ts-easing@^0.2.0:resolved "https://registry.npmjs.org/ts-easing/-/ts-easing-0.2.0.tgz"integrity sha512-Z86EW+fFFh/IFB1fqQ3/+7Zpf9t2ebOAxNI/V6Wo7r5gqiqtxmgTlQ1qbqQcjLKYeSHPTsEmvlJUDg/EuL0uHQ==-ts-pattern@^4.0.1:- version "4.0.2"- resolved "https://registry.yarnpkg.com/ts-pattern/-/ts-pattern-4.0.2.tgz#b36afdb2de1ec0224539dcb7cea3a57c41453b9f"- integrity sha512-eHqR/7A6fcw05vCOfnL6RwgGJbVi9G/YHTdYdjYmElhDdJ1SMn7pWs+6+YuxygaFwQS/g+cIDlu+UD8IVpur1A==-tsconfig-paths@^3.12.0, tsconfig-paths@^3.14.1:version "3.14.1"resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz#ba0734599e8ea36c862798e920bcf163277b137a"@@ -6134,3 +6186,8 @@ [email protected]:integrity sha512-phENi2PLiHnHb6QBVot+dJnaAZ0xosj7p3fWl+znIjBDlnMI2PsZCJZ306BPTFOaHf5qdDEI8x5qFrSOBN5vrw==dependencies:buffer-crc32 "~0.2.3"++zod@^3.16.0:+ version "3.16.0"+ resolved "https://registry.yarnpkg.com/zod/-/zod-3.16.0.tgz#edfdbf77fcc9a5af13a2630a44bdda5b90e759b7"+ integrity sha512-szrIkryADbTM+xBt2a1KoS2CJQXec4f9xG78bj5MJeEH/XqmmHpnO+fG3IE115AKBJak+2HrbxLZkc9mhdbDKA==