diff --git a/src/app/api/get_employees.ts b/src/app/api/get_employees.ts new file mode 100644 index 0000000..882ff44 --- /dev/null +++ b/src/app/api/get_employees.ts @@ -0,0 +1,18 @@ +"use server"; +import type { NextApiRequest, NextApiResponse } from 'next'; +import { getEmployees } from '~/server/functions'; + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + if (req.method === 'GET') { + try { + const employees = await getEmployees(); + res.status(200).json(employees); + } catch (error) { + console.error('Error fetching employees:', error); + res.status(500).json({ message: 'Internal server error' }); + } + } else { + res.setHeader('Allow', ['GET']); + res.status(405).json({ message: `Method ${req.method} Not Allowed` }); + } +} diff --git a/src/app/api/update_status.ts b/src/app/api/update_status.ts new file mode 100644 index 0000000..f8654ac --- /dev/null +++ b/src/app/api/update_status.ts @@ -0,0 +1,29 @@ +"use server"; +import type { NextApiRequest, NextApiResponse } from 'next'; +import { updateEmployeeStatus } from '~/server/functions'; + +type UpdateStatusBody = { + employeeIds: number[]; + newStatus: string; +}; + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + if (req.method === 'POST') { + const { employeeIds, newStatus } = req.body as UpdateStatusBody; + + if (!Array.isArray(employeeIds) || typeof newStatus !== 'string') { + return res.status(400).json({ message: 'Invalid input' }); + } + + try { + await updateEmployeeStatus(employeeIds, newStatus); + return res.status(200).json({ message: 'Status updated successfully' }); + } catch (error) { + console.error('Error updating status:', error); + return res.status(500).json({ message: 'Internal server error' }); + } + } else { + res.setHeader('Allow', ['POST']); + return res.status(405).json({ message: `Method ${req.method} Not Allowed` }); + } +} diff --git a/src/components/ui/Table.tsx b/src/components/ui/Table.tsx new file mode 100644 index 0000000..76f3808 --- /dev/null +++ b/src/components/ui/Table.tsx @@ -0,0 +1,121 @@ +'use client'; + +import { useState, useEffect } from 'react'; + +// Define the Employee interface to match data fetched on the server +interface Employee { + id: number; + name: string; + status: string; + updatedAt: Date; +} + +export default function Table({ employees }: { employees: Employee[] }) { + const [selectedIds, setSelectedIds] = useState([]); + const [status, setStatus] = useState(''); + const [employeeData, setEmployeeData] = useState(employees); + + useEffect(() => { + // Refresh employee data if needed after state updates + setEmployeeData(employees); + }, [employees]); + + const handleCheckboxChange = (id: number) => { + setSelectedIds((prevSelected) => + prevSelected.includes(id) + ? prevSelected.filter((prevId) => prevId !== id) + : [...prevSelected, id] + ); + }; + + const handleStatusChange = (e: React.ChangeEvent) => { + setStatus(e.target.value); + }; + + const handleSubmit = async () => { + if (selectedIds.length > 0 && status.trim() !== '') { + await fetch('/api/update_status', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${process.env.API_KEY}` + }, + body: JSON.stringify({ employeeIds: selectedIds, newStatus: status }), + }); + // Optionally refresh data on the client-side after update + const updatedEmployees = await fetchEmployees(); + setEmployeeData(updatedEmployees); + setSelectedIds([]); + setStatus(''); + } + }; + + const fetchEmployees = async (): Promise => { + const res = await fetch('/api/get_employees', { + method: 'GET', + headers: { + 'Authorization': `Bearer ${process.env.API_KEY}` + } + }); + return res.json() as Promise; + }; + + const formatTime = (timestamp: Date) => { + const date = new Date(timestamp); + const time = date.toLocaleTimeString('en-US', { + hour: 'numeric', + minute: 'numeric', + }); + const day = date.getDate(); + const month = date.toLocaleString('default', { month: 'long' }); + return `${time} - ${month} ${day}`; + }; + + return ( +
+ + + + + + + + + + {employeeData.map((employee) => ( + + + + + + + ))} + +
+ NameStatusUpdated At
+ handleCheckboxChange(employee.id)} + /> + {employee.name}{employee.status}{formatTime(employee.updatedAt)}
+
+ + +
+
+ ); +} diff --git a/src/components/ui/Techs_Table.tsx b/src/components/ui/Techs_Table.tsx index 69da0cb..bcdc8b0 100644 --- a/src/components/ui/Techs_Table.tsx +++ b/src/components/ui/Techs_Table.tsx @@ -1,67 +1,70 @@ //import { auth } from "~/auth"; import { getEmployees } from "~/server/functions"; +import Table from "~/components/ui/Table"; -export const dynamic = "force-dynamic"; +//export const dynamic = "force-dynamic"; export default async function Techs_Table() { const employees = await getEmployees(); + return ; +}; - const formatTime = (timestamp: Date) => { - const date = new Date(timestamp); - const time = date.toLocaleTimeString("en-US", - {hour: "numeric", minute: "numeric",}); - const day = date.getDate(); - const month = date.toLocaleString("default", { month: "long" }); - return `${time} - ${month} ${day}`; - } + //const formatTime = (timestamp: Date) => { + //const date = new Date(timestamp); + //const time = date.toLocaleTimeString("en-US", + //{hour: "numeric", minute: "numeric",}); + //const day = date.getDate(); + //const month = date.toLocaleString("default", { month: "long" }); + //return `${time} - ${month} ${day}`; + //} //const session = await auth(); //const users_name = session?.user?.name; - return ( -
-
- - - - - - - - - {employees.map((employee) => ( - - - - - - - ))} - -
- - Name - - Status - - Updated At -
- - {employee.name}{employee.status}{formatTime(employee.updatedAt)}
-
- - -
- - ); -}; + //return ( + //
+ // + // + // + // + // + // + // + // + // + //{employees.map((employee) => ( + // + // + // + // + // + // + //))} + // + //
+ // + //Name + // + //Status + // + //Updated At + //
+ // + //{employee.name}{employee.status}{formatTime(employee.updatedAt)}
+ //
+ // + // + //
+ //
+ //); +//}; diff --git a/src/server/functions.ts b/src/server/functions.ts index 82b79d2..89333d1 100644 --- a/src/server/functions.ts +++ b/src/server/functions.ts @@ -1,11 +1,33 @@ import "server-only"; import { db } from "~/server/db"; -//import * as schema from "~/server/db/schema"; +import { sql } from "drizzle-orm"; +// Function to Get Employees export const getEmployees = async () => { return await db.query.users.findMany({ - orderBy: (model, { desc }) => desc(model.id), + orderBy: (model, { asc }) => asc(model.id), }); }; +// Function to Update Employee Status using Raw SQL +export const updateEmployeeStatus = async (employeeIds: number[], newStatus: string) => { + try { + // Convert array of ids to a format suitable for SQL query (comma-separated string) + const idString = employeeIds.join(","); + // Prepare the raw SQL query with embedded variables + const query = ` + UPDATE users + SET status = '${newStatus}', updatedAt = '${new Date().toISOString()}' + WHERE id IN (${idString}) + `; + + // Execute the raw SQL query using the execute method + await db.execute(sql`${query}`); + + return { success: true }; + } catch (error) { + console.error("Error updating employee status:", error); + throw new Error("Failed to update status"); + } +};