mirror of
https://github.com/TheRealOwenRees/echecsfrance.git
synced 2026-07-22 20:16:57 +00:00
Zone editing
This commit is contained in:
@@ -2,17 +2,24 @@
|
|||||||
|
|
||||||
import { useSetAtom } from "jotai";
|
import { useSetAtom } from "jotai";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
import { FaGithub, FaRegEnvelope } from "react-icons/fa";
|
import { FaGithub, FaRegEnvelope } from "react-icons/fa";
|
||||||
|
|
||||||
import { burgerMenuIsOpenAtom } from "@/atoms";
|
import { burgerMenuIsOpenAtom } from "@/atoms";
|
||||||
import { Link, usePathname } from "@/utils/navigation";
|
import { Link, usePathname, useRouter } from "@/utils/navigation";
|
||||||
|
|
||||||
import ThemeSwitcher from "./ThemeSwitcher";
|
import ThemeSwitcher from "./ThemeSwitcher";
|
||||||
|
|
||||||
export default function Footer() {
|
export default function Footer() {
|
||||||
const t = useTranslations("Footer");
|
const t = useTranslations("Footer");
|
||||||
const setBurgerMenuIsOpen = useSetAtom(burgerMenuIsOpenAtom);
|
const setBurgerMenuIsOpen = useSetAtom(burgerMenuIsOpenAtom);
|
||||||
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const params = useParams();
|
||||||
|
|
||||||
|
const changeLanguage = (lang: string) => {
|
||||||
|
router.push({ pathname, params: params as any }, { locale: lang });
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<footer
|
<footer
|
||||||
@@ -20,7 +27,7 @@ export default function Footer() {
|
|||||||
data-test="footer"
|
data-test="footer"
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="flex items-center py-2 hover:[&_a]:opacity-80"
|
className="flex items-center py-2 hover:[&_a]:opacity-80 hover:[&_button]:opacity-80"
|
||||||
onClick={() => setBurgerMenuIsOpen(false)}
|
onClick={() => setBurgerMenuIsOpen(false)}
|
||||||
>
|
>
|
||||||
<a
|
<a
|
||||||
@@ -35,13 +42,9 @@ export default function Footer() {
|
|||||||
<FaRegEnvelope />
|
<FaRegEnvelope />
|
||||||
</Link>
|
</Link>
|
||||||
<div className="mr-4 space-x-2 text-xs">
|
<div className="mr-4 space-x-2 text-xs">
|
||||||
<Link href={pathname} locale="fr">
|
<button onClick={() => changeLanguage("fr")}>FR</button>
|
||||||
FR
|
|
||||||
</Link>
|
|
||||||
<span>|</span>
|
<span>|</span>
|
||||||
<Link href={pathname} locale="en">
|
<button onClick={() => changeLanguage("en")}>EN</button>
|
||||||
EN
|
|
||||||
</Link>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs hover:opacity-80">
|
<div className="text-xs hover:opacity-80">
|
||||||
<ThemeSwitcher />
|
<ThemeSwitcher />
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { TimeControl } from "@/types";
|
|||||||
export type ZoneFormValues = z.infer<typeof zoneSchema>;
|
export type ZoneFormValues = z.infer<typeof zoneSchema>;
|
||||||
|
|
||||||
type ZoneFormProps = {
|
type ZoneFormProps = {
|
||||||
|
zone?: ZoneFormValues;
|
||||||
onSubmit: (data: ZoneFormValues) => Promise<void>;
|
onSubmit: (data: ZoneFormValues) => Promise<void>;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
submitTitle?: string;
|
submitTitle?: string;
|
||||||
@@ -22,6 +23,7 @@ type ZoneFormProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const ZoneForm = ({
|
export const ZoneForm = ({
|
||||||
|
zone,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onCancel,
|
onCancel,
|
||||||
submitTitle,
|
submitTitle,
|
||||||
@@ -29,9 +31,11 @@ export const ZoneForm = ({
|
|||||||
}: ZoneFormProps) => {
|
}: ZoneFormProps) => {
|
||||||
const t = useTranslations("Zones");
|
const t = useTranslations("Zones");
|
||||||
const at = useTranslations("App");
|
const at = useTranslations("App");
|
||||||
|
|
||||||
|
// @ts-ignore - Type instantiation is excessively deep and possibly infinite
|
||||||
const form = useForm<ZoneFormValues>({
|
const form = useForm<ZoneFormValues>({
|
||||||
resolver: zodResolver(zoneSchema),
|
resolver: zodResolver(zoneSchema),
|
||||||
defaultValues: {
|
defaultValues: zone ?? {
|
||||||
classicNotifications: false,
|
classicNotifications: false,
|
||||||
rapidNotifications: false,
|
rapidNotifications: false,
|
||||||
blitzNotifications: false,
|
blitzNotifications: false,
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useParams } from "next/navigation";
|
||||||
|
|
||||||
|
import InfoMessage, { clearMessage } from "@/components/InfoMessage";
|
||||||
|
import { editZone } from "@/server/editZone";
|
||||||
|
import { myZones } from "@/server/myZones";
|
||||||
|
import { useRouter } from "@/utils/navigation";
|
||||||
|
|
||||||
|
import { ZoneForm, ZoneFormValues } from "../../components/ZoneForm";
|
||||||
|
|
||||||
|
const EditZone = () => {
|
||||||
|
const t = useTranslations("Zones");
|
||||||
|
const router = useRouter();
|
||||||
|
const params = useParams();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
const [responseMessage, setResponseMessage] = useState({
|
||||||
|
isSuccessful: false,
|
||||||
|
message: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data, isFetching, error, refetch } = useQuery({
|
||||||
|
queryKey: ["zones"],
|
||||||
|
queryFn: async () => myZones(),
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
staleTime: Infinity,
|
||||||
|
gcTime: 10 * 60 * 1000,
|
||||||
|
retry: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const editZoneMutation = useMutation({
|
||||||
|
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) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isFetching && !zone) {
|
||||||
|
router.push("/zones");
|
||||||
|
}
|
||||||
|
|
||||||
|
const onSubmit = async (data: ZoneFormValues) => {
|
||||||
|
await editZoneMutation.mutateAsync(data);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-screen-md px-4 pb-20 pt-8 lg:pt-16">
|
||||||
|
<h2
|
||||||
|
className="mb-4 text-center text-4xl font-extrabold tracking-tight text-gray-900 dark:text-white"
|
||||||
|
data-test="header2"
|
||||||
|
>
|
||||||
|
{t("editTitle")}
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<ZoneForm
|
||||||
|
onSubmit={onSubmit}
|
||||||
|
onCancel={() => router.push("/zones")}
|
||||||
|
zone={zone}
|
||||||
|
/>
|
||||||
|
<InfoMessage responseMessage={responseMessage} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default EditZone;
|
||||||
@@ -57,7 +57,7 @@ const Zones = () => {
|
|||||||
...(zone.rapidNotifications ? [TimeControl.Rapid] : []),
|
...(zone.rapidNotifications ? [TimeControl.Rapid] : []),
|
||||||
...(zone.blitzNotifications ? [TimeControl.Blitz] : []),
|
...(zone.blitzNotifications ? [TimeControl.Blitz] : []),
|
||||||
];
|
];
|
||||||
console.log(notifications);
|
|
||||||
const notificationsList = format.list(
|
const notificationsList = format.list(
|
||||||
notifications.map((tc) => at("timeControlEnumInline", { tc })),
|
notifications.map((tc) => at("timeControlEnumInline", { tc })),
|
||||||
{ type: "conjunction" },
|
{ type: "conjunction" },
|
||||||
@@ -84,12 +84,15 @@ const Zones = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-4">
|
<div className="flex gap-4">
|
||||||
<button
|
<Link
|
||||||
type="button"
|
href={{
|
||||||
|
pathname: "/zones/edit/[id]",
|
||||||
|
params: { id: 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("editButton")}
|
{t("editButton")}
|
||||||
</button>
|
</Link>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
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"
|
||||||
|
|||||||
@@ -19,30 +19,33 @@ export type ZoneEditorProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const ZoneEditor = ({ value, onChange }: ZoneEditorProps) => {
|
export const ZoneEditor = ({ value, onChange }: ZoneEditorProps) => {
|
||||||
const ref = React.useRef<L.FeatureGroup>(null);
|
const initialFeatures = React.useRef(value?.features);
|
||||||
|
const featureGroup = React.useRef<L.FeatureGroup>();
|
||||||
|
|
||||||
React.useEffect(() => {
|
const setFeatureCollectionRef = (element: L.FeatureGroup) => {
|
||||||
if (ref.current?.getLayers().length === 0 && value) {
|
featureGroup.current = element;
|
||||||
|
|
||||||
|
if (element?.getLayers().length === 0 && value) {
|
||||||
L.geoJSON(value).eachLayer((layer) => {
|
L.geoJSON(value).eachLayer((layer) => {
|
||||||
if (
|
if (
|
||||||
layer instanceof L.Polyline ||
|
layer instanceof L.Polyline ||
|
||||||
layer instanceof L.Polygon ||
|
layer instanceof L.Polygon ||
|
||||||
layer instanceof L.Marker
|
layer instanceof L.Marker
|
||||||
) {
|
) {
|
||||||
if (layer?.feature?.properties.radius && ref.current) {
|
if (layer?.feature?.properties.radius && featureGroup.current) {
|
||||||
new L.Circle(layer.feature.geometry.coordinates.slice().reverse(), {
|
new L.Circle(layer.feature.geometry.coordinates.slice().reverse(), {
|
||||||
radius: layer.feature?.properties.radius,
|
radius: layer.feature?.properties.radius,
|
||||||
}).addTo(ref.current);
|
}).addTo(featureGroup.current);
|
||||||
} else {
|
} else {
|
||||||
ref.current?.addLayer(layer);
|
featureGroup.current?.addLayer(layer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [value]);
|
};
|
||||||
|
|
||||||
const handleChange = () => {
|
const handleChange = () => {
|
||||||
const geoJson = ref.current?.toGeoJSON();
|
const geoJson = featureGroup.current?.toGeoJSON();
|
||||||
if (geoJson?.type === "FeatureCollection") {
|
if (geoJson?.type === "FeatureCollection") {
|
||||||
onChange(geoJson);
|
onChange(geoJson);
|
||||||
}
|
}
|
||||||
@@ -54,13 +57,19 @@ export const ZoneEditor = ({ value, onChange }: ZoneEditorProps) => {
|
|||||||
zoom={5}
|
zoom={5}
|
||||||
style={{ height: "600px", flexGrow: 1 }}
|
style={{ height: "600px", flexGrow: 1 }}
|
||||||
>
|
>
|
||||||
<MapEvents />
|
<MapEvents
|
||||||
|
bounds={
|
||||||
|
(initialFeatures.current ?? []).length > 0
|
||||||
|
? L.geoJson(initialFeatures.current).getBounds()
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
<TileLayer
|
<TileLayer
|
||||||
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
|
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
|
||||||
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<FeatureGroup ref={ref}>
|
<FeatureGroup ref={setFeatureCollectionRef}>
|
||||||
<EditControl
|
<EditControl
|
||||||
position="topright"
|
position="topright"
|
||||||
onEdited={handleChange}
|
onEdited={handleChange}
|
||||||
|
|||||||
@@ -243,6 +243,7 @@
|
|||||||
"addZoneButton": "Add a Region",
|
"addZoneButton": "Add a Region",
|
||||||
|
|
||||||
"createTitle": "Create a new zone",
|
"createTitle": "Create a new zone",
|
||||||
|
"editTitle": "Edit zone",
|
||||||
|
|
||||||
"zoneNameLabel": "Zone name",
|
"zoneNameLabel": "Zone name",
|
||||||
"zoneNamePlaceholder": "Name for your zone",
|
"zoneNamePlaceholder": "Name for your zone",
|
||||||
|
|||||||
@@ -244,6 +244,7 @@
|
|||||||
"addZoneButton": "Ajouter une région",
|
"addZoneButton": "Ajouter une région",
|
||||||
|
|
||||||
"createTitle": "Créer une nouvelle région",
|
"createTitle": "Créer une nouvelle région",
|
||||||
|
"editTitle": "Modifier région",
|
||||||
|
|
||||||
"zoneNameLabel": "Nom de la région",
|
"zoneNameLabel": "Nom de la région",
|
||||||
"zoneNamePlaceholder": "Votre nom pour cette région",
|
"zoneNamePlaceholder": "Votre nom pour cette région",
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ export const createZone = action(zoneSchema, async (input) => {
|
|||||||
|
|
||||||
const result = await collections.zones!.insertOne(zoneData);
|
const result = await collections.zones!.insertOne(zoneData);
|
||||||
|
|
||||||
|
if (!result.acknowledged) {
|
||||||
|
throw new Error("ERR_ZONE_INSERT_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errorLog(error);
|
errorLog(error);
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { omit } from "lodash";
|
||||||
|
import { ObjectId } from "mongodb";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { zoneSchema } from "@/schemas";
|
||||||
|
import { collections, dbConnect } from "@/server/mongodb";
|
||||||
|
import { errorLog } from "@/utils/logger";
|
||||||
|
|
||||||
|
import { ZoneModel } from "./models/zoneModel";
|
||||||
|
import { action } from "./safeAction";
|
||||||
|
|
||||||
|
const editZoneSchema = z.object({
|
||||||
|
id: z.string(),
|
||||||
|
zone: zoneSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const editZone = action(editZoneSchema, async ({ id, zone }) => {
|
||||||
|
try {
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
const user = await auth();
|
||||||
|
if (!user?.user) {
|
||||||
|
throw new Error("You must be logged in to create a zone");
|
||||||
|
}
|
||||||
|
|
||||||
|
const zoneData: ZoneModel = {
|
||||||
|
...zone,
|
||||||
|
userId: new ObjectId(user.user!.id!),
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await collections.zones!.findOneAndUpdate(
|
||||||
|
{ _id: new ObjectId(id), userId: new ObjectId(user.user!.id!) },
|
||||||
|
{ $set: { _id: new ObjectId(id), ...zoneData } },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
throw new Error("ERR_ZONE_UPDATE_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...omit(result, ["_id"]),
|
||||||
|
id: result._id.toString(),
|
||||||
|
userId: result.userId.toString(),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
errorLog(error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
+22
-5
@@ -27,17 +27,34 @@ if (!process.env.MONGODB_URI) {
|
|||||||
throw new Error("Please add your Mongo URI to .env.local");
|
throw new Error("Please add your Mongo URI to .env.local");
|
||||||
}
|
}
|
||||||
|
|
||||||
client = new MongoClient(uri, options);
|
if (process.env.NODE_ENV === "development") {
|
||||||
clientPromise = client.connect();
|
// In development mode, use a global variable so that the value
|
||||||
|
// is preserved across module reloads caused by HMR (Hot Module Replacement).
|
||||||
|
|
||||||
|
//@ts-ignore
|
||||||
|
if (!global._mongoClientPromise) {
|
||||||
|
client = new MongoClient(uri, options);
|
||||||
|
|
||||||
|
//@ts-ignore
|
||||||
|
global._mongoClientPromise = client.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
//@ts-ignore
|
||||||
|
clientPromise = global._mongoClientPromise;
|
||||||
|
} else {
|
||||||
|
// In production mode, it's best to not use a global variable.
|
||||||
|
client = new MongoClient(uri, options);
|
||||||
|
clientPromise = client.connect();
|
||||||
|
}
|
||||||
|
|
||||||
export async function dbConnect() {
|
export async function dbConnect() {
|
||||||
await clientPromise;
|
const p = await clientPromise;
|
||||||
|
|
||||||
const userData: mongoDB.Db = client!.db("userData");
|
const userData: mongoDB.Db = p.db("userData");
|
||||||
collections.users = userData.collection("userData");
|
collections.users = userData.collection("userData");
|
||||||
collections.zones = userData.collection("zones");
|
collections.zones = userData.collection("zones");
|
||||||
|
|
||||||
const tournamentData: mongoDB.Db = client!.db("tournamentsFranceDB");
|
const tournamentData: mongoDB.Db = p.db("tournamentsFranceDB");
|
||||||
collections.tournaments = tournamentData.collection("tournaments");
|
collections.tournaments = tournamentData.collection("tournaments");
|
||||||
collections.clubs = tournamentData.collection("clubs");
|
collections.clubs = tournamentData.collection("clubs");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,11 @@ export const pathnames = {
|
|||||||
en: "/zones/create",
|
en: "/zones/create",
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"/zones/edit/[id]": {
|
||||||
|
fr: "/regions/modifier/[id]",
|
||||||
|
en: "/zones/edit/[id]",
|
||||||
|
},
|
||||||
|
|
||||||
"/add-tournament": {
|
"/add-tournament": {
|
||||||
fr: "/ajouter-un-tournoi",
|
fr: "/ajouter-un-tournoi",
|
||||||
en: "/add-tournament",
|
en: "/add-tournament",
|
||||||
@@ -36,6 +41,8 @@ export const pathnames = {
|
|||||||
fr: "/contactez-nous",
|
fr: "/contactez-nous",
|
||||||
en: "/contact-us",
|
en: "/contact-us",
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"[...rest]": "[...rest]",
|
||||||
} satisfies Pathnames<typeof locales>;
|
} satisfies Pathnames<typeof locales>;
|
||||||
|
|
||||||
export const { Link, redirect, usePathname, useRouter, getPathname } =
|
export const { Link, redirect, usePathname, useRouter, getPathname } =
|
||||||
|
|||||||
Reference in New Issue
Block a user