submission successful on AppWrite

This commit is contained in:
ATUL GUNJAL 2025-04-09 09:14:42 +05:30
parent cf13141cb2
commit abf12c8f68
19 changed files with 297 additions and 217 deletions

10
package-lock.json generated
View File

@ -10,6 +10,7 @@
"dependencies": {
"@tailwindcss/postcss": "^4.1.3",
"appwrite": "^17.0.1",
"lucide-react": "^0.487.0",
"next": "15.2.4",
"postcss": "^8.5.3",
"react": "^19.0.0",
@ -4158,6 +4159,15 @@
"loose-envify": "cli.js"
}
},
"node_modules/lucide-react": {
"version": "0.487.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.487.0.tgz",
"integrity": "sha512-aKqhOQ+YmFnwq8dWgGjOuLc8V1R9/c/yOd+zDY4+ohsR2Jo05lSGc3WsstYPIzcTpeosN7LoCkLReUUITvaIvw==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",

View File

@ -11,6 +11,7 @@
"dependencies": {
"@tailwindcss/postcss": "^4.1.3",
"appwrite": "^17.0.1",
"lucide-react": "^0.487.0",
"next": "15.2.4",
"postcss": "^8.5.3",
"react": "^19.0.0",

View File

@ -1,16 +0,0 @@
'use client';
import Sidebar from "./components/Sidebar";
import Navbar from "./components/Navbar";
export default function ClientLayout({ children }) {
return (
<div className="flex h-screen">
<Sidebar />
<div className="flex-1 flex flex-col">
<Navbar />
<main className="p-4 overflow-y-auto">{children}</main>
</div>
</div>
);
}

View File

@ -38,6 +38,7 @@ export default function MemberList() {
<th className="p-2 text-left">Name</th>
<th className="p-2">Phone</th>
<th className="p-2">Join Date</th>
<th className="p-2">Role</th>
</tr>
</thead>
<tbody>

View File

@ -1,24 +1,36 @@
'use client';
import { account } from "../lib/appwrite";
import { useRouter } from 'next/navigation';
import { LogOut } from 'lucide-react';
export default function Navbar() {
const router = useRouter();
const handleLogout = async () => {
try {
await account.deleteSession('current');
router.push('/login');
} catch (error) {
console.error('Logout failed:', error);
}
};
return (
<nav className="bg-white shadow px-4 py-3 flex justify-between items-center">
<span className="font-bold text-lg">Company Portal</span>
<nav className="bg-white border-b border-gray-200 px-4 py-3 sm:px-6 lg:px-8">
<div className="flex justify-between items-center">
<div className="flex items-center">
<span className="font-semibold text-gray-800">Company Portal</span>
</div>
<div className="flex items-center space-x-4">
<button
onClick={handleLogout}
className="bg-red-500 text-white px-4 py-1 rounded hover:bg-red-600"
className="flex items-center space-x-1 text-red-600 hover:text-red-800 transition-colors"
>
Logout
<LogOut className="w-5 h-5" />
<span className="hidden sm:inline">Logout</span>
</button>
</div>
</div>
</nav>
);
}

View File

@ -3,20 +3,23 @@ import Link from 'next/link';
export default function Sidebar() {
return (
<aside className="w-64 bg-gray-800 text-white p-4 hidden md:block">
<aside className="w-64 border-r border-gray-200 h-screen bg-white-800 text-gray-700 p-4 hidden md:block">
<h2 className="text-xl font-bold mb-6">Dashboard</h2>
<ul className="space-y-4">
<li>
<Link href="/dashboard" className="hover:text-gray-300">Home</Link>
<Link href="/pages/dashboard" className="hover:text-blue-500">Home</Link>
</li>
<li>
<Link href="/dashboard/members" className="hover:text-gray-300">Members</Link>
<Link href="/pages/user" className="hover:text-blue-500">user</Link>
</li>
<li>
<Link href="/dashboard/assignments" className="hover:text-gray-300">Assignments</Link>
<Link href="/pages/admin/members" className="hover:text-blue-500">Members</Link>
</li>
<li>
<Link href="/dashboard/profile" className="hover:text-gray-300">My Profile</Link>
<Link href="/pages/assignments" className="hover:text-blue-500">Assignments</Link>
</li>
<li>
<Link href="/pages/user/profile" className="hover:text-blue-500">My Profile</Link>
</li>
</ul>
</aside>

View File

@ -1,5 +1,7 @@
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import Sidebar from "./components/Sidebar"
import Navbar from "./components/Navbar";
const geistSans = Geist({
variable: "--font-geist-sans",
@ -12,7 +14,7 @@ const geistMono = Geist_Mono({
});
export const metadata = {
title: "Appwrite + Next App",
title: "FSPL HrMate",
description: "Built with Next.js and Appwrite",
};
@ -20,7 +22,13 @@ export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable}`}>
{children}
<div className="flex">
<Sidebar />
<div className="flex-1">
<Navbar />
<main className="p-4">{children}</main>
</div>
</div>
</body>
</html>
);

View File

@ -1,50 +1,22 @@
'use client';
import { useState } from 'react';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { account } from "./lib/appwrite";
import { account } from './lib/appwrite';
export default function LoginPage() {
export default function Home() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [err, setErr] = useState('');
const handleLogin = async (e) => {
e.preventDefault();
useEffect(() => {
const checkSession = async () => {
try {
await account.createEmailPasswordSession(email, password);
router.push('/'); // Redirect to home
} catch (error) {
console.error('Login error:', error);
setErr('Invalid credentials');
await account.get(); // Check if session exists
router.replace('/pages/dashboard'); // Redirect if logged in
} catch {
router.replace('/login'); // Redirect to login if no session
}
};
checkSession();
}, []);
return (
<div className="flex items-center justify-center min-h-screen">
<form onSubmit={handleLogin} className="bg-white p-6 rounded shadow-md w-full max-w-sm">
<h2 className="text-xl font-semibold mb-4">Login</h2>
{err && <p className="text-red-500">{err}</p>}
<input
type="email"
placeholder="Email"
className="w-full mb-2 p-2 border rounded"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
className="w-full mb-4 p-2 border rounded"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button className="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded w-full">
Login
</button>
</form>
</div>
);
return null; // No content, just redirection
}

View File

@ -1,7 +1,7 @@
'use client';
import MemberForm from "../../components/MemberForm";
import MemberList from "../../components/MemberList";
import MemberForm from "../../../components/MemberForm";
import MemberList from "../../../components/MemberList";
export default function AdminMembersPage() {
return (

View File

@ -2,7 +2,7 @@
import { useEffect, useState } from "react";
import Link from "next/link";
import { databases } from "../lib/appwrite";
import { databases } from "../../lib/appwrite";
const DB_ID = process.env.NEXT_PUBLIC_APPWRITE_DB_ID;
const MEMBERS_COLLECTION_ID = "members";
@ -56,14 +56,14 @@ export default function AdminDashboard() {
{/* Navigation Buttons */}
<div className="space-y-4">
<Link
href="/admin/members"
href="/pages/admin/members"
className="block bg-blue-600 hover:bg-blue-700 text-white font-semibold px-4 py-2 rounded"
>
Add or View Members
</Link>
<Link
href="/assignments"
href="/pages/assignments"
className="block bg-green-600 hover:bg-green-700 text-white font-semibold px-4 py-2 rounded"
>
📋 Manage Assignments

View File

@ -1,22 +1,22 @@
// app/assignments/page.js
"use client";
import { useEffect, useState } from "react";
import { databases } from "../lib/appwrite"; // Appwrite SDK
import { databases, account } from "../../lib/appwrite";
import { ID } from "appwrite";
export default function AssignmentsPage() {
const [assignments, setAssignments] = useState([]);
const [submissionLinks, setSubmissionLinks] = useState({});
const [userId, setUserId] = useState(""); // You might fetch this from your auth context/session
const [userId, setUserId] = useState(null);
const [loadingUser, setLoadingUser] = useState(true); // 🟡 Loading state
// Fetch assignments and user on mount
useEffect(() => {
// Fetch assignments from Appwrite
const fetchAssignments = async () => {
try {
const response = await databases.listDocuments(
"your_database_id",
"assignments_collection_id"
"67e1452b00016444b37f",
"67f0f285001a1614b4e8"
);
setAssignments(response.documents);
} catch (error) {
@ -24,28 +24,21 @@ export default function AssignmentsPage() {
}
};
fetchAssignments();
}, []);
const handleSubmit = async (assignmentId) => {
const fetchUser = async () => {
try {
await databases.createDocument(
"67e1452b00016444b37f",
"67f0f285001a1614b4e8",
ID.unique(),
{
assignmentId,
userId,
submissionLink: submissionLinks[assignmentId],
}
);
alert("Submitted!");
const user = await account.get();
setUserId(user.$id);
} catch (error) {
console.error("Submission failed:", error);
console.error("User not logged in:", error);
} finally {
setLoadingUser(false); // ✅ Done loading
}
};
fetchAssignments();
fetchUser();
}, []);
const handleInputChange = (assignmentId, value) => {
setSubmissionLinks({
...submissionLinks,
@ -53,6 +46,40 @@ export default function AssignmentsPage() {
});
};
const handleSubmit = async (assignmentId) => {
if (!userId) {
alert("User not logged in. Cannot submit.");
return;
}
const submissionLink = submissionLinks[assignmentId];
if (!submissionLink) {
alert("Submission link is empty.");
return;
}
try {
await databases.createDocument(
"67e1452b00016444b37f",
"67f5ea0a000393d31806", // ✅ Replace with correct ID
ID.unique(),
{
assignmentId,
userId,
submissionLink,
}
);
alert("Submitted!");
} catch (error) {
console.error("Submission failed:", error);
alert("Submission failed: " + error.message);
}
};
if (loadingUser) {
return <div>Loading...</div>; // Optional loading indicator
}
return (
<div>
<h1 className="text-2xl font-bold mb-4">Assignments</h1>
@ -81,6 +108,7 @@ export default function AssignmentsPage() {
<button
onClick={() => handleSubmit(assignment.$id)}
className="mt-2 bg-blue-600 text-white px-4 py-1 rounded"
disabled={!submissionLinks[assignment.$id]}
>
Submit
</button>

View File

@ -2,6 +2,8 @@
import { useEffect, useState } from 'react';
import { account } from"../../lib/appwrite";
import { useRouter } from 'next/navigation';
import Sidebar from '@/app/components/Sidebar';
import Navbar from '@/app/components/Navbar';
export default function DashboardPage() {
const router = useRouter();
@ -22,9 +24,11 @@ export default function DashboardPage() {
if (!user) return <p className="text-center mt-10">Checking auth...</p>;
return (
<div className="p-6">
<div className="flex">
<h1 className="text-2xl font-bold mb-4">Welcome, {user.name || user.email} 👋</h1>
<p>This is your dashboard.</p>
</div>
);
}

View File

@ -1,7 +1,7 @@
'use client';
import { useEffect, useState } from "react";
import { getCurrentUserWithRole } from "../utils/auth";
import { getCurrentUserWithRole } from "../../utils/auth";
export default function UserDashboard() {
const [user, setUser] = useState(null);

View File

@ -0,0 +1,136 @@
'use client';
import { useEffect, useState } from "react";
import { getCurrentUserWithRole } from "../../../utils/auth";
import { databases, databaseId, membersCollectionId, Query } from "../../../lib/appwrite";
import { useRouter } from "next/navigation";
export default function UserProfilePage() {
const router = useRouter();
const [profile, setProfile] = useState(null);
const [form, setForm] = useState({ name: '', phone: '' });
const [docId, setDocId] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchProfile() {
try {
setLoading(true);
setError(null);
const user = await getCurrentUserWithRole();
console.log("User data:", user);
if (!user) {
throw new Error("Please login to access this page");
}
// Use the same DB ID as in your auth.js
const dbId = "67e1452b00016444b37f";
const collectionId = "67f0f1200006897dc192";
const res = await databases.listDocuments(
dbId,
collectionId,
[Query.equal('userId', user.$id)]
);
console.log("Profile data:", res);
if (res.documents.length === 0) {
throw new Error("No profile found for this user");
}
const data = res.documents[0];
setDocId(data.$id);
setProfile(data);
setForm({
name: data.name || user.name || '',
phone: data.phone || ''
});
} catch (err) {
console.error("Profile fetch error:", err);
setError(err.message);
if (err.message.includes("authenticated") || err.message.includes("login")) {
router.push('/login');
}
} finally {
setLoading(false);
}
}
fetchProfile();
}, [router]);
const handleChange = (e) => {
setForm({
...form,
[e.target.name]: e.target.value
});
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
if (!docId) throw new Error("No profile document found");
// Use the same DB ID as above
const dbId = "67e1452b00016444b37f";
const collectionId = "67f0f1200006897dc192";
await databases.updateDocument(
dbId,
collectionId,
docId,
form
);
alert("Profile updated successfully!");
} catch (err) {
console.error("Update error:", err);
alert(err.message || "Failed to update profile");
}
};
if (loading) return <div className="p-6">Loading profile...</div>;
if (error) return <div className="p-6 text-red-500">{error}</div>;
return (
<div className="max-w-md mx-auto p-4">
<form onSubmit={handleSubmit} className="bg-white rounded-lg shadow-md p-6 space-y-4">
<h2 className="text-2xl font-bold text-gray-800">Your Profile</h2>
<div className="space-y-2">
<label className="block text-sm font-medium text-gray-700">Name</label>
<input
type="text"
name="name"
value={form.name}
onChange={handleChange}
className="w-full px-3 py-2 border rounded-md"
required
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-medium text-gray-700">Phone</label>
<input
type="tel"
name="phone"
value={form.phone}
onChange={handleChange}
className="w-full px-3 py-2 border rounded-md"
/>
</div>
<button
type="submit"
className="w-full bg-blue-600 text-white py-2 rounded-md hover:bg-blue-700"
>
Update Profile
</button>
</form>
</div>
);
}

View File

@ -1,16 +0,0 @@
// app/user/layout.js
import React from 'react';
import Navbar from "../components/Navbar"; // Adjust path if needed
import Sidebar from "../components/Sidebar"; // Adjust path if needed
export default function UserLayout({ children }) {
return (
<div className="flex">
<Sidebar />
<div className="flex-1">
<Navbar />
<main className="p-4">{children}</main>
</div>
</div>
);
}

View File

@ -1,67 +0,0 @@
'use client';
import { useEffect, useState } from "react";
import { getCurrentUser } from "../../utils/auth";
import { databases } from "../../lib/appwrite";
export default function UserProfilePage() {
const [profile, setProfile] = useState(null);
const [form, setForm] = useState(null);
const [docId, setDocId] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchProfile() {
const user = await getCurrentUser();
const res = await databases.listDocuments(
process.env.NEXT_PUBLIC_DB_ID,
process.env.NEXT_PUBLIC_MEMBERS_COLLECTION_ID,
[`query.equal("userId", ["${user.$id}"])`]
);
const data = res.documents[0];
setDocId(data.$id);
setProfile(data);
setForm({ name: data.name, phone: data.phone });
setLoading(false);
}
fetchProfile();
}, []);
const handleChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });
const handleSubmit = async (e) => {
e.preventDefault();
await databases.updateDocument(
process.env.NEXT_PUBLIC_DB_ID,
process.env.NEXT_PUBLIC_MEMBERS_COLLECTION_ID,
docId,
form
);
alert("Profile updated!");
};
if (loading) return <p>Loading...</p>;
return (
<form onSubmit={handleSubmit} className="p-6 bg-white rounded shadow space-y-4">
<h2 className="text-xl font-bold">Your Profile</h2>
<input
type="text"
name="name"
value={form.name}
onChange={handleChange}
className="input"
/>
<input
type="text"
name="phone"
value={form.phone}
onChange={handleChange}
className="input"
/>
<button type="submit" className="btn-primary">Update</button>
</form>
);
}

View File

@ -1,7 +1,7 @@
import { Client, Account, Databases, Query } from "appwrite";
const client = new Client()
.setEndpoint("https://cloud.appwrite.io/v1") // Update with your Appwrite endpoint
.setEndpoint("https://cloud.appwrite.io/v1")
.setProject("67e1445400053dca1d9b");
const account = new Account(client);
@ -11,6 +11,10 @@ export async function getCurrentUserWithRole() {
try {
const user = await account.get();
if (!user || !user.$id) {
throw new Error("User not authenticated");
}
const dbId = "67e1452b00016444b37f";
const collectionId = "67f0f1200006897dc192";
@ -18,18 +22,18 @@ export async function getCurrentUserWithRole() {
Query.equal("userId", user.$id),
]);
console.log("Query result:", response); // 🔍 Check this in console
const userDoc = response.documents[0];
return {
$id: user.$id, // Make sure to include this
name: user.name,
email: user.email,
role: userDoc?.role || "unknown",
// Include the document ID if needed
docId: userDoc?.$id
};
} catch (error) {
console.error("Error fetching user with role:", error);
return null;
throw error; // Throw instead of returning null
}
}
}