feat: Implement connected user API and integrate chat and report components

- Added API routes for fetching connected users, keywords, missions, and stations.
- Created a new QueryProvider component for managing query states and socket events.
- Introduced connection stores for dispatch and pilot, managing socket connections and states.
- Updated Prisma schema for connected aircraft model.
- Enhanced UI with toast notifications for status updates and chat interactions.
- Implemented query functions for fetching connected users and keywords with error handling.
This commit is contained in:
PxlLoewe
2025-05-07 00:43:45 -07:00
parent 152b3d4689
commit 50f42e99d3
49 changed files with 1040 additions and 701 deletions

View File

@@ -1,224 +0,0 @@
"use client";
import { ChatBubbleIcon, PaperPlaneIcon } from "@radix-ui/react-icons";
import { useLeftMenuStore } from "_store/leftMenuStore";
import { useSession } from "next-auth/react";
import { Fragment, useEffect, useRef, useState } from "react";
import { cn } from "helpers/cn";
import { getConenctedUsers } from "helpers/axios";
import { asPublicUser, ConnectedAircraft, ConnectedDispatcher } from "@repo/db";
export const Chat = () => {
const {
setReportTabOpen,
chatOpen,
setChatOpen,
sendMessage,
addChat,
chats,
setOwnId,
selectedChat,
setSelectedChat,
setChatNotification,
} = useLeftMenuStore();
const [sending, setSending] = useState(false);
const session = useSession();
const [addTabValue, setAddTabValue] = useState<string>("");
const [message, setMessage] = useState<string>("");
const [connectedUser, setConnectedUser] = useState<
(ConnectedAircraft | ConnectedDispatcher)[] | null
>(null);
const timeout = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (!session.data?.user.id) return;
setOwnId(session.data.user.id);
}, [session, setOwnId]);
useEffect(() => {
const fetchConnectedUser = async () => {
const data = await getConenctedUsers();
if (data) {
const filteredConnectedUser = data.filter((user) => {
return (
user.userId !== session.data?.user.id &&
!Object.keys(chats).includes(user.userId)
);
return true;
});
setConnectedUser(filteredConnectedUser);
}
if (!addTabValue && data[0]) setAddTabValue(data[0].userId);
};
timeout.current = setInterval(() => {
fetchConnectedUser();
}, 1000);
fetchConnectedUser();
return () => {
if (timeout.current) {
clearInterval(timeout.current);
timeout.current = null;
console.log("cleared");
}
};
}, [addTabValue, chats, session.data?.user.id]);
return (
<div className={cn("dropdown dropdown-right", chatOpen && "dropdown-open")}>
<div className="indicator">
{Object.values(chats).some((c) => c.notification) && (
<span className="indicator-item status status-info"></span>
)}
<button
className="btn btn-soft btn-sm btn-primary"
onClick={() => {
setReportTabOpen(false);
setChatOpen(!chatOpen);
if (selectedChat) {
setChatNotification(selectedChat, false);
}
}}
>
<ChatBubbleIcon className="w-4 h-4" />
</button>
</div>
{chatOpen && (
<div
tabIndex={0}
className="dropdown-content card bg-base-200 w-150 shadow-md z-[1100] ml-2 border-1 border-primary"
>
<div className="card-body">
<h2 className="inline-flex items-center gap-2 text-lg font-bold mb-2">
<ChatBubbleIcon /> Chat
</h2>
<div className="join">
<select
className="select select-sm w-full"
value={addTabValue}
onChange={(e) => setAddTabValue(e.target.value)}
>
{!connectedUser?.length && (
<option disabled={true}>Keine Chatpartner gefunden</option>
)}
{connectedUser?.map((user) => (
<option key={user.userId} value={user.userId}>
{asPublicUser(user.publicUser).fullName}
</option>
))}
</select>
<button
className="btn btn-sm btn-soft btn-primary join-item"
onClick={() => {
const user = connectedUser?.find(
(user) => user.userId === addTabValue,
);
if (!user) return;
addChat(addTabValue, asPublicUser(user.publicUser).fullName);
setSelectedChat(addTabValue);
}}
>
<span className="text-xl">+</span>
</button>
</div>
<div className="tabs tabs-lift">
{Object.keys(chats).map((userId) => {
const chat = chats[userId];
if (!chat) return null;
return (
<Fragment key={userId}>
<input
type="radio"
name="my_tabs_3"
className="tab"
aria-label={`<${chat.name}>`}
checked={selectedChat === userId}
onClick={() => {
setChatNotification(userId, false);
}}
onChange={(e) => {
if (e.target.checked) {
// Handle tab change
setSelectedChat(userId);
}
}}
/>
<div className="tab-content bg-base-100 border-base-300 p-6">
{chat.messages.map((chatMessage) => {
const isSender =
chatMessage.senderId === session.data?.user.id;
return (
<div
key={chatMessage.id}
className={`chat ${isSender ? "chat-end" : "chat-start"}`}
>
<p className="chat-footer opacity-50">
{new Date(
chatMessage.timestamp,
).toLocaleTimeString()}
</p>
<div className="chat-bubble">
{chatMessage.text}
</div>
</div>
);
})}
{!chat.messages.length && (
<p className="text-xs opacity-50">
Noch keine Nachrichten
</p>
)}
</div>
</Fragment>
);
})}
</div>
<div className="join">
<div className="w-full">
<label className="input join-item w-full">
<input
type="text"
required
className="w-full"
onChange={(e) => {
setMessage(e.target.value);
}}
value={message}
/>
</label>
</div>
<button
className="btn btn-soft join-item"
onClick={(e) => {
e.preventDefault();
if (message.length < 1) return;
if (!selectedChat) return;
setSending(true);
sendMessage(selectedChat, message)
.then(() => {
setMessage("");
setSending(false);
})
.catch(() => {
setSending(false);
});
return false;
}}
disabled={sending}
role="button"
onSubmit={() => false} // prevent submit event for react hook form
>
{sending ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
<PaperPlaneIcon />
)}
</button>
</div>
</div>
</div>
)}
</div>
);
};

