Initial commit

This commit is contained in:
2025-06-22 00:01:22 +03:00
parent fd70166cf6
commit 033b80bfad
153 changed files with 26874 additions and 1 deletions

19
hooks/use-mobile.tsx Normal file
View File

@@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

194
hooks/use-toast.ts Normal file
View File

@@ -0,0 +1,194 @@
"use client"
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

View File

@@ -0,0 +1,75 @@
"use client"
import { useEffect, useState, useRef } from "react"
interface DepartmentUpdateData {
stats?: any
users?: any[]
field?: string
department?: string
}
export function useDepartmentRealTimeUpdates(adminId: string, onUpdate?: (data: DepartmentUpdateData) => void) {
const [isConnected, setIsConnected] = useState(false)
const intervalRef = useRef<NodeJS.Timeout>()
const lastDataRef = useRef<string>("")
const fetchDepartmentUpdates = async () => {
try {
// Fetch department data in parallel
const [statsRes, usersRes] = await Promise.all([
fetch("/api/admin/department-stats", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ adminId }),
}),
fetch("/api/admin/department-users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ adminId }),
}),
])
const [statsData, usersData] = await Promise.all([statsRes.json(), usersRes.json()])
const newData = {
stats: statsData,
users: usersData.users,
field: usersData.field,
department: usersData.department,
}
const newDataString = JSON.stringify(newData)
// Only trigger update if data actually changed
if (newDataString !== lastDataRef.current) {
lastDataRef.current = newDataString
if (onUpdate) {
onUpdate(newData)
}
}
setIsConnected(true)
} catch (err) {
console.error("Error fetching department updates:", err)
setIsConnected(false)
}
}
useEffect(() => {
if (!adminId) return
// Initial fetch
fetchDepartmentUpdates()
// Set up polling every 2 seconds
intervalRef.current = setInterval(fetchDepartmentUpdates, 2000)
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
}
}, [adminId])
return { isConnected, refetch: fetchDepartmentUpdates }
}

View File

@@ -0,0 +1,73 @@
"use client"
import { useEffect, useState, useRef } from "react"
interface FieldUpdateData {
stats?: any
users?: any[]
field?: string
}
export function useFieldRealTimeUpdates(adminId: string, onUpdate?: (data: FieldUpdateData) => void) {
const [isConnected, setIsConnected] = useState(false)
const intervalRef = useRef<NodeJS.Timeout>()
const lastDataRef = useRef<string>("")
const fetchFieldUpdates = async () => {
try {
// Fetch field data in parallel
const [statsRes, usersRes] = await Promise.all([
fetch("/api/admin/field-stats", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ adminId }),
}),
fetch("/api/admin/field-users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ adminId }),
}),
])
const [statsData, usersData] = await Promise.all([statsRes.json(), usersRes.json()])
const newData = {
stats: statsData,
users: usersData.users,
field: usersData.field,
}
const newDataString = JSON.stringify(newData)
// Only trigger update if data actually changed
if (newDataString !== lastDataRef.current) {
lastDataRef.current = newDataString
if (onUpdate) {
onUpdate(newData)
}
}
setIsConnected(true)
} catch (err) {
console.error("Error fetching field updates:", err)
setIsConnected(false)
}
}
useEffect(() => {
if (!adminId) return
// Initial fetch
fetchFieldUpdates()
// Set up polling every 2 seconds
intervalRef.current = setInterval(fetchFieldUpdates, 2000)
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
}
}, [adminId])
return { isConnected, refetch: fetchFieldUpdates }
}

View File

@@ -0,0 +1,60 @@
"use client"
import { useEffect, useState, useRef } from "react"
interface UpdateData {
stats?: any
users?: any[]
lastReset?: any
}
export function useRealTimeUpdates(onUpdate?: (data: UpdateData) => void) {
const [isConnected, setIsConnected] = useState(false)
const intervalRef = useRef<NodeJS.Timeout>()
const lastDataRef = useRef<string>("")
const fetchUpdates = async () => {
try {
// Fetch all data in parallel
const [statsRes, usersRes, resetRes] = await Promise.all([
fetch("/api/admin/stats"),
fetch("/api/admin/users"),
fetch("/api/admin/last-reset"),
])
const [stats, users, lastReset] = await Promise.all([statsRes.json(), usersRes.json(), resetRes.json()])
const newData = { stats, users, lastReset }
const newDataString = JSON.stringify(newData)
// Only trigger update if data actually changed
if (newDataString !== lastDataRef.current) {
lastDataRef.current = newDataString
if (onUpdate) {
onUpdate(newData)
}
}
setIsConnected(true)
} catch (err) {
console.error("Error fetching updates:", err)
setIsConnected(false)
}
}
useEffect(() => {
// Initial fetch
fetchUpdates()
// Set up polling every 2 seconds
intervalRef.current = setInterval(fetchUpdates, 2000)
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
}
}, [])
return { isConnected, refetch: fetchUpdates }
}

View File

