Zone deletion

This commit is contained in:
Timothy Armes
2024-04-12 13:47:24 +02:00
parent 50943685c0
commit 860644bd9f
12 changed files with 352 additions and 139 deletions
+2 -1
View File
@@ -8,6 +8,7 @@
"colour", "colour",
"colours", "colours",
"contactez", "contactez",
"creer",
"datepicker", "datepicker",
"defaulticon", "defaulticon",
"Depfu", "Depfu",
@@ -31,7 +32,7 @@
"spiderified", "spiderified",
"superjson", "superjson",
"tailwindcss", "tailwindcss",
"tanstack",Ò "tanstack",
"timothyarmes", "timothyarmes",
"tournoi", "tournoi",
"tournois", "tournois",
+1 -1
View File
@@ -13,7 +13,7 @@
}, },
"dependencies": { "dependencies": {
"@auth/mongodb-adapter": "^2.5.0", "@auth/mongodb-adapter": "^2.5.0",
"@headlessui/react": "^1.7.17", "@headlessui/react": "^1.7.18",
"@headlessui/tailwindcss": "^0.2.0", "@headlessui/tailwindcss": "^0.2.0",
"@hookform/resolvers": "^3.3.3", "@hookform/resolvers": "^3.3.3",
"@infra-blocks/zod-utils": "^0.4.2", "@infra-blocks/zod-utils": "^0.4.2",
@@ -5,6 +5,7 @@ import { useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import InfoMessage, { clearMessage } from "@/components/InfoMessage"; import InfoMessage, { clearMessage } from "@/components/InfoMessage";
import { useZones } from "@/hooks/useZones";
import { createZone } from "@/server/createZone"; import { createZone } from "@/server/createZone";
import { useRouter } from "@/utils/navigation"; import { useRouter } from "@/utils/navigation";
@@ -19,9 +20,13 @@ const CreateZone = () => {
message: "", message: "",
}); });
const { refetch } = useZones();
const onSubmit = async (data: ZoneFormValues) => { const onSubmit = async (data: ZoneFormValues) => {
try { try {
await createZone(data); await createZone(data);
await refetch();
router.push("/zones"); router.push("/zones");
} catch (err: unknown) { } catch (err: unknown) {
console.log(err); console.log(err);
@@ -2,13 +2,12 @@
import { useState } from "react"; import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import InfoMessage, { clearMessage } from "@/components/InfoMessage"; import InfoMessage, { clearMessage } from "@/components/InfoMessage";
import { useZones } from "@/hooks/useZones";
import { editZone } from "@/server/editZone"; import { editZone } from "@/server/editZone";
import { myZones } from "@/server/myZones";
import { useRouter } from "@/utils/navigation"; import { useRouter } from "@/utils/navigation";
import { ZoneForm, ZoneFormValues } from "../../components/ZoneForm"; import { ZoneForm, ZoneFormValues } from "../../components/ZoneForm";
@@ -23,43 +22,9 @@ const EditZone = () => {
message: "", message: "",
}); });
const { data, isFetching, error, refetch } = useQuery({ const { zones, isFetching, refetch } = useZones();
queryKey: ["zones"],
queryFn: async () => myZones(),
refetchOnWindowFocus: false,
staleTime: Infinity,
gcTime: 10 * 60 * 1000,
retry: false,
});
const editZoneMutation = useMutation({ const zone = zones.find((zone) => zone.id === params.id);
mutationFn: async (data: ZoneFormValues) => {
const updatedZone = await editZone({
id: params.id as string,
zone: data,
});
if (updatedZone.serverError) {
throw new Error(updatedZone.serverError);
}
return updatedZone;
},
onError: (error) => {
setResponseMessage({
isSuccessful: false,
message: t("createFailure"),
});
clearMessage(setResponseMessage);
},
onSuccess: async () => {
await refetch();
router.push("/zones");
},
});
const zone = (data?.data ?? []).find((zone) => zone.id === params.id);
if (isFetching) { if (isFetching) {
return null; return null;
@@ -70,7 +35,26 @@ const EditZone = () => {
} }
const onSubmit = async (data: ZoneFormValues) => { const onSubmit = async (data: ZoneFormValues) => {
await editZoneMutation.mutateAsync(data); try {
const updatedZone = await editZone({
id: params.id as string,
zone: data,
});
if (updatedZone.serverError) {
throw new Error(updatedZone.serverError);
}
await refetch();
router.push("/zones");
} catch (error) {
setResponseMessage({
isSuccessful: false,
message: t("createFailure"),
});
clearMessage(setResponseMessage);
}
}; };
return ( return (
@@ -87,6 +71,7 @@ const EditZone = () => {
onCancel={() => router.push("/zones")} onCancel={() => router.push("/zones")}
zone={zone} zone={zone}
/> />
<InfoMessage responseMessage={responseMessage} /> <InfoMessage responseMessage={responseMessage} />
</div> </div>
); );
+9 -1
View File
@@ -6,11 +6,19 @@ import { useSession } from "next-auth/react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { SignInForm } from "@/components/SignInForm"; import { SignInForm } from "@/components/SignInForm";
import { Spinner } from "@/components/Spinner";
export default function ZonesLayout({ children }: { children: ReactNode }) { export default function ZonesLayout({ children }: { children: ReactNode }) {
const { data: sessionData } = useSession(); const { data: sessionData, status } = useSession();
const t = useTranslations("Zones"); const t = useTranslations("Zones");
if (status === "loading")
return (
<div className="mt-20 flex justify-center">
<Spinner />
</div>
);
return ( return (
<div className="mx-auto max-w-screen-md px-4 py-8 lg:py-16"> <div className="mx-auto max-w-screen-md px-4 py-8 lg:py-16">
{!sessionData ? ( {!sessionData ? (
+62 -14
View File
@@ -1,16 +1,18 @@
"use client"; "use client";
import React from "react"; import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useFormatter, useTranslations } from "next-intl"; import { useFormatter, useTranslations } from "next-intl";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import { IoAdd } from "react-icons/io5"; import { IoAdd } from "react-icons/io5";
import InfoMessage, { clearMessage } from "@/components/InfoMessage";
import { Modal } from "@/components/Modal";
import { Spinner } from "@/components/Spinner"; import { Spinner } from "@/components/Spinner";
import { myZones } from "@/server/myZones"; import { useZones } from "@/hooks/useZones";
import { deleteZone } from "@/server/deleteZone";
import { TimeControl } from "@/types"; import { TimeControl } from "@/types";
import { Link } from "@/utils/navigation"; import { Link, useRouter } from "@/utils/navigation";
const ZoneThumbnail = dynamic(() => import("./components/ZoneThumbnail"), { const ZoneThumbnail = dynamic(() => import("./components/ZoneThumbnail"), {
ssr: false, ssr: false,
@@ -20,20 +22,39 @@ const ZoneThumbnail = dynamic(() => import("./components/ZoneThumbnail"), {
const Zones = () => { const Zones = () => {
const t = useTranslations("Zones"); const t = useTranslations("Zones");
const at = useTranslations("App"); const at = useTranslations("App");
const router = useRouter();
const format = useFormatter(); const format = useFormatter();
const { data, isFetching, error } = useQuery({ const [deletingZoneId, setDeletingZoneId] = useState<string | null>(null);
queryKey: ["zones"], const [responseMessage, setResponseMessage] = useState({
queryFn: async () => myZones(), isSuccessful: false,
refetchOnWindowFocus: false, message: "",
staleTime: Infinity,
gcTime: 10 * 60 * 1000,
retry: false,
}); });
const zones = data?.data ?? []; const { zones, isFetching, refetch } = useZones();
const onDelete = async () => {
try {
if (!deletingZoneId) return;
await deleteZone({ id: deletingZoneId });
await refetch();
setDeletingZoneId(null);
router.push("/zones");
} catch (err: unknown) {
console.log(err);
setResponseMessage({
isSuccessful: false,
message: t("createFailure"),
});
clearMessage(setResponseMessage);
}
};
return ( return (
<>
<div> <div>
<h2 <h2
className="mb-4 text-center text-4xl font-extrabold tracking-tight text-gray-900 dark:text-white" className="mb-4 text-center text-4xl font-extrabold tracking-tight text-gray-900 dark:text-white"
@@ -91,13 +112,14 @@ const Zones = () => {
}} }}
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit" className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
> >
{t("editButton")} {at("editButton")}
</Link> </Link>
<button <button
type="button" type="button"
onClick={() => setDeletingZoneId(zone.id)}
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit" className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
> >
{t("deleteButton")} {at("deleteButton")}
</button> </button>
</div> </div>
</div> </div>
@@ -117,6 +139,32 @@ const Zones = () => {
</Link> </Link>
</div> </div>
</div> </div>
<Modal
open={deletingZoneId !== null}
onClose={() => setDeletingZoneId(null)}
title={t("deleteZoneTitle")}
subTitle={t("deleteZoneInfo")}
>
<InfoMessage responseMessage={responseMessage} />
<div className="flex items-center justify-between space-x-4 text-sm font-bold">
<button
type="button"
onClick={() => setDeletingZoneId(null)}
className="rounded-lg border border-primary px-3 py-2 text-center text-xs text-primary hover:bg-primary hover:text-white focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:focus:ring-primary-800 sm:w-fit"
>
{at("cancelButton")}
</button>
<button
onClick={() => onDelete()}
className="rounded-lg bg-primary-600 px-5 py-3 text-center text-sm font-medium text-white hover:bg-primary-800 focus:outline-none focus:ring-4 focus:ring-primary-300 disabled:opacity-25 dark:text-white dark:hover:bg-primary-700 dark:focus:ring-primary-800 sm:w-fit"
>
{at("deleteButton")}
</button>
</div>
</Modal>
</>
); );
}; };
+104
View File
@@ -0,0 +1,104 @@
import React, { ComponentProps, Fragment } from "react";
import { Dialog, Transition } from "@headlessui/react";
import { twMerge } from "tailwind-merge";
type ModalProps = ComponentProps<typeof Dialog> & {
title?: string;
subTitle?: string;
titleClass?: string;
subTitleClass?: string;
overlayClass?: string;
panelClass?: string;
children?: React.ReactNode;
};
export const Modal = ({
open,
onClose,
title,
subTitle,
titleClass,
subTitleClass,
overlayClass,
panelClass,
children,
...dialogProps
}: ModalProps) => (
<Transition appear show={open} as={Fragment}>
<Dialog
as="div"
className="relative z-[2000]"
onClose={onClose}
{...dialogProps}
>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div
className={twMerge("fixed inset-0 bg-neutral-900/50", overlayClass)}
/>
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel
className={twMerge(
"flex w-full max-w-md transform flex-col space-y-6 overflow-hidden rounded-lg bg-neutral-100 p-4 transition-all dark:bg-neutral-600",
panelClass,
)}
>
{title && (
<div>
<div className="flex items-center justify-between space-x-4">
<Dialog.Title
as="h3"
className={twMerge(
"text-xl font-normal !leading-8 text-black dark:text-white",
titleClass,
)}
>
{title}
</Dialog.Title>
</div>
{subTitle && (
<Dialog.Description
className={twMerge(
"mt-2 text-left text-xs font-normal text-black dark:text-white",
subTitleClass,
)}
>
{subTitle}
</Dialog.Description>
)}
</div>
)}
{children}
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
+19
View File
@@ -0,0 +1,19 @@
import { useQuery } from "@tanstack/react-query";
import { myZones } from "@/server/myZones";
export const useZones = () => {
const query = useQuery({
queryKey: ["zones"],
queryFn: async () => myZones(),
refetchOnWindowFocus: false,
staleTime: Infinity,
gcTime: 10 * 60 * 1000,
retry: false,
});
return {
...query,
zones: query.data?.data ?? [],
};
};
+7 -5
View File
@@ -17,7 +17,9 @@
"timeControlEnumInline": "{tc, select, Classic {classic} Rapid {rapid} Blitz {blitz} Other {other} other {{tc}}}", "timeControlEnumInline": "{tc, select, Classic {classic} Rapid {rapid} Blitz {blitz} Other {other} other {{tc}}}",
"saveButton": "Save", "saveButton": "Save",
"cancelButton": "Cancel" "cancelButton": "Cancel",
"editButton": "Edit",
"deleteButton": "Delete"
}, },
"Errors": { "Errors": {
@@ -241,8 +243,6 @@
"noNotifications": "You have not enabled email notifications for this zone.", "noNotifications": "You have not enabled email notifications for this zone.",
"withNotifications": "You will receive email notifications for new tournaments with <b>{list}</b> time control in this region.", "withNotifications": "You will receive email notifications for new tournaments with <b>{list}</b> time control in this region.",
"editButton": "Edit",
"deleteButton": "Delete",
"addZoneButton": "Add a Region", "addZoneButton": "Add a Region",
"createTitle": "Create a new zone", "createTitle": "Create a new zone",
@@ -252,8 +252,10 @@
"zoneNamePlaceholder": "Name for your zone", "zoneNamePlaceholder": "Name for your zone",
"notificationsLabel": "Notifications", "notificationsLabel": "Notifications",
"notificationsInfo": "You can choose to turn on notifications for the time controls that interest you, and will receive an email when a new tournament is added to this zone.", "notificationsInfo": "You can choose to turn on notifications for the time controls that interest you, and will receive an email when a new tournament is added to this zone.",
"saveButton": "Save",
"createFailure": "Oops, something went wrong. Please try again later." "createFailure": "Oops, something went wrong. Please try again later.",
"deleteZoneTitle": "Delete Zone",
"deleteZoneInfo": "Are you sure you want to delete this zone? This action cannot be undone."
} }
} }
+7 -5
View File
@@ -17,7 +17,9 @@
"timeControlEnumInline": "{tc, select, Classic {lente} Rapid {rapide} Blitz {blitz} Other {autres} other {{tc}}}", "timeControlEnumInline": "{tc, select, Classic {lente} Rapid {rapide} Blitz {blitz} Other {autres} other {{tc}}}",
"saveButton": "Sauvegarder", "saveButton": "Sauvegarder",
"cancelButton": "Annuler" "cancelButton": "Annuler",
"editButton": "Modifier",
"deleteButton": "Supprimer"
}, },
"Errors": { "Errors": {
@@ -241,8 +243,6 @@
"noNotifications": "Vous n'avez pas activé les notifications par email pour cette région.", "noNotifications": "Vous n'avez pas activé les notifications par email pour cette région.",
"withNotifications": "Vous allez recevoir des notifications par e-mail pour les nouveaux tournois de cadences <b>{list}</b> dans cette région.", "withNotifications": "Vous allez recevoir des notifications par e-mail pour les nouveaux tournois de cadences <b>{list}</b> dans cette région.",
"editButton": "Modifier",
"deleteButton": "Supprimer",
"addZoneButton": "Ajouter une région", "addZoneButton": "Ajouter une région",
"createTitle": "Créer une nouvelle région", "createTitle": "Créer une nouvelle région",
@@ -252,8 +252,10 @@
"zoneNamePlaceholder": "Votre nom pour cette région", "zoneNamePlaceholder": "Votre nom pour cette région",
"notificationsLabel": "Notifications", "notificationsLabel": "Notifications",
"notificationsInfo": "Vous pouvez choisir d'activer les notifications pour les cadences qui vous intéressent, et vous recevrez un e-mail lorsqu'un nouveau tournoi est ajouté dans cette zone.", "notificationsInfo": "Vous pouvez choisir d'activer les notifications pour les cadences qui vous intéressent, et vous recevrez un e-mail lorsqu'un nouveau tournoi est ajouté dans cette zone.",
"saveButton": "Sauvegarder",
"createFailure": "Oups, quelque chose s'est mal passé. Veuillez réessayer." "createFailure": "Oups, quelque chose s'est mal passé. Veuillez réessayer.",
"deleteZoneTitle": "Supprimer la région",
"deleteZoneInfo": "Êtes-vous sûr de vouloir supprimer cette région\u00a0?"
} }
} }
+39
View File
@@ -0,0 +1,39 @@
"use server";
import { ObjectId } from "mongodb";
import { z } from "zod";
import { auth } from "@/auth";
import { collections, dbConnect } from "@/server/mongodb";
import { errorLog } from "@/utils/logger";
import { action } from "./safeAction";
const deleteZoneSchema = z.object({
id: z.string(),
});
export const deleteZone = action(deleteZoneSchema, async ({ id }) => {
try {
await dbConnect();
const user = await auth();
if (!user?.user) {
throw new Error("You must be logged in to create a zone");
}
const result = await collections.zones!.deleteOne({
_id: new ObjectId(id),
userId: new ObjectId(user.user!.id!),
});
if (!result || result.deletedCount !== 1) {
throw new Error("ERR_ZONE_DELETE_FAILED");
}
return true;
} catch (error) {
errorLog(error);
throw error;
}
});
+1 -1
View File
@@ -1259,7 +1259,7 @@
dependencies: dependencies:
tslib "^2.4.0" tslib "^2.4.0"
"@headlessui/react@^1.7.17": "@headlessui/react@^1.7.18":
version "1.7.18" version "1.7.18"
resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-1.7.18.tgz#30af4634d2215b2ca1aa29d07f33d02bea82d9d7" resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-1.7.18.tgz#30af4634d2215b2ca1aa29d07f33d02bea82d9d7"
integrity sha512-4i5DOrzwN4qSgNsL4Si61VMkUcWbcSKueUV7sFhpHzQcSShdlHENE5+QBntMSRvHt8NyoFO2AGG8si9lq+w4zQ== integrity sha512-4i5DOrzwN4qSgNsL4Si61VMkUcWbcSKueUV7sFhpHzQcSShdlHENE5+QBntMSRvHt8NyoFO2AGG8si9lq+w4zQ==