View File

@@ -1,143 +0,0 @@
"use client";
import { ExclamationTriangleIcon, PaperPlaneIcon } from "@radix-ui/react-icons";
import { useSession } from "next-auth/react";
import { useEffect, useRef, useState } from "react";
import { cn } from "helpers/cn";
import { getConenctedUsers, serverApi } from "helpers/axios";
import { useLeftMenuStore } from "_store/leftMenuStore";
import { asPublicUser, ConnectedAircraft, ConnectedDispatcher } from "@repo/db";
export const Report = () => {
const { setChatOpen, setReportTabOpen, reportTabOpen, setOwnId } =
useLeftMenuStore();
const [sending, setSending] = useState(false);
const session = useSession();
const [selectedPlayer, setSelectedPlayer] = useState<string>("");
const [message, setMessage] = useState<string>("");
const [connectedUser, setConnectedUser] = useState<
(ConnectedAircraft | ConnectedDispatcher)[] | null
>(null);
const timeout = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (!session.data?.user.id) return;
setOwnId(session.data.user.id);
}, [session, setOwnId]);
useEffect(() => {
const fetchConnectedUser = async () => {
const data = await getConenctedUsers();
if (data) {
const filteredConnectedUser = data.filter(
(user) => user.userId !== session.data?.user.id,
);
setConnectedUser(filteredConnectedUser);
}
if (!selectedPlayer && data[0]) setSelectedPlayer(data[0].userId);
};
timeout.current = setInterval(() => {
fetchConnectedUser();
}, 1000);
fetchConnectedUser();
return () => {
if (timeout.current) {
clearInterval(timeout.current);
timeout.current = null;
}
};
}, [selectedPlayer, session.data?.user.id]);
return (
<div
className={cn(
"dropdown dropdown-right",
reportTabOpen && "dropdown-open",
)}
>
<div className="indicator">
<button
className="btn btn-soft btn-sm btn-error"
onClick={() => {
setChatOpen(false);
setReportTabOpen(!reportTabOpen);
}}
>
<ExclamationTriangleIcon className="w-4 h-4" />
</button>
</div>
{reportTabOpen && (
<div
tabIndex={0}
className="dropdown-content card bg-base-200 w-150 shadow-md z-[1100] ml-2 border-1 border-error"
>
<div className="card-body">
<h2 className="inline-flex items-center gap-2 text-lg font-bold mb-2">
<ExclamationTriangleIcon /> Report senden
</h2>
<div className="join">
<select
className="select select-sm w-full"
value={selectedPlayer}
onChange={(e) => setSelectedPlayer(e.target.value)}
>
{!connectedUser?.length && (
<option disabled={true}>Keine Spieler gefunden</option>
)}
{connectedUser?.map((user) => (
<option key={user.userId} value={user.userId}>
{asPublicUser(user).fullName}
</option>
))}
</select>
</div>
<div className="join mt-4">
<div className="w-full">
<label className="input join-item w-full">
<input
type="text"
required
className="w-full"
placeholder="Nachricht eingeben"
onChange={(e) => setMessage(e.target.value)}
value={message}
/>
</label>
</div>
<button
className="btn btn-soft join-item"
onClick={(e) => {
e.preventDefault();
if (message.length < 1 || !selectedPlayer) return;
setSending(true);
serverApi("/report", {
method: "POST",
data: {
message,
to: selectedPlayer,
},
})
.then(() => {
setMessage("");
setSending(false);
})
.catch(() => {
setSending(false);
});
}}
disabled={sending}
>
{sending ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
<PaperPlaneIcon />
)}
</button>
</div>
</div>
</div>
)}
</div>
);
};