@@ -0,0 +1,46 @@
"use client"
import { useEffect, useState } from "react"
interface SSEMessage {
type: string
data?: any
timestamp?: string
}
export function useServerSentEvents(onMessage?: (message: SSEMessage) => void) {
const [isConnected, setIsConnected] = useState(false)
const [lastMessage, setLastMessage] = useState<SSEMessage | null>(null)
useEffect(() => {
const eventSource = new EventSource("/api/admin/events")
eventSource.onopen = () => {
console.log("SSE connected to shelter.ruff.co.il")
setIsConnected(true)
}
eventSource.onmessage = (event) => {
try {
const message: SSEMessage = JSON.parse(event.data)
setLastMessage(message)
if (onMessage && message.type !== "ping") {
onMessage(message)
}
} catch (err) {
console.error("Error parsing SSE message:", err)
}
}
eventSource.onerror = () => {
console.log("SSE connection error")
setIsConnected(false)
}
return () => {
eventSource.close()
}
}, [onMessage])
return { isConnected, lastMessage }
}

View File

@@ -0,0 +1,77 @@
"use client"
import { useEffect, useState, useRef } from "react"
interface TeamUpdateData {
stats?: any
users?: any[]
field?: string
department?: string
team?: string
}
export function useTeamRealTimeUpdates(adminId: string, onUpdate?: (data: TeamUpdateData) => void) {
const [isConnected, setIsConnected] = useState(false)
const intervalRef = useRef<NodeJS.Timeout>()
const lastDataRef = useRef<string>("")
const fetchTeamUpdates = async () => {
try {
// Fetch team data in parallel
const [statsRes, usersRes] = await Promise.all([
fetch("/api/admin/team-stats", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ adminId }),
}),
fetch("/api/admin/team-users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ adminId }),
}),
])
const [statsData, usersData] = await Promise.all([statsRes.json(), usersRes.json()])
const newData = {
stats: statsData,
users: usersData.users,
field: usersData.field,
department: usersData.department,
team: usersData.team,
}
const newDataString = JSON.stringify(newData)
// Only trigger update if data actually changed
if (newDataString !== lastDataRef.current) {
lastDataRef.current = newDataString
if (onUpdate) {
onUpdate(newData)
}
}
setIsConnected(true)
} catch (err) {
console.error("Error fetching team updates:", err)
setIsConnected(false)
}
}
useEffect(() => {
if (!adminId) return
// Initial fetch
fetchTeamUpdates()
// Set up polling every 2 seconds
intervalRef.current = setInterval(fetchTeamUpdates, 2000)
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
}
}, [adminId])
return { isConnected, refetch: fetchTeamUpdates }
}

90
hooks/useWebSocket.ts Normal file
View File

@@ -0,0 +1,90 @@
"use client"
import { useEffect, useRef, useState } from "react"
interface WebSocketMessage {
type: string
data?: any
timestamp?: string
}
export function useWebSocket(onMessage?: (message: WebSocketMessage) => void) {
const [isConnected, setIsConnected] = useState(false)
const [lastMessage, setLastMessage] = useState<WebSocketMessage | null>(null)
const ws = useRef<WebSocket | null>(null)
const reconnectTimeoutRef = useRef<NodeJS.Timeout>()
const reconnectAttempts = useRef(0)
const maxReconnectAttempts = 5
const connect = () => {
try {
// Use WSS for your HTTPS domain
const wsUrl = "wss://shelter.ruff.co.il/api/websocket"
ws.current = new WebSocket(wsUrl)
ws.current.onopen = () => {
console.log("WebSocket connected to shelter.ruff.co.il")
setIsConnected(true)
reconnectAttempts.current = 0
// Send ping to keep connection alive
const pingInterval = setInterval(() => {
if (ws.current?.readyState === WebSocket.OPEN) {
ws.current.send(JSON.stringify({ type: "ping" }))
} else {
clearInterval(pingInterval)
}
}, 30000)
}
ws.current.onmessage = (event) => {
try {
const message: WebSocketMessage = JSON.parse(event.data)
setLastMessage(message)
if (onMessage) {
onMessage(message)
}
} catch (err) {
console.error("Error parsing WebSocket message:", err)
}
}
ws.current.onclose = () => {
console.log("WebSocket disconnected")
setIsConnected(false)
// Attempt to reconnect
if (reconnectAttempts.current < maxReconnectAttempts) {
reconnectAttempts.current++
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.current), 30000)
console.log(`Attempting to reconnect in ${delay}ms (attempt ${reconnectAttempts.current})`)
reconnectTimeoutRef.current = setTimeout(() => {
connect()
}, delay)
}
}
ws.current.onerror = (error) => {
console.error("WebSocket error:", error)
}
} catch (err) {
console.error("Error creating WebSocket connection:", err)
}
}
useEffect(() => {
connect()
return () => {
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current)
}
if (ws.current) {
ws.current.close()
}
}
}, [])
return { isConnected, lastMessage }
}