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 { useTranslations } from "next-intl";
|
||||
import { useParams } from "next/navigation";
|
||||
import { FaGithub, FaRegEnvelope } from "react-icons/fa";
|
||||
|
||||
import { burgerMenuIsOpenAtom } from "@/atoms";
|
||||
import { Link, usePathname } from "@/utils/navigation";
|
||||
import { Link, usePathname, useRouter } from "@/utils/navigation";
|
||||
|
||||
import ThemeSwitcher from "./ThemeSwitcher";
|
||||
|
||||
export default function Footer() {
|
||||
const t = useTranslations("Footer");
|
||||
const setBurgerMenuIsOpen = useSetAtom(burgerMenuIsOpenAtom);
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const params = useParams();
|
||||
|
||||
const changeLanguage = (lang: string) => {
|
||||
router.push({ pathname, params: params as any }, { locale: lang });
|
||||
};
|
||||
|
||||
return (
|
||||
<footer
|
||||
@@ -20,7 +27,7 @@ export default function Footer() {
|
||||
data-test="footer"
|
||||
>
|
||||
<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)}
|
||||
>
|
||||
<a
|
||||
@@ -35,13 +42,9 @@ export default function Footer() {
|
||||
<FaRegEnvelope />
|
||||
</Link>
|
||||
<div className="mr-4 space-x-2 text-xs">
|
||||
<Link href={pathname} locale="fr">
|
||||
FR
|
||||
</Link>
|
||||
<button onClick={() => changeLanguage("fr")}>FR</button>
|
||||
<span>|</span>
|
||||
<Link href={pathname} locale="en">
|
||||
EN
|
||||
</Link>
|
||||
<button onClick={() => changeLanguage("en")}>EN</button>
|
||||
</div>
|
||||
<div className="text-xs hover:opacity-80">
|
||||
<ThemeSwitcher />
|
||||
|
||||
@@ -15,6 +15,7 @@ import { TimeControl } from "@/types";
|
||||
export type ZoneFormValues = z.infer<typeof zoneSchema>;
|
||||
|
||||
type ZoneFormProps = {
|
||||
zone?: ZoneFormValues;
|
||||
onSubmit: (data: ZoneFormValues) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
submitTitle?: string;
|
||||
@@ -22,6 +23,7 @@ type ZoneFormProps = {
|
||||
};
|
||||
|
||||
export const ZoneForm = ({
|
||||
zone,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
submitTitle,
|
||||
@@ -29,9 +31,11 @@ export const ZoneForm = ({
|
||||
}: ZoneFormProps) => {
|
||||
const t = useTranslations("Zones");
|
||||
const at = useTranslations("App");
|
||||
|
||||
// @ts-ignore - Type instantiation is excessively deep and possibly infinite
|
||||
const form = useForm<ZoneFormValues>({
|
||||
resolver: zodResolver(zoneSchema),
|
||||
defaultValues: {
|
||||
defaultValues: zone ?? {
|
||||
classicNotifications: false,
|
||||
rapidNotifications: 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.blitzNotifications ? [TimeControl.Blitz] : []),
|
||||
];
|
||||
console.log(notifications);
|
||||
|
||||
const notificationsList = format.list(
|
||||
notifications.map((tc) => at("timeControlEnumInline", { tc })),
|
||||
{ type: "conjunction" },
|
||||
@@ -84,12 +84,15 @@ const Zones = () => {
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4">
|
||||
<button
|
||||
type="button"
|
||||
<Link
|
||||
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"
|
||||
>
|
||||
{t("editButton")}
|
||||
</button>
|
||||
</Link>
|
||||
<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"
|
||||
|
||||
@@ -19,30 +19,33 @@ export type 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(() => {
|
||||
if (ref.current?.getLayers().length === 0 && value) {
|
||||
const setFeatureCollectionRef = (element: L.FeatureGroup) => {
|
||||
featureGroup.current = element;
|
||||
|
||||
if (element?.getLayers().length === 0 && value) {
|
||||
L.geoJSON(value).eachLayer((layer) => {
|
||||
if (
|
||||
layer instanceof L.Polyline ||
|
||||
layer instanceof L.Polygon ||
|
||||
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(), {
|
||||
radius: layer.feature?.properties.radius,
|
||||
}).addTo(ref.current);
|
||||
}).addTo(featureGroup.current);
|
||||
} else {
|
||||
ref.current?.addLayer(layer);
|
||||
featureGroup.current?.addLayer(layer);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [value]);
|
||||
};
|
||||
|
||||
const handleChange = () => {
|
||||
const geoJson = ref.current?.toGeoJSON();
|
||||
const geoJson = featureGroup.current?.toGeoJSON();
|
||||
if (geoJson?.type === "FeatureCollection") {
|
||||
onChange(geoJson);
|
||||
}
|
||||
@@ -54,13 +57,19 @@ export const ZoneEditor = ({ value, onChange }: ZoneEditorProps) => {
|
||||
zoom={5}
|
||||
style={{ height: "600px", flexGrow: 1 }}
|
||||
>
|
||||
<MapEvents />
|
||||
<MapEvents
|
||||
bounds={
|
||||
(initialFeatures.current ?? []).length > 0
|
||||
? L.geoJson(initialFeatures.current).getBounds()
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<TileLayer
|
||||
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
|
||||
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||
/>
|
||||
|
||||
<FeatureGroup ref={ref}>
|
||||
<FeatureGroup ref={setFeatureCollectionRef}>
|
||||
<EditControl
|
||||
position="topright"
|
||||
onEdited={handleChange}
|
||||
|
||||
@@ -243,6 +243,7 @@
|
||||
"addZoneButton": "Add a Region",
|
||||
|
||||
"createTitle": "Create a new zone",
|
||||
"editTitle": "Edit zone",
|
||||
|
||||
"zoneNameLabel": "Zone name",
|
||||
"zoneNamePlaceholder": "Name for your zone",
|
||||
|
||||
@@ -244,6 +244,7 @@
|
||||
"addZoneButton": "Ajouter une région",
|
||||
|
||||
"createTitle": "Créer une nouvelle région",
|
||||
"editTitle": "Modifier région",
|
||||
|
||||
"zoneNameLabel": "Nom de la 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);
|
||||
|
||||
if (!result.acknowledged) {
|
||||
throw new Error("ERR_ZONE_INSERT_FAILED");
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (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;
|
||||
}
|
||||
});
|
||||
+20
-3
@@ -27,17 +27,34 @@ if (!process.env.MONGODB_URI) {
|
||||
throw new Error("Please add your Mongo URI to .env.local");
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
// 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() {
|
||||
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.zones = userData.collection("zones");
|
||||
|
||||
const tournamentData: mongoDB.Db = client!.db("tournamentsFranceDB");
|
||||
const tournamentData: mongoDB.Db = p.db("tournamentsFranceDB");
|
||||
collections.tournaments = tournamentData.collection("tournaments");
|
||||
collections.clubs = tournamentData.collection("clubs");
|
||||
}
|
||||
|
||||
@@ -27,6 +27,11 @@ export const pathnames = {
|
||||
en: "/zones/create",
|
||||
},
|
||||
|
||||
"/zones/edit/[id]": {
|
||||
fr: "/regions/modifier/[id]",
|
||||
en: "/zones/edit/[id]",
|
||||
},
|
||||
|
||||
"/add-tournament": {
|
||||
fr: "/ajouter-un-tournoi",
|
||||
en: "/add-tournament",
|
||||
@@ -36,6 +41,8 @@ export const pathnames = {
|
||||
fr: "/contactez-nous",
|
||||
en: "/contact-us",
|
||||
},
|
||||
|
||||
"[...rest]": "[...rest]",
|
||||
} satisfies Pathnames<typeof locales>;
|
||||
|
||||
export const { Link, redirect, usePathname, useRouter, getPathname } =
|
||||
|
||||
Reference in New Issue
Block a user