View File

@@ -1,4 +1,3 @@
import { useMissionsStore } from "_store/missionsStore";
import { Marker, useMap } from "react-leaflet";
import { DivIcon, Marker as LMarker, Popup as LPopup } from "leaflet";
import { useMapStore } from "_store/mapStore";
@@ -31,6 +30,8 @@ import Einsatzdetails, {
Patientdetails,
Rettungsmittel,
} from "./_components/MissionMarkerTabs";
import { useQuery } from "@tanstack/react-query";
import { getMissionsAPI } from "querys/missions";
export const MISSION_STATUS_COLORS: Record<MissionState | "attention", string> =
{
@@ -367,7 +368,13 @@ const MissionMarker = ({ mission }: { mission: Mission }) => {
};
export const MissionLayer = () => {
const missions = useMissionsStore((state) => state.missions);
const { data: missions = [] } = useQuery({
queryKey: ["missions"],
queryFn: () =>
getMissionsAPI({
OR: [{ state: "draft" }, { state: "running" }],
}),
});
// IDEA: Add Marker to Map Layer / LayerGroup
return (

View File

@@ -1,8 +1,8 @@
import { Mission } from "@repo/db";
import { useQuery } from "@tanstack/react-query";
import { SmartPopup, useSmartPopup } from "_components/SmartPopup";
import { Aircraft, useAircraftsStore } from "_store/aircraftsStore";
import { useMapStore } from "_store/mapStore";
import { useMissionsStore } from "_store/missionsStore";
import {
FMS_STATUS_COLORS,
FMS_STATUS_TEXT_COLORS,
@@ -12,6 +12,7 @@ import {
MISSION_STATUS_TEXT_COLORS,
} from "dispatch/_components/map/MissionMarkers";
import { cn } from "helpers/cn";
import { getMissionsAPI } from "querys/missions";
import { useEffect, useState } from "react";
import { useMap } from "react-leaflet";
@@ -141,7 +142,13 @@ const PopupContent = ({
export const MarkerCluster = () => {
const map = useMap();
const aircrafts = useAircraftsStore((state) => state.aircrafts);
const missions = useMissionsStore((state) => state.missions);
const { data: missions } = useQuery({
queryKey: ["missions"],
queryFn: () =>
getMissionsAPI({
OR: [{ state: "draft" }, { state: "running" }],
}),
});
const [cluster, setCluster] = useState<
{
aircrafts: Aircraft[];
@@ -185,7 +192,7 @@ export const MarkerCluster = () => {
];
}
});
missions.forEach((mission) => {
missions?.forEach((mission) => {
const lat = mission.addressLat;
const lng = mission.addressLng;
const existingClusterIndex = newCluster.findIndex(

View File

@@ -24,13 +24,24 @@ import {
Mission,
MissionLog,
MissionMessageLog,
Prisma,
} from "@repo/db";
import { useMissionsStore } from "_store/missionsStore";
import { usePannelStore } from "_store/pannelStore";
import { useSession } from "next-auth/react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { deleteMissionAPI, editMissionAPI } from "querys/missions";
const Einsatzdetails = ({ mission }: { mission: Mission }) => {
const { deleteMission } = useMissionsStore((state) => state);
const queryClient = useQueryClient();
const deleteMissionMutation = useMutation({
mutationKey: ["missions"],
mutationFn: deleteMissionAPI,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["missions"],
});
},
});
const { setMissionFormValues, setOpen } = usePannelStore((state) => state);
return (
<div className="p-4 text-base-content">
@@ -93,7 +104,7 @@ const Einsatzdetails = ({ mission }: { mission: Mission }) => {
<button
className="btn btn-sm btn-error btn-outline"
onClick={() => {
deleteMission(mission.id);
deleteMissionMutation.mutate(mission.id);
}}
>
<Trash size={18} />
@@ -180,8 +191,22 @@ const Rettungsmittel = ({ mission }: { mission: Mission }) => {
const FMSStatusHistory = ({ mission }: { mission: Mission }) => {
const session = useSession();
const [isAddingNote, setIsAddingNote] = useState(false);
const { editMission } = useMissionsStore((state) => state);
const [note, setNote] = useState("");
const queryClient = useQueryClient();
const editMissionMutation = useMutation({
mutationFn: ({
id,
mission,
}: {
id: number;
mission: Partial<Prisma.MissionUpdateInput>;
}) => editMissionAPI(id, mission),
mutationKey: ["missions"],
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["missions"] });
},
});
if (!session.data?.user) return null;
return (
@@ -220,13 +245,18 @@ const FMSStatusHistory = ({ mission }: { mission: Mission }) => {
},
} as MissionMessageLog,
];
editMission(mission.id, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
missionLog: newMissionLog as any,
}).then(() => {
setIsAddingNote(false);
setNote("");
});
editMissionMutation
.mutateAsync({
id: mission.id,
mission: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
missionLog: newMissionLog as any,
},
})
.then(() => {
setIsAddingNote(false);
setNote("");
});
}}
>
<Plus size={20} />

View File

@@ -1,7 +1,7 @@
"use client";
import { useEffect, useState } from "react";
import { useDispatchConnectionStore } from "_store/connectionStore";
import { useDispatchConnectionStore } from "_store/dispatch/connectionStore";
import {
Disc,
Mic,

View File

@@ -1,6 +1,6 @@
"use client";
import { useSession } from "next-auth/react";
import { useDispatchConnectionStore } from "../../../../_store/connectionStore";
import { useDispatchConnectionStore } from "../../../../_store/dispatch/connectionStore";
import { useRef, useState } from "react";
export const ConnectionBtn = () => {

View File

@@ -1,11 +0,0 @@
"use server";
export interface Dispatcher {
userId: string;
lastSeen: string;
loginTime: string;
logoffTime: string;
selectedZone: string;
name: string;
socketId: string;
}

View File

@@ -1,11 +1,10 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { BellRing, BookmarkPlus } from "lucide-react";
import { Select } from "_components/Select";
import { Keyword, KEYWORD_CATEGORY, missionType, Station } from "@repo/db";
import { getKeywords, getStations } from "dispatch/_components/pannel/action";
import { KEYWORD_CATEGORY, missionType, Prisma } from "@repo/db";
import {
MissionOptionalDefaults,
MissionOptionalDefaultsSchema,
@@ -13,13 +12,52 @@ import {
import { usePannelStore } from "_store/pannelStore";
import { useSession } from "next-auth/react";
import { toast } from "react-hot-toast";
import { useMissionsStore } from "_store/missionsStore";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createMissionAPI, editMissionAPI } from "querys/missions";
import { getKeywordsAPI } from "querys/keywords";
import { getStationsAPI } from "querys/stations";
export const MissionForm = () => {
const { isEditingMission, editingMissionId, setEditingMission } =
usePannelStore();
const createMission = useMissionsStore((state) => state.createMission);
const { deleteMission } = useMissionsStore((state) => state);
const queryClient = useQueryClient();
const { data: keywords } = useQuery({
queryKey: ["keywords"],
queryFn: () => getKeywordsAPI(),
});
const { data: stations } = useQuery({
queryKey: ["stations"],
queryFn: () => getStationsAPI(),
});
const createMissionMutation = useMutation({
mutationFn: createMissionAPI,
mutationKey: ["missions"],
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["missions"],
});
},
});
const editMissionMutation = useMutation({
mutationFn: ({
id,
mission,
}: {
id: number;
mission: Partial<Prisma.MissionUpdateInput>;
}) => editMissionAPI(id, mission),
mutationKey: ["missions"],
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["missions"],
});
},
});
const session = useSession();
const defaultFormValues = React.useMemo(
() =>
@@ -85,18 +123,6 @@ export const MissionForm = () => {
}
}, [missionFormValues, form, defaultFormValues]);
const [stations, setStations] = useState<Station[]>([]);
const [keywords, setKeywords] = useState<Keyword[]>([]);
useEffect(() => {
getKeywords().then((data) => {
setKeywords(data);
});
getStations().then((data) => {
setStations(data);
});
}, []);
console.log(form.formState.errors);
return (
<form className="space-y-4">
@@ -165,7 +191,7 @@ export const MissionForm = () => {
placeholder="Wähle ein oder mehrere Rettungsmittel aus"
isMulti
form={form}
options={stations.map((s) => ({
options={stations?.map((s) => ({
label: s.bosCallsign,
value: s.id.toString(),
}))}
@@ -217,7 +243,7 @@ export const MissionForm = () => {
{...form.register("missionKeywordAbbreviation")}
className="select select-primary select-bordered w-full mb-4"
onChange={(e) => {
const keyword = keywords.find(
const keyword = keywords?.find(
(k) => k.abreviation === e.target.value,
);
form.setValue("missionKeywordName", keyword?.name || null);
@@ -232,15 +258,16 @@ export const MissionForm = () => {
<option disabled value={""}>
Einsatzstichwort auswählen...
</option>
{keywords
.filter(
(k) => k.category === form.watch("missionKeywordCategory"),
)
.map((keyword) => (
<option key={keyword.id} value={keyword.abreviation}>
{keyword.name}
</option>
))}
{keywords &&
keywords
.filter(
(k) => k.category === form.watch("missionKeywordCategory"),
)
.map((keyword) => (
<option key={keyword.id} value={keyword.abreviation}>
{keyword.name}
</option>
))}
</select>
{/* TODO: Nur anzeigen wenn eine Station mit HPG ausgewählt ist */}
<select
@@ -251,16 +278,17 @@ export const MissionForm = () => {
<option disabled value="">
Einsatz Szenerie auswählen...
</option>
{keywords
.find((k) => k.name === form.watch("missionKeywordName"))
?.hpgMissionTypes?.map((missionString) => {
const [name] = missionString.split(":");
return (
<option key={missionString} value={missionString}>
{name}
</option>
);
})}
{keywords &&
keywords
.find((k) => k.name === form.watch("missionKeywordName"))
?.hpgMissionTypes?.map((missionString) => {
const [name] = missionString.split(":");
return (
<option key={missionString} value={missionString}>
{name}
</option>
);
})}
</select>
</>
)}
@@ -277,8 +305,6 @@ export const MissionForm = () => {
/>
)}
</div>
{/* Patienteninformationen Section */}
<div className="form-control">
<h2 className="text-lg font-bold mb-2">Patienteninformationen</h2>
<textarea
@@ -287,22 +313,24 @@ export const MissionForm = () => {
className="textarea textarea-primary textarea-bordered w-full"
/>
</div>
<p className="text-sm text-error">
Du musst noch ein Gebäude auswählen, um den Einsatz zu erstellen.
</p>
<div className="form-control min-h-[140px] max-w-[320px]">
<div className="form-control min-h-[140px]">
<div className="flex gap-2">
{isEditingMission && editingMissionId ? (
<button
type="button"
className="btn btn-primary btn-block"
className="btn btn-primary flex-1"
onClick={form.handleSubmit(
async (mission: MissionOptionalDefaults) => {
try {
deleteMission(Number(editingMissionId));
const newMission = await createMission(mission);
const newMission = await editMissionMutation.mutateAsync({
id: Number(editingMissionId),
mission:
mission as unknown as Partial<Prisma.MissionUpdateInput>,
});
toast.success(
`Einsatz ${newMission.id} erfolgreich aktualisiert`,
);
@@ -327,7 +355,10 @@ export const MissionForm = () => {
onClick={form.handleSubmit(
async (mission: MissionOptionalDefaults) => {
try {
const newMission = await createMission(mission);
const newMission =
await createMissionMutation.mutateAsync(
mission as unknown as Prisma.MissionCreateInput,
);
toast.success(`Einsatz ${newMission.id} erstellt`);
// TODO: Einsatz alarmieren
setOpen(false);
@@ -343,11 +374,15 @@ export const MissionForm = () => {
</button>
<button
type="submit"
className="btn btn-primary btn-block"
className="btn btn-primary flex-1"
onClick={form.handleSubmit(
async (mission: MissionOptionalDefaults) => {
try {
const newMission = await createMission(mission);
const newMission =
await createMissionMutation.mutateAsync(
mission as unknown as Prisma.MissionCreateInput,
);
toast.success(`Einsatz ${newMission.id} erstellt`);
form.reset();
setOpen(false);

View File

@@ -2,10 +2,41 @@ import { usePannelStore } from "_store/pannelStore";
import { cn } from "helpers/cn";
import { MissionForm } from "./MissionForm";
import { Rss, Trash2Icon } from "lucide-react";
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { getMissionsAPI } from "querys/missions";
export const Pannel = () => {
const { setOpen, setMissionFormValues } = usePannelStore();
const { isEditingMission, setEditingMission } = usePannelStore();
const { isEditingMission, setEditingMission, missionFormValues } =
usePannelStore();
const missions = useQuery({
queryKey: ["missions"],
queryFn: () =>
getMissionsAPI({
OR: [{ state: "draft" }, { state: "running" }],
}),
});
useEffect(() => {
if (isEditingMission && missionFormValues) {
const mission = missions.data?.find(
(mission) => mission.id === missionFormValues.id,
);
if (!mission) {
setEditingMission(false, null);
setMissionFormValues({});
setOpen(false);
}
}
}, [
isEditingMission,
missions,
setMissionFormValues,
setEditingMission,
setOpen,
missionFormValues,
]);
return (
<div className={cn("flex-1 max-w-[600px] z-9999999")}>

View File

@@ -1,15 +0,0 @@
"use server";
import { prisma } from "@repo/db";
export const getKeywords = async () => {
const keywords = prisma.keyword.findMany();
return keywords;
};
export const getStations = async () => {
const stations = await prisma.station.findMany();
console.log(stations);
return stations;
};

View File

@@ -4,8 +4,8 @@ import { Pannel } from "dispatch/_components/pannel/Pannel";
import { usePannelStore } from "_store/pannelStore";
import { cn } from "helpers/cn";
import dynamic from "next/dynamic";
import { Chat } from "./_components/left/Chat";
import { Report } from "./_components/left/Report";
import { Chat } from "../_components/left/Chat";
import { Report } from "../_components/left/Report";
const Map = dynamic(() => import("./_components/map/Map"), { ssr: false });
const DispatchPage = () => {

View File

@@ -1,5 +1,6 @@
import { pilotSocket } from "pilot/socket";
import { io } from "socket.io-client";
export const socket = io(process.env.NEXT_PUBLIC_DISPATCH_SERVER_URL, {
export const dispatchSocket = io(process.env.NEXT_PUBLIC_DISPATCH_SERVER_URL, {
autoConnect: false,
});