feat: hackathon
This commit is contained in:
@@ -4,7 +4,13 @@
|
||||
"Bash(npx nx run-many:*)",
|
||||
"Bash(npm install:*)",
|
||||
"Bash(npm view:*)",
|
||||
"Bash(npx nx build landing)"
|
||||
"Bash(npx nx build landing)",
|
||||
"Bash(npm uninstall:*)",
|
||||
"Bash(dir:*)",
|
||||
"Bash(ren page.tsx page-original.tsx)",
|
||||
"Bash(ren:*)",
|
||||
"Bash(npx supabase:*)",
|
||||
"Bash(libs/service/src/types/supabase.ts)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
|
||||
VITE_SUPABASE_URL=https://your-project-id.supabase.co
|
||||
VITE_SUPABASE_ANON_KEY=your-anon-key-here
|
||||
@@ -64,3 +64,5 @@ storybook-static
|
||||
out
|
||||
.cursor/rules/nx-rules.mdc
|
||||
.github/instructions/nx.instructions.md
|
||||
|
||||
.env.local
|
||||
|
||||
@@ -7,6 +7,8 @@ export default [
|
||||
{
|
||||
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
rules: {
|
||||
'jsx-a11y/accessible-emoji': 'off',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { FC, ReactElement, useEffect, useState, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { supabase } from '@imphnen-frontend-service/service';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const CallbackPage: FC = (): ReactElement => {
|
||||
const navigate = useNavigate();
|
||||
const { setSession } = useAuthStore();
|
||||
const [isProcessing, setIsProcessing] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const hasRunRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handleCallback = async () => {
|
||||
if (hasRunRef.current) {
|
||||
console.log('[Callback] Already processed, skipping...');
|
||||
return;
|
||||
}
|
||||
hasRunRef.current = true;
|
||||
try {
|
||||
console.log('[Callback] Processing OAuth callback...');
|
||||
console.log('[Callback] Current URL:', globalThis.location.href);
|
||||
|
||||
// Supabase client is configured with detectSessionInUrl: true
|
||||
// This means Supabase automatically detects and processes OAuth tokens from the URL hash
|
||||
// We just need to wait a moment for it to complete, then check for the session
|
||||
|
||||
console.log('[Callback] Waiting for Supabase to process OAuth callback...');
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// Get the session that Supabase automatically created from the URL hash
|
||||
const { data: { session: sessionData }, error: sessionError } = await supabase.auth.getSession();
|
||||
|
||||
if (sessionError) {
|
||||
console.error('[Callback] Session error:', sessionError);
|
||||
throw new Error(sessionError.message || 'Failed to get session');
|
||||
}
|
||||
|
||||
if (!sessionData || !sessionData.user) {
|
||||
throw new Error('No session found after OAuth callback. Please try logging in again.');
|
||||
}
|
||||
|
||||
console.log('[Callback] Supabase session established:', {
|
||||
userId: sessionData.user.id,
|
||||
email: sessionData.user.email,
|
||||
});
|
||||
|
||||
// Create/update user in the users table (for foreign key constraints)
|
||||
console.log('[Callback] Creating/updating user record...');
|
||||
const { data: userData, error: upsertError } = await supabase
|
||||
.from('users')
|
||||
.upsert({
|
||||
id: sessionData.user.id,
|
||||
email: sessionData.user.email || '',
|
||||
fullname: sessionData.user.user_metadata?.full_name ||
|
||||
sessionData.user.user_metadata?.name ||
|
||||
sessionData.user.email?.split('@')[0] || '',
|
||||
avatar: sessionData.user.user_metadata?.avatar_url || '',
|
||||
is_active: true,
|
||||
updated_at: new Date().toISOString(),
|
||||
}, {
|
||||
onConflict: 'id',
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (upsertError) {
|
||||
console.warn('[Callback] Failed to create user record:', upsertError);
|
||||
// Don't throw - continue with login even if user record creation fails
|
||||
} else {
|
||||
console.log('[Callback] User record created/updated successfully');
|
||||
}
|
||||
|
||||
// Store user-friendly data in Zustand for UI purposes
|
||||
// Supabase now manages the actual auth session
|
||||
// Use data from database if available, otherwise use OAuth metadata
|
||||
const userRecord = userData || {
|
||||
id: sessionData.user.id,
|
||||
email: sessionData.user.email || '',
|
||||
fullname: sessionData.user.user_metadata?.full_name ||
|
||||
sessionData.user.user_metadata?.name ||
|
||||
sessionData.user.email?.split('@')[0] || '',
|
||||
avatar: sessionData.user.user_metadata?.avatar_url || '',
|
||||
phone_number: '',
|
||||
birthdate: '',
|
||||
gender: '',
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
setSession({
|
||||
token: {
|
||||
access_token: sessionData.access_token,
|
||||
refresh_token: sessionData.refresh_token || '',
|
||||
},
|
||||
user: {
|
||||
id: userRecord.id,
|
||||
email: userRecord.email,
|
||||
fullname: userRecord.fullname,
|
||||
phone_number: userRecord.phone_number || '',
|
||||
avatar: userRecord.avatar || '',
|
||||
birthdate: userRecord.birthdate || '',
|
||||
gender: userRecord.gender || '',
|
||||
is_active: userRecord.is_active,
|
||||
location: userRecord.location,
|
||||
bio: userRecord.bio,
|
||||
skills: userRecord.skills,
|
||||
role: {
|
||||
id: '',
|
||||
name: 'user',
|
||||
permissions: [],
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log('[Callback] Session stored successfully');
|
||||
toast.success('Login successful!');
|
||||
setIsProcessing(false);
|
||||
|
||||
// Check if user has completed onboarding (has location)
|
||||
// Use globalThis.location.replace for hard redirect to prevent history issues
|
||||
if (userRecord.location) {
|
||||
console.log('[Callback] User has completed onboarding, redirecting to dashboard...');
|
||||
globalThis.location.replace('/dashboard');
|
||||
} else {
|
||||
console.log('[Callback] User needs onboarding, redirecting...');
|
||||
globalThis.location.replace('/onboarding/user');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Callback] Error:', err);
|
||||
setError((err as Error).message);
|
||||
setIsProcessing(false);
|
||||
toast.error('An error occurred during login');
|
||||
|
||||
setTimeout(() => {
|
||||
navigate('/auth/login');
|
||||
}, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
handleCallback();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []); // Run only once on mount
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 px-4">
|
||||
<div className="bg-white w-full max-w-2xl p-8 rounded-2xl shadow-lg border border-red-200">
|
||||
<div className="text-center mb-6">
|
||||
<div className="text-red-500 text-5xl mb-4">⚠️</div>
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">
|
||||
GitHub Login Failed
|
||||
</h2>
|
||||
<p className="text-red-600 mb-4 whitespace-pre-line">{error}</p>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-600 text-sm mt-6 text-center">
|
||||
Redirecting to login page in 3 seconds...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex justify-center items-center min-h-screen bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
|
||||
<h2 className="text-xl font-semibold text-gray-900 mb-2">
|
||||
Completing login...
|
||||
</h2>
|
||||
<p className="text-gray-600">Please wait</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CallbackPage;
|
||||
@@ -0,0 +1,89 @@
|
||||
import { FC, ReactElement, useEffect, useState } from 'react';
|
||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useGitHubAuth } from '@imphnen-frontend-service/service';
|
||||
import { useSession } from '@imphnen-frontend-service/utils';
|
||||
import { GithubOutlined } from '@ant-design/icons';
|
||||
|
||||
const LoginPage: FC = (): ReactElement => {
|
||||
console.log('[LoginPage] Rendering...');
|
||||
|
||||
const navigate = useNavigate();
|
||||
const { signInWithGitHub } = useGitHubAuth();
|
||||
const [isGithubLoading, setIsGithubLoading] = useState(false);
|
||||
const { isAuthenticated } = useSession();
|
||||
|
||||
console.log('[LoginPage] isAuthenticated:', isAuthenticated);
|
||||
|
||||
useEffect(() => {
|
||||
console.log('[LoginPage] useEffect - isAuthenticated:', isAuthenticated);
|
||||
if (isAuthenticated) {
|
||||
console.log('[LoginPage] Redirecting to dashboard...');
|
||||
navigate('/dashboard');
|
||||
}
|
||||
}, [isAuthenticated, navigate]);
|
||||
|
||||
const handleGithubLogin = async () => {
|
||||
try {
|
||||
setIsGithubLoading(true);
|
||||
console.log('[Login] Initiating GitHub OAuth...');
|
||||
|
||||
const result = await signInWithGitHub();
|
||||
console.log('[Login] OAuth result:', result);
|
||||
|
||||
// Check if we got a redirect URL
|
||||
if (result?.url) {
|
||||
console.log('[Login] Redirecting to GitHub OAuth:', result.url);
|
||||
// Supabase should handle the redirect automatically
|
||||
// If we're still here after 2 seconds, manually redirect
|
||||
setTimeout(() => {
|
||||
if (result.url) {
|
||||
globalThis.location.href = result.url;
|
||||
}
|
||||
}, 2000);
|
||||
} else {
|
||||
console.error('[Login] No OAuth URL returned');
|
||||
setIsGithubLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Login] GitHub login failed:', error);
|
||||
setIsGithubLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 px-4">
|
||||
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-100">
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-3xl font-bold text-gray-900 mb-2">
|
||||
Welcome to Hackathon
|
||||
</h2>
|
||||
<p className="text-gray-600">
|
||||
Sign in with your GitHub account to join or create your hackathon team
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className="w-full gap-2 py-3"
|
||||
variant="secondary"
|
||||
onClick={handleGithubLogin}
|
||||
disabled={isGithubLoading}
|
||||
type="button"
|
||||
>
|
||||
<GithubOutlined className="text-xl" />
|
||||
<span className="font-semibold">
|
||||
{isGithubLoading ? 'Connecting...' : 'Sign in with GitHub'}
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-gray-500 text-sm">
|
||||
By signing in, you agree to our Terms of Service and Privacy Policy
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPage;
|
||||
@@ -0,0 +1,205 @@
|
||||
import { useState } from 'react';
|
||||
import { useGitHubAuth, useEmailAuth, supabase } from '@imphnen-frontend-service/service';
|
||||
import { GithubOutlined } from '@ant-design/icons';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function LoginPage() {
|
||||
console.log('[LoginPage] Rendering...');
|
||||
|
||||
const navigate = useNavigate();
|
||||
const { setSession } = useAuthStore();
|
||||
const { signInWithGitHub } = useGitHubAuth();
|
||||
const { signInWithEmail } = useEmailAuth();
|
||||
const [isGithubLoading, setIsGithubLoading] = useState(false);
|
||||
const [isEmailLoading, setIsEmailLoading] = useState(false);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleEmailLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!email || !password) {
|
||||
setError('Please enter both email and password');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsEmailLoading(true);
|
||||
console.log('[Login] Attempting email login...');
|
||||
|
||||
const result = await signInWithEmail(email, password);
|
||||
console.log('[Login] Email login successful:', result);
|
||||
|
||||
// Get user data from database
|
||||
const { data: userData } = await supabase
|
||||
.from('users')
|
||||
.select('*')
|
||||
.eq('id', result.user.id)
|
||||
.single();
|
||||
|
||||
// Store session in Zustand
|
||||
setSession({
|
||||
token: {
|
||||
access_token: result.session.access_token,
|
||||
refresh_token: result.session.refresh_token || '',
|
||||
},
|
||||
user: {
|
||||
id: result.user.id,
|
||||
email: result.user.email || '',
|
||||
fullname: userData?.fullname || result.user.user_metadata?.full_name || '',
|
||||
phone_number: userData?.phone_number || '',
|
||||
avatar: userData?.avatar || '',
|
||||
birthdate: userData?.birthdate || '',
|
||||
gender: userData?.gender || '',
|
||||
is_active: userData?.is_active || true,
|
||||
location: userData?.location,
|
||||
bio: userData?.bio,
|
||||
skills: userData?.skills,
|
||||
role: {
|
||||
id: '',
|
||||
name: 'user',
|
||||
permissions: [],
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
toast.success('Login successful!');
|
||||
|
||||
// Redirect based on onboarding status
|
||||
if (userData?.location) {
|
||||
navigate('/dashboard');
|
||||
} else {
|
||||
navigate('/onboarding/user');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Login] Email login failed:', err);
|
||||
setError((err as Error).message || 'Login failed');
|
||||
setIsEmailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGithubLogin = async () => {
|
||||
try {
|
||||
setIsGithubLoading(true);
|
||||
console.log('[Login] Initiating GitHub OAuth...');
|
||||
|
||||
const result = await signInWithGitHub();
|
||||
console.log('[Login] OAuth result:', result);
|
||||
|
||||
// Check if we got a redirect URL
|
||||
if (result?.url) {
|
||||
console.log('[Login] Redirecting to GitHub OAuth:', result.url);
|
||||
// Manually redirect immediately
|
||||
globalThis.location.href = result.url;
|
||||
} else {
|
||||
console.error('[Login] No OAuth URL returned');
|
||||
setIsGithubLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Login] GitHub login failed:', error);
|
||||
setIsGithubLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
|
||||
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200">
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-3xl font-bold text-gray-900 mb-2">
|
||||
Welcome Back
|
||||
</h2>
|
||||
<p className="text-gray-600">
|
||||
Sign in to join or create your hackathon team
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-3 bg-red-50 border border-red-200 rounded-lg">
|
||||
<p className="text-red-600 text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleEmailLogin} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="your@email.com"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{isEmailLoading ? 'Signing in...' : 'Sign in with Email'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="my-6 flex items-center">
|
||||
<div className="flex-1 border-t border-gray-300"></div>
|
||||
<span className="px-4 text-sm text-gray-500">OR</span>
|
||||
<div className="flex-1 border-t border-gray-300"></div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleGithubLogin}
|
||||
disabled={isGithubLoading}
|
||||
type="button"
|
||||
className="w-full py-3 flex items-center justify-center gap-2 bg-gray-100 border border-gray-300 rounded-lg font-semibold hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 disabled:bg-gray-100 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<GithubOutlined className="text-xl" />
|
||||
<span>
|
||||
{isGithubLoading ? 'Connecting...' : 'Sign in with GitHub'}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-gray-600 text-sm">
|
||||
Don't have an account?{' '}
|
||||
<a href="/auth/signup" className="text-primary-600 hover:text-primary-700 font-semibold">
|
||||
Sign up
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-gray-500 text-xs">
|
||||
By signing in, you agree to our Terms of Service and Privacy Policy
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import { useState } from 'react';
|
||||
import { useGitHubAuth, useEmailAuth, supabase } from '@imphnen-frontend-service/service';
|
||||
import { GithubOutlined } from '@ant-design/icons';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function SignupPage() {
|
||||
const navigate = useNavigate();
|
||||
const { setSession } = useAuthStore();
|
||||
const { signInWithGitHub } = useGitHubAuth();
|
||||
const { signUpWithEmail } = useEmailAuth();
|
||||
const [isGithubLoading, setIsGithubLoading] = useState(false);
|
||||
const [isEmailLoading, setIsEmailLoading] = useState(false);
|
||||
const [fullname, setFullname] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleEmailSignup = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
if (!fullname || !email || !password || !confirmPassword) {
|
||||
setError('Please fill in all fields');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
setError('Password must be at least 6 characters long');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsEmailLoading(true);
|
||||
console.log('[Signup] Attempting email signup...');
|
||||
|
||||
const result = await signUpWithEmail(email, password, fullname);
|
||||
console.log('[Signup] Email signup successful:', result);
|
||||
|
||||
if (!result.user) {
|
||||
throw new Error('Signup failed - no user returned');
|
||||
}
|
||||
|
||||
// Create user record in database
|
||||
const { error: upsertError } = await supabase
|
||||
.from('users')
|
||||
.upsert({
|
||||
id: result.user.id,
|
||||
email: result.user.email || '',
|
||||
fullname: fullname,
|
||||
is_active: true,
|
||||
updated_at: new Date().toISOString(),
|
||||
}, {
|
||||
onConflict: 'id',
|
||||
});
|
||||
|
||||
if (upsertError) {
|
||||
console.warn('[Signup] Failed to create user record:', upsertError);
|
||||
}
|
||||
|
||||
// If session is available (email confirmation disabled), store it
|
||||
if (result.session) {
|
||||
setSession({
|
||||
token: {
|
||||
access_token: result.session.access_token,
|
||||
refresh_token: result.session.refresh_token || '',
|
||||
},
|
||||
user: {
|
||||
id: result.user.id,
|
||||
email: result.user.email || '',
|
||||
fullname: fullname,
|
||||
phone_number: '',
|
||||
avatar: '',
|
||||
birthdate: '',
|
||||
gender: '',
|
||||
is_active: true,
|
||||
role: {
|
||||
id: '',
|
||||
name: 'user',
|
||||
permissions: [],
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
toast.success('Account created successfully!');
|
||||
navigate('/onboarding/user');
|
||||
} else {
|
||||
// Email confirmation is enabled
|
||||
toast.success('Account created! Please check your email to verify your account.');
|
||||
setTimeout(() => {
|
||||
navigate('/auth/login');
|
||||
}, 2000);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Signup] Email signup failed:', err);
|
||||
setError((err as Error).message || 'Signup failed');
|
||||
setIsEmailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGithubLogin = async () => {
|
||||
try {
|
||||
setIsGithubLoading(true);
|
||||
console.log('[Signup] Initiating GitHub OAuth...');
|
||||
|
||||
const result = await signInWithGitHub();
|
||||
console.log('[Signup] OAuth result:', result);
|
||||
|
||||
if (result?.url) {
|
||||
console.log('[Signup] Redirecting to GitHub OAuth:', result.url);
|
||||
globalThis.location.href = result.url;
|
||||
} else {
|
||||
console.error('[Signup] No OAuth URL returned');
|
||||
setIsGithubLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Signup] GitHub login failed:', error);
|
||||
setIsGithubLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
|
||||
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200">
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-3xl font-bold text-gray-900 mb-2">
|
||||
Create Account
|
||||
</h2>
|
||||
<p className="text-gray-600">
|
||||
Join the hackathon community
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-3 bg-red-50 border border-red-200 rounded-lg">
|
||||
<p className="text-red-600 text-sm">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleEmailSignup} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="fullname" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Full Name
|
||||
</label>
|
||||
<input
|
||||
id="fullname"
|
||||
type="text"
|
||||
value={fullname}
|
||||
onChange={(e) => setFullname(e.target.value)}
|
||||
placeholder="John Doe"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="your@email.com"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Confirm Password
|
||||
</label>
|
||||
<input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isEmailLoading}
|
||||
className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{isEmailLoading ? 'Creating account...' : 'Create Account'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="my-6 flex items-center">
|
||||
<div className="flex-1 border-t border-gray-300"></div>
|
||||
<span className="px-4 text-sm text-gray-500">OR</span>
|
||||
<div className="flex-1 border-t border-gray-300"></div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleGithubLogin}
|
||||
disabled={isGithubLoading}
|
||||
type="button"
|
||||
className="w-full py-3 flex items-center justify-center gap-2 bg-gray-100 border border-gray-300 rounded-lg font-semibold hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 disabled:bg-gray-100 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<GithubOutlined className="text-xl" />
|
||||
<span>
|
||||
{isGithubLoading ? 'Connecting...' : 'Sign up with GitHub'}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-gray-600 text-sm">
|
||||
Already have an account?{' '}
|
||||
<a href="/auth/login" className="text-primary-600 hover:text-primary-700 font-semibold">
|
||||
Sign in
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 text-center">
|
||||
<p className="text-gray-500 text-xs">
|
||||
By signing up, you agree to our Terms of Service and Privacy Policy
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import { FC, ReactElement } from 'react';
|
||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { useMyTeams, useMyInvitations, useRespondToInvitation, supabase } from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const DashboardPage: FC = (): ReactElement => {
|
||||
const navigate = useNavigate();
|
||||
const { session, clearSession } = useAuthStore();
|
||||
const { data: teamsData } = useMyTeams();
|
||||
const { data: invitationsData } = useMyInvitations();
|
||||
const { mutateAsync: respondToInvitation } = useRespondToInvitation();
|
||||
|
||||
const user = session?.user;
|
||||
const myTeams = teamsData?.data || [];
|
||||
const invitations = invitationsData?.data || [];
|
||||
|
||||
const handleAcceptInvitation = async (invitationId: string) => {
|
||||
try {
|
||||
await respondToInvitation({ invitationId, action: 'accept' });
|
||||
toast.success('Invitation accepted! You are now a team member.');
|
||||
} catch (error) {
|
||||
console.error('Failed to accept invitation:', error);
|
||||
toast.error('Failed to accept invitation');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRejectInvitation = async (invitationId: string) => {
|
||||
try {
|
||||
await respondToInvitation({ invitationId, action: 'reject' });
|
||||
toast.success('Invitation declined');
|
||||
} catch (error) {
|
||||
console.error('Failed to reject invitation:', error);
|
||||
toast.error('Failed to decline invitation');
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
// Clear Supabase session
|
||||
await supabase.auth.signOut();
|
||||
|
||||
// Clear Zustand store
|
||||
clearSession();
|
||||
|
||||
// Clear localStorage
|
||||
localStorage.clear();
|
||||
|
||||
toast.success('Logged out successfully');
|
||||
|
||||
// Redirect to login
|
||||
navigate('/auth/login');
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
// Even if there's an error, clear everything and redirect
|
||||
clearSession();
|
||||
localStorage.clear();
|
||||
navigate('/auth/login');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Header */}
|
||||
<div className="bg-white border-b">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">
|
||||
Welcome, {user?.fullname || 'User'}!
|
||||
</h1>
|
||||
<p className="text-gray-600 mt-1">
|
||||
{user?.location && `📍 ${user.location}`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center space-x-3">
|
||||
{user?.avatar && (
|
||||
<img
|
||||
src={user.avatar}
|
||||
alt="Profile"
|
||||
className="w-16 h-16 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
onClick={handleLogout}
|
||||
variant="secondary"
|
||||
className="bg-red-500 hover:bg-red-600 text-white"
|
||||
>
|
||||
Logout
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
{/* Team Invitations */}
|
||||
{invitations.length > 0 && (
|
||||
<div className="mb-8 bg-blue-50 border border-blue-200 rounded-lg p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">
|
||||
Team Invitations ({invitations.length})
|
||||
</h2>
|
||||
<div className="space-y-3">
|
||||
{invitations.map((invitation) => (
|
||||
<div key={invitation.id} className="bg-white p-4 rounded-lg shadow-sm flex items-center justify-between">
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">{invitation.team.name}</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
Invited by {invitation.inviter.fullname}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleAcceptInvitation(invitation.id)}
|
||||
>
|
||||
Accept
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => handleRejectInvitation(invitation.id)}
|
||||
>
|
||||
Decline
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* My Teams */}
|
||||
{myTeams.length > 0 ? (
|
||||
<div className="mb-8">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">My Team</h2>
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{myTeams.map((team) => (
|
||||
<Link
|
||||
key={team.id}
|
||||
to={`/teams/${team.id}`}
|
||||
className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow"
|
||||
>
|
||||
{team.banner && (
|
||||
<img
|
||||
src={team.banner}
|
||||
alt={team.name}
|
||||
className="w-full h-32 object-cover"
|
||||
/>
|
||||
)}
|
||||
<div className="p-6">
|
||||
<div className="flex items-center space-x-3 mb-3">
|
||||
{team.logo && (
|
||||
<img
|
||||
src={team.logo}
|
||||
alt={team.name}
|
||||
className="w-12 h-12 rounded-full object-cover"
|
||||
/>
|
||||
)}
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900">{team.name}</h3>
|
||||
<p className="text-sm text-gray-600">📍 {team.city}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-gray-600 text-sm line-clamp-2">
|
||||
{team.description}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* No Team - Show CTAs */
|
||||
<div className="bg-white rounded-lg shadow-md p-8">
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">
|
||||
You're not in a team yet
|
||||
</h2>
|
||||
<p className="text-gray-600">
|
||||
Join an existing team or create your own to get started
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-2 max-w-2xl mx-auto">
|
||||
<Link
|
||||
to="/teams/browse"
|
||||
className="bg-blue-600 text-white rounded-lg p-6 hover:bg-blue-700 transition-colors text-center"
|
||||
>
|
||||
<div className="text-4xl mb-3">🔍</div>
|
||||
<h3 className="text-xl font-bold mb-2">Browse Teams</h3>
|
||||
<p className="text-blue-100">
|
||||
Find and join existing teams looking for members
|
||||
</p>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/teams/create"
|
||||
className="bg-green-600 text-white rounded-lg p-6 hover:bg-green-700 transition-colors text-center"
|
||||
>
|
||||
<div className="text-4xl mb-3">➕</div>
|
||||
<h3 className="text-xl font-bold mb-2">Create Team</h3>
|
||||
<p className="text-green-100">
|
||||
Start your own team and invite members
|
||||
</p>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* User Profile Card */}
|
||||
<div className="mt-8 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl shadow-lg overflow-hidden">
|
||||
<div className="bg-gradient-to-r from-blue-600 to-indigo-600 h-24"></div>
|
||||
<div className="px-8 pb-8">
|
||||
<div className="flex items-start -mt-12 mb-6">
|
||||
{user?.avatar && (
|
||||
<img
|
||||
src={user.avatar}
|
||||
alt={user.fullname}
|
||||
className="w-24 h-24 rounded-full border-4 border-white shadow-lg object-cover"
|
||||
/>
|
||||
)}
|
||||
<div className="ml-6 mt-14">
|
||||
<h2 className="text-2xl font-bold text-gray-900">{user?.fullname}</h2>
|
||||
{user?.location ? (
|
||||
<p className="text-gray-600 flex items-center mt-1">
|
||||
<svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
|
||||
</svg>
|
||||
{user.location}
|
||||
</p>
|
||||
) : (
|
||||
<Link to="/onboarding/user" className="text-blue-600 hover:text-blue-700 text-sm mt-1 inline-block">
|
||||
Complete your profile →
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{user?.bio && (
|
||||
<div className="bg-white rounded-lg p-4 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-2">About</h3>
|
||||
<p className="text-gray-800 leading-relaxed">{user.bio}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-lg p-4 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-3">Contact</h3>
|
||||
<div className="flex items-center text-gray-700">
|
||||
<svg className="w-5 h-5 mr-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z" />
|
||||
<path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z" />
|
||||
</svg>
|
||||
<span className="text-gray-900">{user?.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{user?.skills && user.skills.length > 0 && (
|
||||
<div className="bg-white rounded-lg p-4 shadow-sm">
|
||||
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-3">Skills</h3>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{user.skills.map((skill: string) => (
|
||||
<span
|
||||
key={skill}
|
||||
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium shadow-sm hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
{skill}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DashboardPage;
|
||||
@@ -1,6 +1,127 @@
|
||||
import { Outlet, ScrollRestoration } from 'react-router-dom';
|
||||
import { Outlet, ScrollRestoration, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { supabase } from '@imphnen-frontend-service/service';
|
||||
|
||||
// Define onboarding routes
|
||||
const ONBOARDING_ROUTES = new Set(['/onboarding/user']);
|
||||
|
||||
export default function RootLayout() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const [isChecking, setIsChecking] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
const pathname = location.pathname;
|
||||
|
||||
console.log('[Layout] Checking auth for route:', pathname);
|
||||
|
||||
// Allow hackathon pages without checks
|
||||
if (pathname.startsWith('/hackathons')) {
|
||||
console.log('[Layout] Public route, allowing access');
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Allow auth callback without checks
|
||||
if (pathname === '/auth/callback') {
|
||||
console.log('[Layout] Auth callback, allowing access');
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check Supabase session
|
||||
const { data: { session }, error } = await supabase.auth.getSession();
|
||||
|
||||
if (error) {
|
||||
console.error('[Layout] Session error:', error);
|
||||
}
|
||||
|
||||
// Public auth pages (login, signup) - allow unauthenticated access
|
||||
const isPublicAuthPage = pathname === '/auth/login' || pathname === '/auth/signup';
|
||||
|
||||
if (isPublicAuthPage) {
|
||||
// If already authenticated, redirect to dashboard
|
||||
if (session) {
|
||||
console.log('[Layout] Already authenticated, redirecting to dashboard');
|
||||
navigate('/dashboard', { replace: true });
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
// Allow unauthenticated access
|
||||
console.log('[Layout] Public auth page, allowing access');
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Home page - redirect based on auth status
|
||||
if (pathname === '/') {
|
||||
if (session) {
|
||||
console.log('[Layout] Already authenticated, redirecting to dashboard');
|
||||
navigate('/dashboard', { replace: true });
|
||||
} else {
|
||||
console.log('[Layout] Not authenticated, redirecting to login');
|
||||
navigate('/auth/login', { replace: true });
|
||||
}
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Require authentication for all other routes
|
||||
if (!session) {
|
||||
console.log('[Layout] No session, redirecting to login');
|
||||
navigate('/auth/login', { replace: true });
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if user has completed onboarding (skip for onboarding routes)
|
||||
if (!ONBOARDING_ROUTES.has(pathname)) {
|
||||
try {
|
||||
const { data: userData, error: userError } = await supabase
|
||||
.from('users')
|
||||
.select('location')
|
||||
.eq('id', session.user.id)
|
||||
.single();
|
||||
|
||||
if (userError) {
|
||||
console.error('[Layout] Failed to fetch user data:', userError);
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const hasLocation = !!userData?.location;
|
||||
|
||||
if (!hasLocation) {
|
||||
console.log('[Layout] User needs onboarding, redirecting');
|
||||
navigate('/onboarding/user', { replace: true });
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Layout] Unexpected error checking onboarding:', error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[Layout] Auth check passed');
|
||||
setIsChecking(false);
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, [location.pathname, navigate]);
|
||||
|
||||
// Show loading state while checking auth
|
||||
if (isChecking) {
|
||||
return (
|
||||
<div className="flex justify-center items-center min-h-screen bg-gray-50">
|
||||
<div className="text-center">
|
||||
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
|
||||
<p className="text-gray-600">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Outlet />
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { FC, ReactElement, useState, useEffect } from 'react';
|
||||
import { ControlledInputField } from '@imphnen-frontend-service/ui/organisms';
|
||||
import { Button, Textarea } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { userOnboardingSchema, TUserOnboardingForm, useUpdateUserMe, useUploadAvatar } from '@imphnen-frontend-service/service';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useUserMe } from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
|
||||
const ROLE_OPTIONS = [
|
||||
'Frontend Developer',
|
||||
'Backend Developer',
|
||||
'Full Stack Developer',
|
||||
'DevOps Engineer',
|
||||
'UI/UX Designer',
|
||||
'Product Manager',
|
||||
'Data Scientist',
|
||||
'Mobile Developer',
|
||||
];
|
||||
|
||||
const INDONESIAN_CITIES = [
|
||||
'Jakarta', 'Surabaya', 'Bandung', 'Medan', 'Semarang',
|
||||
'Makassar', 'Palembang', 'Tangerang', 'Depok', 'Bekasi',
|
||||
'Yogyakarta', 'Malang', 'Bogor', 'Batam', 'Pekanbaru',
|
||||
];
|
||||
|
||||
const UserOnboardingPage: FC = (): ReactElement => {
|
||||
const navigate = useNavigate();
|
||||
const [avatarFile, setAvatarFile] = useState<File | null>(null);
|
||||
const [avatarPreview, setAvatarPreview] = useState<string>('');
|
||||
|
||||
const { data: userData } = useUserMe();
|
||||
const { mutateAsync: updateUser, isPending: isUpdating } = useUpdateUserMe();
|
||||
const { mutateAsync: uploadAvatar, isPending: isUploading } = useUploadAvatar();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
const form = useForm<TUserOnboardingForm>({
|
||||
resolver: zodResolver(userOnboardingSchema),
|
||||
mode: 'all',
|
||||
defaultValues: {
|
||||
fullname: session?.user?.fullname || userData?.data?.fullname || '',
|
||||
location: session?.user?.location || '',
|
||||
bio: session?.user?.bio || '',
|
||||
skills: session?.user?.skills || [],
|
||||
},
|
||||
});
|
||||
|
||||
// Set initial avatar preview from GitHub avatar if available
|
||||
useEffect(() => {
|
||||
if (session?.user?.avatar && !avatarPreview) {
|
||||
setAvatarPreview(session.user.avatar);
|
||||
}
|
||||
}, [session?.user?.avatar, avatarPreview]);
|
||||
|
||||
const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setAvatarFile(file);
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
setAvatarPreview(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
console.log('[Onboarding] Starting submission...', data);
|
||||
let avatarUrl = session?.user?.avatar || null;
|
||||
|
||||
// Upload avatar if a new file was selected
|
||||
if (avatarFile) {
|
||||
console.log('[Onboarding] Uploading avatar...');
|
||||
const uploadResult = await uploadAvatar(avatarFile);
|
||||
avatarUrl = uploadResult.data.url;
|
||||
console.log('[Onboarding] Avatar uploaded:', avatarUrl);
|
||||
}
|
||||
|
||||
// Update user in Supabase
|
||||
console.log('[Onboarding] Updating user in Supabase...');
|
||||
const result = await updateUser({
|
||||
fullname: data.fullname,
|
||||
avatar: avatarUrl,
|
||||
location: data.location,
|
||||
bio: data.bio,
|
||||
skills: data.skills,
|
||||
});
|
||||
console.log('[Onboarding] User updated successfully:', result);
|
||||
|
||||
// Wait a bit for the onSuccess handler to update localStorage
|
||||
// The updateUser mutation's onSuccess handler updates the Zustand store and localStorage
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
console.log('[Onboarding] Navigating to dashboard...');
|
||||
// Use window.location for a full page reload to ensure middleware sees updated localStorage
|
||||
globalThis.location.href = '/dashboard';
|
||||
} catch (error) {
|
||||
console.error('[Onboarding] Onboarding failed:', error);
|
||||
alert(`Onboarding failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col justify-center items-center min-h-screen bg-gray-50 px-4 py-8">
|
||||
<div className="bg-white w-full max-w-2xl p-8 rounded-xl shadow-lg">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">
|
||||
Complete Your Profile
|
||||
</h1>
|
||||
<p className="text-gray-600">
|
||||
Tell us more about yourself to get started
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={onSubmit} className="space-y-6">
|
||||
{/* Avatar Upload */}
|
||||
<div className="flex flex-col items-center space-y-4">
|
||||
<div className="relative">
|
||||
{avatarPreview ? (
|
||||
<img
|
||||
src={avatarPreview}
|
||||
alt="Avatar preview"
|
||||
className="w-32 h-32 rounded-full object-cover border-4 border-gray-200"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-32 h-32 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-400 text-4xl">👤</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="avatar" className="cursor-pointer">
|
||||
<span className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 inline-block">
|
||||
{avatarPreview ? 'Change Photo' : 'Upload Photo'}
|
||||
</span>
|
||||
<input
|
||||
id="avatar"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleAvatarChange}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-xs text-gray-500 mt-2 text-center">Optional, but highly recommended</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Full Name */}
|
||||
<ControlledInputField
|
||||
control={form.control}
|
||||
label="Full Name"
|
||||
placeholder="Enter your full name"
|
||||
name="fullname"
|
||||
/>
|
||||
|
||||
{/* City */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
City <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="location"
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<select
|
||||
{...field}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="">Select your city</option>
|
||||
{INDONESIAN_CITIES.map((city) => (
|
||||
<option key={city} value={city}>
|
||||
{city}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldState.error && (
|
||||
<p className="text-sm text-red-500 mt-1">{fieldState.error.message}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Role/Skills */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Role / Skills
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="skills"
|
||||
render={({ field }) => (
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{ROLE_OPTIONS.map((role) => (
|
||||
<label key={role} className="flex items-center space-x-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={field.value?.includes(role)}
|
||||
onChange={(e) => {
|
||||
const newValue = e.target.checked
|
||||
? [...(field.value || []), role]
|
||||
: (field.value || []).filter((v) => v !== role);
|
||||
field.onChange(newValue);
|
||||
}}
|
||||
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm">{role}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Bio */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Bio <span className="text-gray-400">(Optional)</span>
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="bio"
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<Textarea
|
||||
{...field}
|
||||
placeholder="Tell us about yourself..."
|
||||
rows={4}
|
||||
className="w-full"
|
||||
/>
|
||||
{fieldState.error && (
|
||||
<p className="text-sm text-red-500 mt-1">{fieldState.error.message}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className="w-full"
|
||||
type="submit"
|
||||
disabled={!form.formState.isValid || isUpdating || isUploading}
|
||||
>
|
||||
{isUpdating || isUploading ? 'Saving...' : 'Complete Setup'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserOnboardingPage;
|
||||
@@ -1,19 +1,759 @@
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useState } from 'react';
|
||||
|
||||
export default function HomePage() {
|
||||
const navigate = useNavigate();
|
||||
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
|
||||
const [openFaq, setOpenFaq] = useState<number | null>(0);
|
||||
|
||||
const faqs = [
|
||||
{
|
||||
question: 'Siapa yang bisa mengikuti hackathon ini?',
|
||||
answer:
|
||||
'Hackathon ini terbuka untuk mahasiswa, fresh graduate, dan profesional muda yang memiliki passion di bidang teknologi. Peserta dapat mendaftar secara tim.',
|
||||
},
|
||||
{
|
||||
question: 'Apakah ada biaya pendaftaran?',
|
||||
answer:
|
||||
'Tidak, hackathon ini gratis dan terbuka untuk semua peserta yang memenuhi kriteria.',
|
||||
},
|
||||
{
|
||||
question: 'Apa tema hackathon kali ini?',
|
||||
answer:
|
||||
'Tema hackathon kali ini adalah "Inovasi AI: Mendorong Usaha Lokal dengan AI Inklusif".',
|
||||
},
|
||||
{
|
||||
question: 'Bagaimana format pelaksanaannya?',
|
||||
answer:
|
||||
'Hackathon dilaksanakan secara online dengan berbagai tahap mulai dari pendaftaran, technical meeting, tahap penyisihan, hingga final.',
|
||||
},
|
||||
{
|
||||
question: 'Apa hadiah lombanya?',
|
||||
answer:
|
||||
'Total hadiah senilai Rp14.500.000 dengan juara 1 mendapat Rp6.000.000, juara 2 Rp4.000.000, juara 3 Rp2.500.000, dan juara kategori lainnya Rp2.000.000.',
|
||||
},
|
||||
{
|
||||
question: 'Apakah harus membentuk tim? Boleh solo?',
|
||||
answer:
|
||||
'Ya, peserta harus membentuk tim dengan maksimal 3 orang per tim.',
|
||||
},
|
||||
{
|
||||
question: 'Apakah boleh menggunakan AI (vibe coding)?',
|
||||
answer:
|
||||
'Ya, peserta diperbolehkan menggunakan AI tools untuk membantu development.',
|
||||
},
|
||||
{
|
||||
question: 'Apa project wajib di-deploy?',
|
||||
answer:
|
||||
'Ya, project harus di-deploy dan dapat diakses secara online untuk penilaian.',
|
||||
},
|
||||
{
|
||||
question: 'Apakah peserta mendapatkan sertifikat?',
|
||||
answer:
|
||||
'Ya, semua peserta yang menyelesaikan hackathon akan mendapatkan sertifikat.',
|
||||
},
|
||||
{
|
||||
question: 'Website error dan terjadi masalah?',
|
||||
answer:
|
||||
'Silakan hubungi kami melalui grup WA Hackathon atau email imphnen@gmail.com.',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center">
|
||||
<h1 className="text-4xl font-bold text-gray-900 mb-4">
|
||||
Hackathon App
|
||||
<div className="min-h-screen bg-white">
|
||||
{/* Navigation */}
|
||||
<nav className="flex items-center justify-between px-4 md:px-8 py-4 border-b border-gray-200 bg-white sticky top-0 z-50">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg md:text-xl font-bold">IMPHNEN</span>
|
||||
<span className="text-lg md:text-xl font-bold text-blue-600">
|
||||
Hackathon
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Desktop Menu */}
|
||||
<div className="hidden md:flex items-center gap-6 lg:gap-8">
|
||||
<a
|
||||
href="#timeline"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
Timeline
|
||||
</a>
|
||||
<a
|
||||
href="#hadiah"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
Hadiah
|
||||
</a>
|
||||
<a
|
||||
href="#faq"
|
||||
className="text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
FAQ
|
||||
</a>
|
||||
|
||||
<button
|
||||
onClick={() => navigate('/auth/login')}
|
||||
className="px-4 lg:px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm lg:text-base"
|
||||
>
|
||||
Daftar Sekarang
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Mobile Menu Button */}
|
||||
<button
|
||||
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
|
||||
className="md:hidden p-2"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 6h16M4 12h16M4 18h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
{/* Mobile Menu */}
|
||||
{mobileMenuOpen && (
|
||||
<div className="md:hidden border-b border-gray-200 bg-white">
|
||||
<div className="flex flex-col gap-4 px-4 py-4">
|
||||
<a href="#timeline" className="text-gray-600 hover:text-gray-900">
|
||||
Timeline
|
||||
</a>
|
||||
<a href="#hadiah" className="text-gray-600 hover:text-gray-900">
|
||||
Hadiah
|
||||
</a>
|
||||
<a href="#faq" className="text-gray-600 hover:text-gray-900">
|
||||
FAQ
|
||||
</a>
|
||||
<a href="#masuk" className="text-gray-600 hover:text-gray-900">
|
||||
Masuk
|
||||
</a>
|
||||
<button
|
||||
onClick={() => navigate('/auth/login')}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-center"
|
||||
>
|
||||
Daftar Sekarang
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Hero Section */}
|
||||
<section className="flex flex-col items-center justify-center px-4 md:px-8 py-10 md:py-20 bg-gradient-to-b from-white to-gray-50">
|
||||
{/* Logos */}
|
||||
<div className="flex items-center gap-4 md:gap-8 lg:gap-12 mb-8 md:mb-12 lg:mb-16 flex-wrap justify-center">
|
||||
<div className="flex items-center">
|
||||
<span className="text-3xl md:text-5xl lg:text-6xl font-bold text-blue-600">
|
||||
IMPHNEN
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-3xl md:text-5xl lg:text-6xl font-bold text-gray-400">
|
||||
×
|
||||
</span>
|
||||
<div className="flex items-center">
|
||||
<span className="text-3xl md:text-5xl lg:text-6xl font-bold">
|
||||
Kolosal
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<h1 className="text-5xl md:text-7xl lg:text-9xl font-bold text-gray-900 mb-6 md:mb-10 lg:mb-12 text-center">
|
||||
Hackathon
|
||||
</h1>
|
||||
<p className="text-lg text-gray-600 mb-8">
|
||||
Welcome to the Hackathon platform
|
||||
|
||||
{/* Subtitle */}
|
||||
<p className="text-xl md:text-3xl lg:text-4xl text-blue-600 font-semibold mb-6 md:mb-8 text-center px-4">
|
||||
"Inovasi AI: Mendorong Usaha Lokal dengan AI Inklusif"
|
||||
</p>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-base md:text-xl lg:text-2xl text-gray-600 max-w-xs md:max-w-2xl lg:max-w-3xl text-center mb-8 md:mb-12 px-4">
|
||||
Kompetisi pengembangan teknologi untuk menciptakan
|
||||
<br className="hidden md:block" /> solusi inovatif yang menghadirkan
|
||||
dampak nyata
|
||||
</p>
|
||||
|
||||
{/* Status */}
|
||||
<div className="flex flex-col md:flex-row items-center gap-4 md:gap-8 mb-10 md:mb-16 text-sm md:text-lg lg:text-xl text-gray-600">
|
||||
<div className="flex items-center gap-2 md:gap-3">
|
||||
<svg
|
||||
className="w-5 h-5 md:w-6 md:h-6"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<circle cx="10" cy="10" r="8" fill="#10b981" />
|
||||
</svg>
|
||||
<span>Online</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 md:gap-3 text-center">
|
||||
<svg
|
||||
className="w-5 h-5 md:w-6 md:h-6"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" />
|
||||
</svg>
|
||||
<span>Pendaftaran hingga 30 November 2025</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CTA Buttons */}
|
||||
<div className="flex flex-col md:flex-row gap-4 w-full md:w-auto px-4 md:px-0">
|
||||
<button
|
||||
onClick={() => navigate('/auth/login')}
|
||||
className="w-full md:w-auto px-6 md:px-8 py-3 bg-blue-600 text-white text-base md:text-lg rounded-lg hover:bg-blue-700 transition-colors text-center font-semibold"
|
||||
>
|
||||
Daftar Sekarang
|
||||
</button>
|
||||
<button className="w-full md:w-auto px-6 md:px-8 py-3 bg-white text-gray-900 text-base md:text-lg rounded-lg border-2 border-gray-300 hover:border-gray-400 transition-colors text-center font-semibold">
|
||||
Gabung Grup WA Hackathon
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Scroll indicator */}
|
||||
<div className="mt-12 md:mt-20">
|
||||
<svg
|
||||
className="w-6 h-6 text-gray-400 animate-bounce"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 14l-7 7m0 0l-7-7m7 7V3"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* About Section */}
|
||||
<section className="py-16 md:py-24 px-4 md:px-8 bg-white">
|
||||
<div className="max-w-4xl mx-auto text-center">
|
||||
<h2 className="text-3xl md:text-5xl font-bold mb-6">
|
||||
Tentang <span className="text-blue-600">Hackathon</span>
|
||||
</h2>
|
||||
<p className="text-lg md:text-xl text-gray-600 mb-6">
|
||||
<span className="font-semibold text-gray-900">Hackathon</span>{' '}
|
||||
adalah kompetisi pengembangan teknologi yang mengajak talenta muda
|
||||
untuk berkolaborasi dalam menciptakan solusi inovatif.
|
||||
</p>
|
||||
<p className="text-lg md:text-xl text-gray-600">
|
||||
IMPHNEN bersama Kolosal.ai mengadakan Hackathon dengan tema lomba{' '}
|
||||
<span className="font-semibold text-blue-600">
|
||||
"Inovasi AI: Mendorong Usaha Lokal dengan AI Inklusif"
|
||||
</span>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Prizes Section */}
|
||||
<section id="hadiah" className="py-16 md:py-24 px-4 md:px-8 bg-gray-50">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<div className="text-center mb-12">
|
||||
<h2 className="text-3xl md:text-5xl font-bold mb-4">
|
||||
Hadiah <span className="text-blue-600">Menarik</span>
|
||||
</h2>
|
||||
<p className="text-xl md:text-2xl text-blue-600 font-semibold">
|
||||
Total Prize Pool Rp14.500.000
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{/* Prize 1 */}
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg border-2 border-blue-500 transform hover:scale-105 transition-transform">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center">
|
||||
<svg
|
||||
className="w-8 h-8 text-blue-600"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-center mb-2">Juara 1</h3>
|
||||
<p className="text-3xl font-bold text-blue-600 text-center">
|
||||
Rp6.000.000
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Prize 2 */}
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg border-2 border-gray-300 transform hover:scale-105 transition-transform">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center">
|
||||
<svg
|
||||
className="w-8 h-8 text-gray-600"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-center mb-2">Juara 2</h3>
|
||||
<p className="text-3xl font-bold text-blue-600 text-center">
|
||||
Rp4.000.000
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Prize 3 */}
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg border-2 border-orange-300 transform hover:scale-105 transition-transform">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="w-16 h-16 bg-orange-100 rounded-full flex items-center justify-center">
|
||||
<svg
|
||||
className="w-8 h-8 text-orange-600"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-center mb-2">Juara 3</h3>
|
||||
<p className="text-3xl font-bold text-orange-600 text-center">
|
||||
Rp2.500.000
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Special Prize */}
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg border-2 border-purple-300 transform hover:scale-105 transition-transform">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center">
|
||||
<svg
|
||||
className="w-8 h-8 text-purple-600"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-center mb-2">
|
||||
Juara Kategori Lainnya
|
||||
</h3>
|
||||
<p className="text-3xl font-bold text-purple-600 text-center">
|
||||
Rp2.000.000
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Timeline Section */}
|
||||
<section id="timeline" className="py-16 md:py-24 px-4 md:px-8 bg-white">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="text-center mb-12">
|
||||
<h2 className="text-3xl md:text-5xl font-bold mb-4">
|
||||
Timeline <span className="text-blue-600">Acara</span>
|
||||
</h2>
|
||||
<p className="text-lg text-gray-600">
|
||||
Jadwal lengkap pelaksanaan hackathon
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-8">
|
||||
{/* Timeline Item 1 */}
|
||||
<div className="flex gap-6">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-4 h-4 bg-blue-600 rounded-full"></div>
|
||||
<div className="w-0.5 h-full bg-gray-300"></div>
|
||||
</div>
|
||||
<div className="flex-1 pb-8">
|
||||
<p className="text-blue-600 font-semibold mb-2">
|
||||
30 November 2025
|
||||
</p>
|
||||
<h3 className="text-xl font-bold mb-2">Penutupan Registrasi</h3>
|
||||
<p className="text-gray-600">
|
||||
Batas akhir pendaftaran peserta hackathon.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline Item 2 */}
|
||||
<div className="flex gap-6">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-4 h-4 bg-blue-600 rounded-full"></div>
|
||||
<div className="w-0.5 h-full bg-gray-300"></div>
|
||||
</div>
|
||||
<div className="flex-1 pb-8">
|
||||
<p className="text-blue-600 font-semibold mb-2">
|
||||
30 November 2025
|
||||
</p>
|
||||
<h3 className="text-xl font-bold mb-2">Technical Meeting</h3>
|
||||
<p className="text-gray-600">
|
||||
Akan diadakan technical meeting terkait lomba melalui Google
|
||||
Meet. Stay tune di grup WA Hackathon.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline Item 3 */}
|
||||
<div className="flex gap-6">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-4 h-4 bg-blue-600 rounded-full"></div>
|
||||
<div className="w-0.5 h-full bg-gray-300"></div>
|
||||
</div>
|
||||
<div className="flex-1 pb-8">
|
||||
<p className="text-blue-600 font-semibold mb-2">
|
||||
1 - 7 Desember 2025
|
||||
</p>
|
||||
<h3 className="text-xl font-bold mb-2">Tahap Penyisihan</h3>
|
||||
<p className="text-gray-600">
|
||||
Peserta mengerjakan tantangan yang diberikan.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline Item 4 */}
|
||||
<div className="flex gap-6">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-4 h-4 bg-blue-600 rounded-full"></div>
|
||||
<div className="w-0.5 h-full bg-gray-300"></div>
|
||||
</div>
|
||||
<div className="flex-1 pb-8">
|
||||
<p className="text-blue-600 font-semibold mb-2">
|
||||
8 - 14 Desember 2025
|
||||
</p>
|
||||
<h3 className="text-xl font-bold mb-2">Penilaian & Webinar</h3>
|
||||
<p className="text-gray-600">
|
||||
Proses penilaian oleh juri dan sesi webinar.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline Item 5 */}
|
||||
<div className="flex gap-6">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="w-4 h-4 bg-blue-600 rounded-full"></div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="text-blue-600 font-semibold mb-2">
|
||||
15 Desember 2025
|
||||
</p>
|
||||
<h3 className="text-xl font-bold mb-2">Pengumuman & Final</h3>
|
||||
<p className="text-gray-600">
|
||||
Presentasi final dan pengumuman pemenang.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Judges Section */}
|
||||
<section className="py-16 md:py-24 px-4 md:px-8 bg-gray-50">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<div className="text-center mb-12">
|
||||
<h2 className="text-3xl md:text-5xl font-bold mb-4">
|
||||
Dewan <span className="text-blue-600">Juri</span>
|
||||
</h2>
|
||||
<p className="text-lg text-gray-600">
|
||||
Perwakilan dari IMPHNEN dan Kolosal.ai yang akan menilai karya
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
{/* Judge 1 */}
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg text-center">
|
||||
<div className="w-24 h-24 bg-gray-200 rounded-full mx-auto mb-4"></div>
|
||||
<h3 className="text-xl font-bold mb-1">
|
||||
Alifais Farrel Ramdhani
|
||||
</h3>
|
||||
<p className="text-blue-600 font-semibold mb-1">CTO</p>
|
||||
<p className="text-gray-600">Kolosal.ai</p>
|
||||
</div>
|
||||
|
||||
{/* Judge 2 */}
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg text-center">
|
||||
<div className="w-24 h-24 bg-gray-200 rounded-full mx-auto mb-4"></div>
|
||||
<h3 className="text-xl font-bold mb-1">Anka Tama</h3>
|
||||
<p className="text-blue-600 font-semibold mb-1">Admin</p>
|
||||
<p className="text-gray-600">IMPHNEN</p>
|
||||
</div>
|
||||
|
||||
{/* Judge 3 */}
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg text-center">
|
||||
<div className="w-24 h-24 bg-gray-200 rounded-full mx-auto mb-4"></div>
|
||||
<h3 className="text-xl font-bold mb-1">Hafid Nur</h3>
|
||||
<p className="text-blue-600 font-semibold mb-1">Moderator</p>
|
||||
<p className="text-gray-600">IMPHNEN</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* FAQ Section */}
|
||||
<section id="faq" className="py-16 md:py-24 px-4 md:px-8 bg-white">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="text-center mb-12">
|
||||
<h2 className="text-3xl md:text-5xl font-bold mb-4 text-blue-600">
|
||||
FAQ
|
||||
</h2>
|
||||
<p className="text-lg text-gray-600">
|
||||
Pertanyaan yang Sering Diajukan
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-gray-500">
|
||||
This is a new Vite + React app with file-based routing
|
||||
{faqs.map((faq, index) => (
|
||||
<div key={index} className="border border-gray-200 rounded-lg">
|
||||
<button
|
||||
onClick={() => setOpenFaq(openFaq === index ? null : index)}
|
||||
className="w-full px-6 py-4 flex items-center justify-between text-left hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<span className="font-semibold text-gray-900">
|
||||
{faq.question}
|
||||
</span>
|
||||
<svg
|
||||
className={`w-5 h-5 text-blue-600 transform transition-transform ${
|
||||
openFaq === index ? 'rotate-180' : ''
|
||||
}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
{openFaq === index && (
|
||||
<div className="px-6 pb-4 text-gray-600">{faq.answer}</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Sponsors Section */}
|
||||
<section className="py-16 md:py-24 px-4 md:px-8 bg-gray-50">
|
||||
<div className="max-w-6xl mx-auto text-center">
|
||||
<h2 className="text-3xl md:text-5xl font-bold mb-4">
|
||||
Sponsor & <span className="text-blue-600">Partner</span>
|
||||
</h2>
|
||||
<p className="text-lg text-gray-600 mb-12">
|
||||
Acara ini sepenuhnya disponsori oleh
|
||||
</p>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<div className="bg-white rounded-xl p-8 shadow-lg inline-block">
|
||||
<span className="text-3xl font-bold">Kolosal</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* CTA Section */}
|
||||
<section
|
||||
id="masuk"
|
||||
className="py-16 md:py-24 px-4 md:px-8 bg-gradient-to-b from-white to-blue-50"
|
||||
>
|
||||
<div className="max-w-4xl mx-auto text-center">
|
||||
<h2 className="text-3xl md:text-5xl font-bold mb-6">
|
||||
Segera Daftarkan <span className="text-blue-600">Timmu!</span>
|
||||
</h2>
|
||||
<p className="text-lg md:text-xl text-gray-600 mb-8">
|
||||
Jangan lewatkan kesempatan emas untuk bersaing dengan developer
|
||||
terbaik,
|
||||
<br className="hidden md:block" />
|
||||
belajar dari para ahli, dan memenangkan hadiah jutaan rupiah!
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col md:flex-row gap-4 justify-center">
|
||||
<button
|
||||
onClick={() => navigate('/auth/login')}
|
||||
className="px-8 py-3 bg-blue-600 text-white text-lg rounded-lg hover:bg-blue-700 transition-colors font-semibold"
|
||||
>
|
||||
Daftar Sekarang
|
||||
</button>
|
||||
<button className="px-8 py-3 bg-white text-gray-900 text-lg rounded-lg border-2 border-gray-300 hover:border-gray-400 transition-colors font-semibold">
|
||||
Gabung Grup WA Hackathon
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-gray-500 mt-6">
|
||||
Pendaftaran ditutup pada{' '}
|
||||
<span className="text-blue-600 font-semibold">
|
||||
30 November 2025
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="bg-gray-900 text-white py-12 px-4 md:px-8">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-8">
|
||||
{/* Brand */}
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<span className="text-2xl font-bold">IMPHNEN</span>
|
||||
<span className="text-2xl font-bold text-blue-500">
|
||||
Hackathon
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-gray-400 text-sm">
|
||||
Wujudkan ide brilian mu menjadi solusi nyata. Bergabunglah dalam
|
||||
IMPHNEN Hackathon dan jadilah bagian dari perubahan teknologi
|
||||
masa depan.
|
||||
</p>
|
||||
<div className="flex gap-4 mt-4">
|
||||
<a
|
||||
href="#"
|
||||
className="text-gray-400 hover:text-white transition-colors"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
|
||||
</svg>
|
||||
</a>
|
||||
<a
|
||||
href="#"
|
||||
className="text-gray-400 hover:text-white transition-colors"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073z" />
|
||||
</svg>
|
||||
</a>
|
||||
<a
|
||||
href="#"
|
||||
className="text-gray-400 hover:text-white transition-colors"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.840 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Links */}
|
||||
<div>
|
||||
<h3 className="font-bold text-lg mb-4">Quick Links</h3>
|
||||
<ul className="space-y-2 text-gray-400">
|
||||
<li>
|
||||
<a
|
||||
href="#timeline"
|
||||
className="hover:text-white transition-colors"
|
||||
>
|
||||
Timeline
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
href="#hadiah"
|
||||
className="hover:text-white transition-colors"
|
||||
>
|
||||
Hadiah
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#faq" className="hover:text-white transition-colors">
|
||||
FAQ
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
href="#masuk"
|
||||
className="hover:text-white transition-colors"
|
||||
>
|
||||
Daftar
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Contact */}
|
||||
<div>
|
||||
<h3 className="font-bold text-lg mb-4">Contact</h3>
|
||||
<ul className="space-y-2 text-gray-400">
|
||||
<li className="flex items-center gap-2">
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
imphnen@gmail.com
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M17 8h2a2 2 0 012 2v6a2 2 0 01-2 2h-2v4l-4-4H9a1.994 1.994 0 01-1.414-.586m0 0L11 14h4a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2v4l.586-.586z"
|
||||
/>
|
||||
</svg>
|
||||
WA Group Hackathon
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"
|
||||
/>
|
||||
</svg>
|
||||
IMPHNEN.dev
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-800 pt-8 text-center text-gray-400 text-sm">
|
||||
<p>
|
||||
© 2025 IMPHNEN - Ingin Menjadi Programmer Handal Namun Enggan
|
||||
Ngoding. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import { FC, ReactElement, useState, useRef, useEffect } from 'react';
|
||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { useTeamById, useTeamMessages, useSendMessage, useDeleteMessage } from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const TeamChatPage: FC = (): ReactElement => {
|
||||
const { teamId } = useParams<{ teamId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { session } = useAuthStore();
|
||||
const [message, setMessage] = useState('');
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data: teamData } = useTeamById(teamId || '');
|
||||
const { data: messages, isLoading } = useTeamMessages(teamId || '');
|
||||
const { mutateAsync: sendMessage, isPending: isSending } = useSendMessage(teamId || '');
|
||||
const { mutateAsync: deleteMessage } = useDeleteMessage(teamId || '');
|
||||
|
||||
const team = teamData?.data;
|
||||
const currentUserId = session?.user?.id;
|
||||
|
||||
// Auto-scroll to bottom when new messages arrive
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, [messages]);
|
||||
|
||||
const handleSendMessage = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!message.trim() || isSending) return;
|
||||
|
||||
try {
|
||||
await sendMessage(message.trim());
|
||||
setMessage('');
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
toast.error('Failed to send message');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteMessage = async (messageId: string) => {
|
||||
if (!confirm('Are you sure you want to delete this message?')) return;
|
||||
|
||||
try {
|
||||
await deleteMessage(messageId);
|
||||
toast.success('Message deleted');
|
||||
} catch (error) {
|
||||
console.error('Failed to delete message:', error);
|
||||
toast.error('Failed to delete message');
|
||||
}
|
||||
};
|
||||
|
||||
const formatTime = (timestamp: string) => {
|
||||
const date = new Date(timestamp);
|
||||
const now = new Date();
|
||||
const diffInMs = now.getTime() - date.getTime();
|
||||
const diffInMins = Math.floor(diffInMs / 60000);
|
||||
|
||||
if (diffInMins < 1) return 'Just now';
|
||||
if (diffInMins < 60) return `${diffInMins}m ago`;
|
||||
if (diffInMins < 1440) return `${Math.floor(diffInMins / 60)}h ago`;
|
||||
|
||||
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-50">
|
||||
{/* Header */}
|
||||
<div className="bg-white border-b shadow-sm">
|
||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Team Chat</h1>
|
||||
<p className="text-gray-600 text-sm mt-0.5">{team?.name}</p>
|
||||
</div>
|
||||
<Button variant="secondary" onClick={() => navigate(`/teams/${teamId}`)}>
|
||||
Back to Team
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Messages Container */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
|
||||
</div>
|
||||
) : messages && messages.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{messages.map((msg) => {
|
||||
const isOwnMessage = msg.user_id === currentUserId;
|
||||
const isLeader = team?.leader_id === currentUserId;
|
||||
const canDelete = isOwnMessage || isLeader;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`flex ${isOwnMessage ? 'justify-end' : 'justify-start'}`}
|
||||
>
|
||||
<div className={`flex gap-3 max-w-lg ${isOwnMessage ? 'flex-row-reverse' : 'flex-row'}`}>
|
||||
{/* Avatar */}
|
||||
<div className="flex-shrink-0">
|
||||
{msg.user?.avatar ? (
|
||||
<img
|
||||
src={msg.user.avatar}
|
||||
alt={msg.user.fullname}
|
||||
className="w-10 h-10 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-full bg-blue-600 flex items-center justify-center text-white font-semibold">
|
||||
{msg.user?.fullname?.charAt(0) || '?'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Message Bubble */}
|
||||
<div className={`flex-1 ${isOwnMessage ? 'text-right' : 'text-left'}`}>
|
||||
<div className={`inline-block ${isOwnMessage ? 'items-end' : 'items-start'}`}>
|
||||
<div className="flex items-baseline gap-2 mb-1">
|
||||
<span className="font-semibold text-sm text-gray-900">
|
||||
{isOwnMessage ? 'You' : msg.user?.fullname}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{formatTime(msg.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={`relative group rounded-2xl px-4 py-2.5 ${
|
||||
isOwnMessage
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-white text-gray-900 border border-gray-200'
|
||||
}`}
|
||||
>
|
||||
<p className="text-sm whitespace-pre-wrap break-words">{msg.message}</p>
|
||||
|
||||
{/* Delete button */}
|
||||
{canDelete && (
|
||||
<button
|
||||
onClick={() => handleDeleteMessage(msg.id)}
|
||||
className={`absolute top-1 ${isOwnMessage ? 'left-1' : 'right-1'} opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded hover:bg-gray-200 ${isOwnMessage ? 'hover:bg-blue-700' : ''}`}
|
||||
title="Delete message"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-center">
|
||||
<div className="text-6xl mb-4">💬</div>
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2">
|
||||
No messages yet
|
||||
</h3>
|
||||
<p className="text-gray-600">
|
||||
Be the first to start the conversation!
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Message Input */}
|
||||
<div className="bg-white border-t shadow-lg">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
|
||||
<form onSubmit={handleSendMessage} className="flex gap-3">
|
||||
<input
|
||||
type="text"
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
placeholder="Type your message..."
|
||||
className="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
disabled={isSending}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!message.trim() || isSending}
|
||||
className="px-6 py-3"
|
||||
>
|
||||
{isSending ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Sending...
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
|
||||
</svg>
|
||||
Send
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TeamChatPage;
|
||||
@@ -0,0 +1,353 @@
|
||||
import { FC, ReactElement, useState, useEffect } from 'react';
|
||||
import { ControlledInputField } from '@imphnen-frontend-service/ui/organisms';
|
||||
import { Button, Textarea } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { teamUpdateSchema, TTeamUpdateForm, useUpdateTeam, useTeamById, ETeamVisibility, useUploadFile } from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
const INDONESIAN_CITIES = [
|
||||
'Jakarta', 'Surabaya', 'Bandung', 'Medan', 'Semarang',
|
||||
'Makassar', 'Palembang', 'Tangerang', 'Depok', 'Bekasi',
|
||||
'Yogyakarta', 'Malang', 'Bogor', 'Batam', 'Pekanbaru',
|
||||
];
|
||||
|
||||
const EditTeamPage: FC = (): ReactElement => {
|
||||
const { teamId } = useParams<{ teamId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { session } = useAuthStore();
|
||||
const [logoFile, setLogoFile] = useState<File | null>(null);
|
||||
const [logoPreview, setLogoPreview] = useState<string>('');
|
||||
const [bannerFile, setBannerFile] = useState<File | null>(null);
|
||||
const [bannerPreview, setBannerPreview] = useState<string>('');
|
||||
|
||||
const { data: teamData, isLoading: isLoadingTeam } = useTeamById(teamId || '');
|
||||
const { mutateAsync: updateTeam, isPending: isUpdating } = useUpdateTeam(teamId || '');
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const team = teamData?.data;
|
||||
const currentUserId = session?.user?.id;
|
||||
const isLeader = currentUserId === team?.leader_id;
|
||||
|
||||
const form = useForm<TTeamUpdateForm>({
|
||||
resolver: zodResolver(teamUpdateSchema),
|
||||
mode: 'all',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (team) {
|
||||
form.reset({
|
||||
name: team.name,
|
||||
description: team.description,
|
||||
city: team.city,
|
||||
visibility: team.visibility,
|
||||
logo: team.logo,
|
||||
banner: team.banner,
|
||||
});
|
||||
if (team.logo) setLogoPreview(team.logo);
|
||||
if (team.banner) setBannerPreview(team.banner);
|
||||
}
|
||||
}, [team, form]);
|
||||
|
||||
if (isLoadingTeam) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-gray-600">Loading team...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLeader) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Access Denied</h2>
|
||||
<p className="text-gray-600 mb-4">Only the team leader can edit team information</p>
|
||||
<Button onClick={() => navigate(`/teams/${teamId}`)}>Back to Team</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setLogoFile(file);
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
setLogoPreview(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBannerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setBannerFile(file);
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
setBannerPreview(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
let logoUrl = data.logo;
|
||||
let bannerUrl = data.banner;
|
||||
|
||||
if (logoFile) {
|
||||
const logoResult = await uploadFile(logoFile);
|
||||
logoUrl = logoResult.data.url;
|
||||
}
|
||||
|
||||
if (bannerFile) {
|
||||
const bannerResult = await uploadFile(bannerFile);
|
||||
bannerUrl = bannerResult.data.url;
|
||||
}
|
||||
|
||||
await updateTeam({
|
||||
...data,
|
||||
logo: logoUrl,
|
||||
banner: bannerUrl,
|
||||
});
|
||||
|
||||
navigate(`/teams/${teamId}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to update team:', error);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="bg-white border-b">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<h1 className="text-3xl font-bold text-gray-900">Edit Team Info</h1>
|
||||
<p className="text-gray-600 mt-1">Update your team details</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
<div className="bg-white rounded-lg shadow-md p-8">
|
||||
<form onSubmit={onSubmit} className="space-y-6">
|
||||
{/* Banner Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Team Banner
|
||||
</label>
|
||||
{bannerPreview ? (
|
||||
<div className="relative">
|
||||
<img
|
||||
src={bannerPreview}
|
||||
alt="Banner preview"
|
||||
className="w-full h-48 object-cover rounded-lg border-2 border-gray-200"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setBannerFile(null);
|
||||
setBannerPreview('');
|
||||
form.setValue('banner', null);
|
||||
}}
|
||||
className="absolute top-2 right-2 bg-red-500 text-white px-3 py-1 rounded-lg text-sm hover:bg-red-600"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
|
||||
<div className="text-center">
|
||||
<p className="text-gray-500">Click to upload banner</p>
|
||||
<p className="text-xs text-gray-400 mt-1">1200x400 recommended</p>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleBannerChange}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Logo Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Team Logo
|
||||
</label>
|
||||
<div className="flex items-center space-x-4">
|
||||
{logoPreview ? (
|
||||
<img
|
||||
src={logoPreview}
|
||||
alt="Logo preview"
|
||||
className="w-24 h-24 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-24 h-24 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-400 text-3xl">👥</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="logo" className="cursor-pointer">
|
||||
<span className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 inline-block">
|
||||
{logoPreview ? 'Change Logo' : 'Upload Logo'}
|
||||
</span>
|
||||
<input
|
||||
id="logo"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleLogoChange}
|
||||
/>
|
||||
</label>
|
||||
{logoPreview && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setLogoFile(null);
|
||||
setLogoPreview('');
|
||||
form.setValue('logo', null);
|
||||
}}
|
||||
className="ml-3 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Team Name */}
|
||||
<ControlledInputField
|
||||
control={form.control}
|
||||
label="Team Name"
|
||||
placeholder="Enter team name"
|
||||
name="name"
|
||||
/>
|
||||
|
||||
{/* City */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
City
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="city"
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<select
|
||||
{...field}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="">Select city</option>
|
||||
{INDONESIAN_CITIES.map((city) => (
|
||||
<option key={city} value={city}>
|
||||
{city}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldState.error && (
|
||||
<p className="text-sm text-red-500 mt-1">{fieldState.error.message}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Description
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<Textarea
|
||||
{...field}
|
||||
value={field.value || ''}
|
||||
placeholder="Tell others about your team..."
|
||||
rows={4}
|
||||
className="w-full"
|
||||
/>
|
||||
{fieldState.error && (
|
||||
<p className="text-sm text-red-500 mt-1">{fieldState.error.message}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Visibility */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Team Visibility
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="visibility"
|
||||
render={({ field }) => (
|
||||
<div className="space-y-3">
|
||||
<label className="flex items-start space-x-3 cursor-pointer border rounded-lg p-4 hover:bg-gray-50">
|
||||
<input
|
||||
type="radio"
|
||||
{...field}
|
||||
value={ETeamVisibility.PUBLIC}
|
||||
checked={field.value === ETeamVisibility.PUBLIC}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">Public</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
Team will be visible in Browse Teams
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
<label className="flex items-start space-x-3 cursor-pointer border rounded-lg p-4 hover:bg-gray-50">
|
||||
<input
|
||||
type="radio"
|
||||
{...field}
|
||||
value={ETeamVisibility.PRIVATE}
|
||||
checked={field.value === ETeamVisibility.PRIVATE}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">Private</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
Team hidden, invite-only
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="flex space-x-3 pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => navigate(`/teams/${teamId}`)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="flex-1"
|
||||
disabled={isUpdating || isUploading}
|
||||
>
|
||||
{isUpdating || isUploading ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditTeamPage;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { FC, ReactNode } from 'react';
|
||||
import { Outlet } from 'react-router';
|
||||
import { Navigation } from '../../../components/navigation';
|
||||
|
||||
interface TeamLayoutProps {
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export const TeamLayout: FC<TeamLayoutProps> = () => {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TeamLayout;
|
||||
@@ -0,0 +1,294 @@
|
||||
import { FC, ReactElement, useState } from 'react';
|
||||
import { Button, Input } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import {
|
||||
useTeamById,
|
||||
useTeamMembers,
|
||||
useTeamJoinRequests,
|
||||
useInviteMember,
|
||||
useRemoveMember,
|
||||
useRespondToJoinRequest,
|
||||
ETeamMemberStatus,
|
||||
inviteMemberSchema,
|
||||
TInviteMemberForm,
|
||||
} from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
const ManageMembersPage: FC = (): ReactElement => {
|
||||
const { teamId } = useParams<{ teamId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { session } = useAuthStore();
|
||||
const [showInviteModal, setShowInviteModal] = useState(false);
|
||||
|
||||
const { data: teamData } = useTeamById(teamId || '');
|
||||
const { data: membersData, isLoading: isLoadingMembers } = useTeamMembers(teamId || '');
|
||||
const { data: joinRequestsData } = useTeamJoinRequests(teamId || '');
|
||||
|
||||
const { mutateAsync: inviteMember, isPending: isInviting } = useInviteMember(teamId || '');
|
||||
const { mutateAsync: removeMember, isPending: isRemoving } = useRemoveMember(teamId || '');
|
||||
const { mutateAsync: respondToRequest, isPending: isResponding } = useRespondToJoinRequest(teamId || '');
|
||||
|
||||
const team = teamData?.data;
|
||||
const members = membersData?.data || [];
|
||||
const joinRequests = Array.isArray(joinRequestsData?.data) ? joinRequestsData.data : [];
|
||||
const currentUserId = session?.user?.id;
|
||||
const isLeader = currentUserId === team?.leader_id;
|
||||
|
||||
const form = useForm<TInviteMemberForm>({
|
||||
resolver: zodResolver(inviteMemberSchema),
|
||||
mode: 'all',
|
||||
});
|
||||
|
||||
if (!isLeader) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Access Denied</h2>
|
||||
<p className="text-gray-600 mb-4">Only the team leader can manage members</p>
|
||||
<Button onClick={() => navigate(`/teams/${teamId}`)}>Back to Team</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleInvite = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
await inviteMember(data);
|
||||
setShowInviteModal(false);
|
||||
form.reset();
|
||||
} catch (error) {
|
||||
console.error('Failed to invite member:', error);
|
||||
}
|
||||
});
|
||||
|
||||
const handleRemove = async (userId: string) => {
|
||||
// eslint-disable-next-line no-restricted-globals
|
||||
if (confirm('Are you sure you want to remove this member?')) {
|
||||
try {
|
||||
await removeMember(userId);
|
||||
} catch (error) {
|
||||
console.error('Failed to remove member:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleApproveRequest = async (requestId: string) => {
|
||||
try {
|
||||
await respondToRequest({ requestId, action: 'approve' });
|
||||
} catch (error) {
|
||||
console.error('Failed to approve request:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRejectRequest = async (requestId: string) => {
|
||||
try {
|
||||
await respondToRequest({ requestId, action: 'reject' });
|
||||
} catch (error) {
|
||||
console.error('Failed to reject request:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="bg-white border-b">
|
||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Manage Members</h1>
|
||||
<p className="text-gray-600 mt-1">{team?.name}</p>
|
||||
</div>
|
||||
<div className="flex space-x-3">
|
||||
<Button onClick={() => setShowInviteModal(true)}>
|
||||
Invite Member
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate(`/teams/${teamId}`)}>
|
||||
Back to Team
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
|
||||
{/* Join Requests */}
|
||||
{joinRequests.length > 0 && (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">
|
||||
Join Requests ({joinRequests.length})
|
||||
</h2>
|
||||
<div className="space-y-3">
|
||||
{joinRequests.map((request) => (
|
||||
<div key={request.id} className="border rounded-lg p-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center space-x-3 flex-1">
|
||||
{request.user.avatar ? (
|
||||
<img
|
||||
src={request.user.avatar}
|
||||
alt={request.user.fullname}
|
||||
className="w-12 h-12 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-500">👤</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<p className="font-medium text-gray-900">{request.user.fullname}</p>
|
||||
<p className="text-sm text-gray-600">{request.user.email}</p>
|
||||
{request.user.location && (
|
||||
<p className="text-sm text-gray-500">📍 {request.user.location}</p>
|
||||
)}
|
||||
<p className="text-sm text-gray-700 mt-2 italic">"{request.message}"</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex space-x-2 ml-4">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleApproveRequest(request.id)}
|
||||
disabled={isResponding}
|
||||
>
|
||||
Approve
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => handleRejectRequest(request.id)}
|
||||
disabled={isResponding}
|
||||
>
|
||||
Reject
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Current Members */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">
|
||||
Current Members ({members.length})
|
||||
</h2>
|
||||
{isLoadingMembers ? (
|
||||
<p className="text-gray-600">Loading members...</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{members.map((member) => (
|
||||
<div key={member.id} className="border rounded-lg p-4 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-3">
|
||||
{member.user.avatar ? (
|
||||
<img
|
||||
src={member.user.avatar}
|
||||
alt={member.user.fullname}
|
||||
className="w-12 h-12 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-500">👤</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">{member.user.fullname}</p>
|
||||
<p className="text-sm text-gray-600">{member.user.email}</p>
|
||||
{member.user.location && (
|
||||
<p className="text-sm text-gray-500">📍 {member.user.location}</p>
|
||||
)}
|
||||
<div className="flex items-center space-x-2 mt-1">
|
||||
{member.role === 'leader' && (
|
||||
<span className="px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs font-medium">
|
||||
Leader
|
||||
</span>
|
||||
)}
|
||||
{member.status === ETeamMemberStatus.PENDING && (
|
||||
<span className="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-xs font-medium">
|
||||
Pending Invitation
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{member.role !== 'leader' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => handleRemove(member.user_id)}
|
||||
disabled={isRemoving}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Warning */}
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
|
||||
<p className="text-sm text-yellow-800">
|
||||
<strong>Note:</strong> Members cannot leave the team without your approval. Only you can remove members from the team.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Invite Member Modal */}
|
||||
{showInviteModal && (
|
||||
<div className="fixed inset-0 bg-black/20 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
Invite Member
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-4">
|
||||
Send an invitation to join your team. The invited member will see the invitation on their dashboard after logging in.
|
||||
</p>
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3 mb-6">
|
||||
<p className="text-sm text-yellow-800">
|
||||
<strong>Important:</strong> The email you enter must match the GitHub email address the member uses to sign in.
|
||||
</p>
|
||||
</div>
|
||||
<form onSubmit={handleInvite} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<Input
|
||||
{...form.register('email')}
|
||||
type="email"
|
||||
placeholder="member@example.com"
|
||||
/>
|
||||
{form.formState.errors.email && (
|
||||
<p className="text-sm text-red-500 mt-1">
|
||||
{form.formState.errors.email.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex space-x-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => {
|
||||
setShowInviteModal(false);
|
||||
form.reset();
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="flex-1"
|
||||
disabled={!form.formState.isValid || isInviting}
|
||||
>
|
||||
{isInviting ? 'Sending...' : 'Send Invitation'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ManageMembersPage;
|
||||
@@ -0,0 +1,445 @@
|
||||
import { FC, ReactElement, useState } from 'react';
|
||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { Link, useParams, useNavigate } from 'react-router';
|
||||
import { useTeamById, useTeamMembers, useInviteMember, useTeamJoinRequests, useRespondToJoinRequest, ETeamMemberRole } from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const MAX_TEAM_MEMBERS = 5;
|
||||
|
||||
const TeamDashboardPage: FC = (): ReactElement => {
|
||||
const { teamId } = useParams<{ teamId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { session } = useAuthStore();
|
||||
const [showInviteModal, setShowInviteModal] = useState(false);
|
||||
const [showJoinRequestsModal, setShowJoinRequestsModal] = useState(false);
|
||||
const [inviteEmail, setInviteEmail] = useState('');
|
||||
|
||||
const { data: teamData, isLoading: isLoadingTeam } = useTeamById(teamId || '');
|
||||
const { data: membersData, isLoading: isLoadingMembers } = useTeamMembers(teamId || '');
|
||||
const { data: joinRequestsData } = useTeamJoinRequests(teamId || '', !!teamId);
|
||||
const { mutateAsync: inviteMember, isPending: isInviting } = useInviteMember(teamId || '');
|
||||
const { mutateAsync: respondToJoinRequest, isPending: isResponding } = useRespondToJoinRequest(teamId || '');
|
||||
|
||||
const team = teamData?.data;
|
||||
const members = membersData?.data || [];
|
||||
const joinRequests = joinRequestsData?.data || [];
|
||||
const pendingJoinRequests = joinRequests.filter((req: any) => req.status === 'pending');
|
||||
const currentUserId = session?.user?.id;
|
||||
|
||||
const isLeader = currentUserId === team?.leader_id;
|
||||
const canInvite = isLeader && members.length < MAX_TEAM_MEMBERS;
|
||||
|
||||
console.log('Leader check:', { currentUserId, leaderId: team?.leader_id, isLeader });
|
||||
|
||||
const handleInviteMember = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!inviteEmail.trim() || isInviting) return;
|
||||
|
||||
try {
|
||||
await inviteMember({ email: inviteEmail.trim() });
|
||||
toast.success('Invitation sent successfully!');
|
||||
setInviteEmail('');
|
||||
setShowInviteModal(false);
|
||||
} catch (error) {
|
||||
console.error('Failed to invite member:', error);
|
||||
toast.error('Failed to send invitation');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRespondToJoinRequest = async (requestId: string, action: 'approve' | 'reject') => {
|
||||
try {
|
||||
await respondToJoinRequest({ requestId, action });
|
||||
toast.success(action === 'approve' ? 'Request approved!' : 'Request rejected');
|
||||
} catch (error) {
|
||||
console.error('Failed to respond to join request:', error);
|
||||
toast.error('Failed to process request');
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoadingTeam || isLoadingMembers) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-gray-600">Loading team...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!team) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Team not found</h2>
|
||||
<Button onClick={() => navigate('/dashboard')}>Back to Dashboard</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Header with Banner */}
|
||||
<div className="bg-white border-b">
|
||||
{team.banner && (
|
||||
<div className="w-full h-48 overflow-hidden">
|
||||
<img
|
||||
src={team.banner}
|
||||
alt={team.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
{team.logo && (
|
||||
<img
|
||||
src={team.logo}
|
||||
alt={team.name}
|
||||
className="w-20 h-20 rounded-full object-cover border-4 border-white shadow-lg -mt-10"
|
||||
/>
|
||||
)}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">{team.name}</h1>
|
||||
<p className="text-gray-600 mt-1">📍 {team.city}</p>
|
||||
<div className="flex items-center space-x-4 mt-2">
|
||||
<span className="text-sm text-gray-500">
|
||||
{members.length} {members.length === 1 ? 'Member' : 'Members'}
|
||||
</span>
|
||||
<span className="text-sm text-gray-500">
|
||||
{team.visibility === 'public' ? '🌐 Public' : '🔒 Private'}
|
||||
</span>
|
||||
{isLeader && (
|
||||
<span className="px-3 py-1 bg-blue-600 text-white rounded-md text-sm font-semibold shadow-sm">
|
||||
👑 Team Leader
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Link to="/dashboard">
|
||||
<Button variant="secondary">Back to Dashboard</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
{/* Main Content */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
{/* Team Description */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">About Team</h2>
|
||||
<p className="text-gray-700 whitespace-pre-wrap">{team.description}</p>
|
||||
</div>
|
||||
|
||||
{/* Team Actions - Only for Leader */}
|
||||
{isLeader && (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">Team Management</h2>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Button
|
||||
className="w-full"
|
||||
variant="secondary"
|
||||
onClick={() => setShowInviteModal(true)}
|
||||
disabled={!canInvite}
|
||||
>
|
||||
➕ Invite Member {!canInvite && `(${members.length}/${MAX_TEAM_MEMBERS})`}
|
||||
</Button>
|
||||
<Button
|
||||
className="w-full relative"
|
||||
variant="secondary"
|
||||
onClick={() => setShowJoinRequestsModal(true)}
|
||||
>
|
||||
📩 Join Requests
|
||||
{pendingJoinRequests.length > 0 && (
|
||||
<span className="absolute -top-2 -right-2 bg-red-500 text-white text-xs font-bold rounded-full w-6 h-6 flex items-center justify-center">
|
||||
{pendingJoinRequests.length}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<Link to={`/teams/${teamId}/edit`}>
|
||||
<Button className="w-full" variant="secondary">
|
||||
✏️ Edit Team Info
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to={`/teams/${teamId}/members`}>
|
||||
<Button className="w-full" variant="secondary">
|
||||
👥 Manage Members
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to={`/teams/${teamId}/chat`}>
|
||||
<Button className="w-full" variant="secondary">
|
||||
💬 Team Chat
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to={`/teams/${teamId}/submit`}>
|
||||
<Button className="w-full">
|
||||
🚀 Submit Project
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
{!canInvite && members.length >= MAX_TEAM_MEMBERS && (
|
||||
<p className="text-sm text-gray-600 mt-3 text-center">
|
||||
Maximum team size reached ({MAX_TEAM_MEMBERS} members)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quick Actions for Members */}
|
||||
{!isLeader && (
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">Quick Actions</h2>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Link to={`/teams/${teamId}/chat`}>
|
||||
<Button className="w-full" variant="secondary">
|
||||
💬 Team Chat
|
||||
</Button>
|
||||
</Link>
|
||||
{team.has_submission && (
|
||||
<Link to={`/teams/${teamId}/submission`}>
|
||||
<Button className="w-full" variant="secondary">
|
||||
📄 View Submission
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Submission Status */}
|
||||
{team.has_submission && (
|
||||
<div className="bg-green-50 border border-green-200 rounded-lg p-6">
|
||||
<div className="flex items-center space-x-3">
|
||||
<span className="text-3xl">✅</span>
|
||||
<div>
|
||||
<h3 className="font-bold text-green-900">Project Submitted</h3>
|
||||
<p className="text-green-700 text-sm">
|
||||
Your team has successfully submitted a project
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Link to={`/teams/${teamId}/submission`}>
|
||||
<Button className="mt-4 w-full" variant="secondary">
|
||||
View Submission Details
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sidebar */}
|
||||
<div className="space-y-6">
|
||||
{/* Team Leader */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h3 className="font-bold text-gray-900 mb-4">Team Leader</h3>
|
||||
{team.leader && (
|
||||
<div className="flex items-center space-x-3">
|
||||
{team.leader.avatar ? (
|
||||
<img
|
||||
src={team.leader.avatar}
|
||||
alt={team.leader.fullname}
|
||||
className="w-12 h-12 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-500">👤</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">{team.leader.fullname}</p>
|
||||
<p className="text-sm text-gray-600">{team.leader.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Team Members */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<h3 className="font-bold text-gray-900 mb-4">
|
||||
Members ({members.length})
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
{members.map((member) => (
|
||||
<div key={member.id} className="flex items-center space-x-3">
|
||||
{member.user.avatar ? (
|
||||
<img
|
||||
src={member.user.avatar}
|
||||
alt={member.user.fullname}
|
||||
className="w-10 h-10 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-500 text-sm">👤</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-gray-900 truncate">
|
||||
{member.user.fullname}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{member.role === ETeamMemberRole.LEADER ? 'Leader' : 'Member'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Invite Member Modal */}
|
||||
{showInviteModal && (
|
||||
<div className="fixed inset-0 bg-black/20 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
Invite Team Member
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-4">
|
||||
Send an invitation to join your team. The invited member will see the invitation on their dashboard after logging in.
|
||||
</p>
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3 mb-6">
|
||||
<p className="text-sm text-yellow-800">
|
||||
<strong>Important:</strong> The email you enter must match the GitHub email address the member uses to sign in.
|
||||
</p>
|
||||
</div>
|
||||
<form onSubmit={handleInviteMember} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="invite-email" className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<input
|
||||
id="invite-email"
|
||||
type="email"
|
||||
value={inviteEmail}
|
||||
onChange={(e) => setInviteEmail(e.target.value)}
|
||||
placeholder="Enter email address..."
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
required
|
||||
/>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
Current members: {members.length}/{MAX_TEAM_MEMBERS}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex space-x-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => {
|
||||
setShowInviteModal(false);
|
||||
setInviteEmail('');
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="flex-1"
|
||||
disabled={!inviteEmail.trim() || isInviting}
|
||||
>
|
||||
{isInviting ? 'Sending...' : 'Send Invitation'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Join Requests Modal */}
|
||||
{showJoinRequestsModal && (
|
||||
<div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[80vh] overflow-y-auto">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900">
|
||||
Join Requests ({pendingJoinRequests.length})
|
||||
</h2>
|
||||
<button
|
||||
onClick={() => setShowJoinRequestsModal(false)}
|
||||
className="text-gray-400 hover:text-gray-600 text-2xl"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{pendingJoinRequests.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-gray-600 text-lg">No pending join requests</p>
|
||||
<p className="text-gray-500 text-sm mt-2">
|
||||
When users request to join your team, they'll appear here
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{pendingJoinRequests.map((request: any) => (
|
||||
<div key={request.id} className="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-start space-x-3 flex-1">
|
||||
{request.user?.avatar ? (
|
||||
<img
|
||||
src={request.user.avatar}
|
||||
alt={request.user.fullname}
|
||||
className="w-12 h-12 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center shrink-0">
|
||||
<span className="text-gray-500 text-xl">👤</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<p className="font-semibold text-gray-900">
|
||||
{request.user?.fullname || 'Unknown User'}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{request.user?.email}
|
||||
</p>
|
||||
{request.message && (
|
||||
<div className="mt-2 bg-gray-50 rounded-lg p-3">
|
||||
<p className="text-sm text-gray-700">
|
||||
<strong>Message:</strong> {request.message}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-gray-500 mt-2">
|
||||
Requested {new Date(request.created_at).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex space-x-2 ml-4">
|
||||
<Button
|
||||
onClick={() => handleRespondToJoinRequest(request.id, 'approve')}
|
||||
disabled={isResponding || members.length >= MAX_TEAM_MEMBERS}
|
||||
className="px-4 py-2 text-sm"
|
||||
>
|
||||
✓ Accept
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleRespondToJoinRequest(request.id, 'reject')}
|
||||
disabled={isResponding}
|
||||
variant="secondary"
|
||||
className="px-4 py-2 text-sm"
|
||||
>
|
||||
✕ Reject
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{members.length >= MAX_TEAM_MEMBERS && (
|
||||
<div className="mt-3 bg-yellow-50 border border-yellow-200 rounded-lg p-2">
|
||||
<p className="text-xs text-yellow-800">
|
||||
Team is full ({MAX_TEAM_MEMBERS}/{MAX_TEAM_MEMBERS} members). Remove a member before accepting new requests.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TeamDashboardPage;
|
||||
@@ -0,0 +1,207 @@
|
||||
import { FC, ReactElement } from 'react';
|
||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { useTeamById, useTeamSubmission } from '@imphnen-frontend-service/service';
|
||||
|
||||
const SubmissionViewPage: FC = (): ReactElement => {
|
||||
const { teamId } = useParams<{ teamId: string }>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: teamData } = useTeamById(teamId || '');
|
||||
const { data: submissionData, isLoading } = useTeamSubmission(teamId || '', !!teamId);
|
||||
|
||||
const team = teamData?.data;
|
||||
const submission = submissionData?.data;
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-gray-600">Loading submission...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!submission) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<div className="text-6xl mb-4">📄</div>
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">No Submission Yet</h2>
|
||||
<p className="text-gray-600 mb-4">Your team hasn't submitted a project</p>
|
||||
<Button onClick={() => navigate(`/teams/${teamId}`)}>Back to Team</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const submittedDate = submission.submitted_at
|
||||
? new Date(submission.submitted_at).toLocaleString('id-ID', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
: 'Not submitted';
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="bg-white border-b">
|
||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Project Submission</h1>
|
||||
<p className="text-gray-600 mt-1">{team?.name}</p>
|
||||
</div>
|
||||
<Button variant="secondary" onClick={() => navigate(`/teams/${teamId}`)}>
|
||||
Back to Team
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
{/* Status Banner */}
|
||||
<div className="bg-green-50 border border-green-500 rounded-lg p-6 mb-6">
|
||||
<div className="flex items-center space-x-3">
|
||||
<span className="text-4xl">✅</span>
|
||||
<div>
|
||||
<h3 className="font-bold text-green-900 text-lg">Project Submitted Successfully</h3>
|
||||
<p className="text-green-700 text-sm">
|
||||
Submitted on {submittedDate}
|
||||
</p>
|
||||
<p className="text-green-600 text-xs mt-1">
|
||||
This submission is now read-only and cannot be edited
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{/* Project Header */}
|
||||
<div className="bg-gradient-to-r from-blue-600 to-blue-800 text-white p-8">
|
||||
<h2 className="text-3xl font-bold mb-2">{submission.project_name}</h2>
|
||||
<p className="text-blue-100">Team: {team?.name}</p>
|
||||
</div>
|
||||
|
||||
{/* Project Details */}
|
||||
<div className="p-8 space-y-6">
|
||||
{/* Description */}
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-3">Project Description</h3>
|
||||
<div className="bg-gray-50 rounded-lg p-4">
|
||||
<p className="text-gray-700 whitespace-pre-wrap">{submission.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Links */}
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Repository */}
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-3">Repository</h3>
|
||||
<a
|
||||
href={submission.repository_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center space-x-2 text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
<span>🔗</span>
|
||||
<span className="break-all">{submission.repository_url}</span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Demo URL */}
|
||||
{submission.demo_url && (
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-3">Live Demo</h3>
|
||||
<a
|
||||
href={submission.demo_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center space-x-2 text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
<span>🌐</span>
|
||||
<span className="break-all">{submission.demo_url}</span>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Presentation URL */}
|
||||
{submission.presentation_url && (
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-3">Presentation</h3>
|
||||
<a
|
||||
href={submission.presentation_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center space-x-2 text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
<span>📊</span>
|
||||
<span className="break-all">{submission.presentation_url}</span>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Screenshots */}
|
||||
{submission.screenshots && submission.screenshots.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-3">
|
||||
Screenshots ({submission.screenshots.length})
|
||||
</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{submission.screenshots.map((url, index) => (
|
||||
<a
|
||||
key={index}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block"
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt={`Screenshot ${index + 1}`}
|
||||
className="w-full h-48 object-cover rounded-lg border-2 border-gray-200 hover:border-blue-500 transition-colors cursor-pointer"
|
||||
/>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Submission Info */}
|
||||
<div className="bg-gray-50 rounded-lg p-4 border-t-4 border-blue-600">
|
||||
<h3 className="text-sm font-bold text-gray-900 mb-2">Submission Information</h3>
|
||||
<div className="grid gap-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Status:</span>
|
||||
<span className="font-medium text-green-600">
|
||||
{submission.status === 'submitted' ? '✓ Submitted' : 'Draft'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Submitted:</span>
|
||||
<span className="font-medium text-gray-900">{submittedDate}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-600">Submission ID:</span>
|
||||
<span className="font-medium text-gray-900 font-mono text-xs">
|
||||
{submission.id}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Read-only Notice */}
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
|
||||
<p className="text-sm text-yellow-800">
|
||||
<strong>Note:</strong> This submission is now locked and cannot be edited or deleted.
|
||||
If you need to make changes, please contact the hackathon organizers.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SubmissionViewPage;
|
||||
@@ -0,0 +1,296 @@
|
||||
import { FC, ReactElement, useState } from 'react';
|
||||
import { ControlledInputField } from '@imphnen-frontend-service/ui/organisms';
|
||||
import { Button, Textarea } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate, useParams } from 'react-router';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import {
|
||||
projectSubmissionSchema,
|
||||
TProjectSubmissionForm,
|
||||
useSubmitProject,
|
||||
useTeamById,
|
||||
useTeamSubmission,
|
||||
useUploadFile,
|
||||
} from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
const SubmitProjectPage: FC = (): ReactElement => {
|
||||
const { teamId } = useParams<{ teamId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { session } = useAuthStore();
|
||||
const [showConfirmModal, setShowConfirmModal] = useState(false);
|
||||
const [screenshots, setScreenshots] = useState<string[]>([]);
|
||||
|
||||
const { data: teamData } = useTeamById(teamId || '');
|
||||
const { data: submissionData } = useTeamSubmission(teamId || '', !!teamId);
|
||||
const { mutateAsync: submitProject, isPending: isSubmitting } = useSubmitProject(teamId || '');
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const team = teamData?.data;
|
||||
const currentUserId = session?.user?.id;
|
||||
const isLeader = currentUserId === team?.leader_id;
|
||||
const hasSubmission = !!submissionData?.data;
|
||||
|
||||
const form = useForm<TProjectSubmissionForm>({
|
||||
resolver: zodResolver(projectSubmissionSchema),
|
||||
mode: 'all',
|
||||
});
|
||||
|
||||
if (!isLeader) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Access Denied</h2>
|
||||
<p className="text-gray-600 mb-4">Only the team leader can submit projects</p>
|
||||
<Button onClick={() => navigate(`/teams/${teamId}`)}>Back to Team</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (hasSubmission) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<div className="text-6xl mb-4">✅</div>
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">Project Already Submitted</h2>
|
||||
<p className="text-gray-600 mb-4">Your team has already submitted a project</p>
|
||||
<div className="flex space-x-3">
|
||||
<Button onClick={() => navigate(`/teams/${teamId}/submission`)}>
|
||||
View Submission
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate(`/teams/${teamId}`)}>
|
||||
Back to Team
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleScreenshotUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files;
|
||||
if (!files) return;
|
||||
|
||||
try {
|
||||
const uploadPromises = Array.from(files).map(file => uploadFile(file));
|
||||
const results = await Promise.all(uploadPromises);
|
||||
const urls = results.map(r => r.data.url);
|
||||
setScreenshots([...screenshots, ...urls]);
|
||||
} catch (error) {
|
||||
console.error('Failed to upload screenshots:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const removeScreenshot = (index: number) => {
|
||||
setScreenshots(screenshots.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const onSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
await submitProject({
|
||||
...data,
|
||||
screenshots,
|
||||
});
|
||||
navigate(`/teams/${teamId}/submission`);
|
||||
} catch (error) {
|
||||
console.error('Failed to submit project:', error);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="bg-white border-b">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<h1 className="text-3xl font-bold text-gray-900">Submit Project</h1>
|
||||
<p className="text-gray-600 mt-1">{team?.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
{/* Warning Banner */}
|
||||
<div className="bg-red-50 border-2 border-red-500 rounded-lg p-6 mb-6">
|
||||
<div className="flex items-start space-x-3">
|
||||
<span className="text-3xl">⚠️</span>
|
||||
<div>
|
||||
<h3 className="font-bold text-red-900 text-lg">IMPORTANT WARNING</h3>
|
||||
<ul className="text-red-800 mt-2 space-y-1 text-sm">
|
||||
<li>• You can only submit your project ONCE</li>
|
||||
<li>• After submission, you CANNOT edit or change anything</li>
|
||||
<li>• Make sure all information is correct before submitting</li>
|
||||
<li>• Review your project details carefully</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg shadow-md p-8">
|
||||
<form onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setShowConfirmModal(true);
|
||||
}} className="space-y-6">
|
||||
{/* Project Name */}
|
||||
<ControlledInputField
|
||||
control={form.control}
|
||||
label="Project Name"
|
||||
placeholder="Enter your project name"
|
||||
name="project_name"
|
||||
/>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Project Description <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<Textarea
|
||||
{...field}
|
||||
placeholder="Describe your project, its features, and what problem it solves..."
|
||||
rows={6}
|
||||
className="w-full"
|
||||
/>
|
||||
{fieldState.error && (
|
||||
<p className="text-sm text-red-500 mt-1">{fieldState.error.message}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Repository URL */}
|
||||
<ControlledInputField
|
||||
control={form.control}
|
||||
label="Repository URL (GitHub, GitLab, etc.)"
|
||||
placeholder="https://github.com/username/project"
|
||||
name="repository_url"
|
||||
type="url"
|
||||
/>
|
||||
|
||||
{/* Demo URL */}
|
||||
<ControlledInputField
|
||||
control={form.control}
|
||||
label="Demo URL (Optional)"
|
||||
placeholder="https://your-project-demo.com"
|
||||
name="demo_url"
|
||||
type="url"
|
||||
/>
|
||||
|
||||
{/* Presentation URL */}
|
||||
<ControlledInputField
|
||||
control={form.control}
|
||||
label="Presentation URL (Optional)"
|
||||
placeholder="https://slides.com/your-presentation or Google Drive link"
|
||||
name="presentation_url"
|
||||
type="url"
|
||||
/>
|
||||
|
||||
{/* Screenshots */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Project Screenshots <span className="text-gray-400">(Optional)</span>
|
||||
</label>
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 gap-4 mb-4">
|
||||
{screenshots.map((url, index) => (
|
||||
<div key={index} className="relative">
|
||||
<img
|
||||
src={url}
|
||||
alt={`Screenshot ${index + 1}`}
|
||||
className="w-full h-32 object-cover rounded-lg border-2 border-gray-200"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeScreenshot(index)}
|
||||
className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm hover:bg-red-600"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<label className="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
|
||||
<div className="text-center">
|
||||
<p className="text-gray-500">Click to upload screenshots</p>
|
||||
<p className="text-xs text-gray-400 mt-1">PNG, JPG up to 5MB each</p>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleScreenshotUpload}
|
||||
disabled={isUploading}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="flex space-x-3 pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => navigate(`/teams/${teamId}`)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="flex-1"
|
||||
disabled={!form.formState.isValid || isUploading}
|
||||
>
|
||||
Review & Submit
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Confirmation Modal */}
|
||||
{showConfirmModal && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||
<div className="text-center mb-6">
|
||||
<div className="text-5xl mb-4">⚠️</div>
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-2">
|
||||
Final Confirmation
|
||||
</h2>
|
||||
<p className="text-red-600 font-medium">
|
||||
This action is IRREVERSIBLE!
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 mb-6">
|
||||
<p className="text-sm text-gray-700 mb-3">
|
||||
By clicking "Submit Project", you confirm that:
|
||||
</p>
|
||||
<ul className="text-sm text-gray-600 space-y-2">
|
||||
<li>✓ All information is correct and complete</li>
|
||||
<li>✓ You understand this can only be done once</li>
|
||||
<li>✓ You cannot edit after submission</li>
|
||||
<li>✓ Your team agrees with this submission</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="flex space-x-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => setShowConfirmModal(false)}
|
||||
>
|
||||
Go Back
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onSubmit}
|
||||
className="flex-1 bg-red-600 hover:bg-red-700"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Submitting...' : 'Submit Project'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SubmitProjectPage;
|
||||
@@ -0,0 +1,233 @@
|
||||
import { FC, ReactElement, useState } from 'react';
|
||||
import { Button, Input } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { useTeams, useJoinTeam, useMyTeams, ETeamVisibility, joinTeamSchema, TJoinTeamForm } from '@imphnen-frontend-service/service';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
const INDONESIAN_CITIES = [
|
||||
'All Cities', 'Jakarta', 'Surabaya', 'Bandung', 'Medan', 'Semarang',
|
||||
'Makassar', 'Palembang', 'Tangerang', 'Depok', 'Bekasi',
|
||||
'Yogyakarta', 'Malang', 'Bogor', 'Batam', 'Pekanbaru',
|
||||
];
|
||||
|
||||
const BrowseTeamsPage: FC = (): ReactElement => {
|
||||
const navigate = useNavigate();
|
||||
const [search, setSearch] = useState('');
|
||||
const [selectedCity, setSelectedCity] = useState('All Cities');
|
||||
const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
|
||||
const [showJoinModal, setShowJoinModal] = useState(false);
|
||||
|
||||
const { data: teamsData, isLoading } = useTeams({
|
||||
search,
|
||||
city: selectedCity === 'All Cities' ? undefined : selectedCity,
|
||||
visibility: ETeamVisibility.PUBLIC,
|
||||
});
|
||||
|
||||
const { data: myTeamsData } = useMyTeams();
|
||||
const { mutateAsync: joinTeam, isPending: isJoining } = useJoinTeam();
|
||||
|
||||
const form = useForm<TJoinTeamForm>({
|
||||
resolver: zodResolver(joinTeamSchema),
|
||||
mode: 'all',
|
||||
});
|
||||
|
||||
const teams = teamsData?.data || [];
|
||||
const myTeams = myTeamsData?.data || [];
|
||||
|
||||
// Helper function to check if user is a member of a team
|
||||
const isMyTeam = (teamId: string) => {
|
||||
return myTeams.some((team: any) => team.id === teamId);
|
||||
};
|
||||
|
||||
const handleJoinRequest = (teamId: string) => {
|
||||
setSelectedTeamId(teamId);
|
||||
setShowJoinModal(true);
|
||||
};
|
||||
|
||||
const onSubmit = form.handleSubmit(async (data) => {
|
||||
if (!selectedTeamId) return;
|
||||
|
||||
try {
|
||||
await joinTeam({ teamId: selectedTeamId, data });
|
||||
setShowJoinModal(false);
|
||||
form.reset();
|
||||
setSelectedTeamId(null);
|
||||
} catch (error) {
|
||||
console.error('Failed to send join request:', error);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Header */}
|
||||
<div className="bg-white border-b">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-gray-900">Browse Teams</h1>
|
||||
<p className="text-gray-600 mt-1">Find and join teams looking for members</p>
|
||||
</div>
|
||||
<Link to="/dashboard">
|
||||
<Button variant="secondary">Back to Dashboard</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<div className="bg-white p-6 rounded-lg shadow-sm mb-6">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Search Teams
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search by team name..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Filter by City
|
||||
</label>
|
||||
<select
|
||||
value={selectedCity}
|
||||
onChange={(e) => setSelectedCity(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
{INDONESIAN_CITIES.map((city) => (
|
||||
<option key={city} value={city}>
|
||||
{city}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Teams List */}
|
||||
{isLoading ? (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-gray-600">Loading teams...</p>
|
||||
</div>
|
||||
) : teams.length === 0 ? (
|
||||
<div className="bg-white rounded-lg shadow-sm p-12 text-center">
|
||||
<p className="text-gray-600 text-lg">No teams found</p>
|
||||
<p className="text-gray-500 mt-2">Try adjusting your filters</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{teams.map((team) => (
|
||||
<div key={team.id} className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow">
|
||||
{team.banner && (
|
||||
<img
|
||||
src={team.banner}
|
||||
alt={team.name}
|
||||
className="w-full h-32 object-cover"
|
||||
/>
|
||||
)}
|
||||
<div className="p-6">
|
||||
<div className="flex items-center space-x-3 mb-3">
|
||||
{team.logo ? (
|
||||
<img
|
||||
src={team.logo}
|
||||
alt={team.name}
|
||||
className="w-12 h-12 rounded-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-500 text-xl">👥</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-bold text-gray-900">{team.name}</h3>
|
||||
<p className="text-sm text-gray-600">📍 {team.city}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-gray-600 text-sm mb-4 line-clamp-3">
|
||||
{team.description}
|
||||
</p>
|
||||
{isMyTeam(team.id) ? (
|
||||
<Button
|
||||
className="w-full"
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/teams/${team.id}`)}
|
||||
>
|
||||
Your Team
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => handleJoinRequest(team.id)}
|
||||
>
|
||||
Request to Join
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Join Request Modal */}
|
||||
{showJoinModal && (
|
||||
<div className="fixed inset-0 bg-black/30 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
Request to Join Team
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-6">
|
||||
Send a message to the team leader explaining why you want to join
|
||||
</p>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Your Message
|
||||
</label>
|
||||
<textarea
|
||||
{...form.register('message')}
|
||||
rows={4}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
placeholder="Tell the team leader why you want to join their team..."
|
||||
/>
|
||||
{form.formState.errors.message && (
|
||||
<p className="text-sm text-red-500 mt-1">
|
||||
{form.formState.errors.message.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex space-x-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => {
|
||||
setShowJoinModal(false);
|
||||
form.reset();
|
||||
setSelectedTeamId(null);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="flex-1"
|
||||
disabled={!form.formState.isValid || isJoining}
|
||||
>
|
||||
{isJoining ? 'Sending...' : 'Send Request'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BrowseTeamsPage;
|
||||
@@ -0,0 +1,322 @@
|
||||
import { FC, ReactElement, useState } from 'react';
|
||||
import { ControlledInputField } from '@imphnen-frontend-service/ui/organisms';
|
||||
import { Button, Textarea } from '@imphnen-frontend-service/ui/atoms';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { teamCreateSchema, TTeamCreateForm, useCreateTeam, ETeamVisibility, useUploadFile } from '@imphnen-frontend-service/service';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
|
||||
const INDONESIAN_CITIES = [
|
||||
'Jakarta', 'Surabaya', 'Bandung', 'Medan', 'Semarang',
|
||||
'Makassar', 'Palembang', 'Tangerang', 'Depok', 'Bekasi',
|
||||
'Yogyakarta', 'Malang', 'Bogor', 'Batam', 'Pekanbaru',
|
||||
];
|
||||
|
||||
const CreateTeamPage: FC = (): ReactElement => {
|
||||
const navigate = useNavigate();
|
||||
const [logoFile, setLogoFile] = useState<File | null>(null);
|
||||
const [logoPreview, setLogoPreview] = useState<string>('');
|
||||
const [bannerFile, setBannerFile] = useState<File | null>(null);
|
||||
const [bannerPreview, setBannerPreview] = useState<string>('');
|
||||
|
||||
const form = useForm<TTeamCreateForm>({
|
||||
resolver: zodResolver(teamCreateSchema),
|
||||
mode: 'all',
|
||||
defaultValues: {
|
||||
visibility: ETeamVisibility.PUBLIC,
|
||||
logo: null,
|
||||
banner: null,
|
||||
},
|
||||
});
|
||||
|
||||
const { mutateAsync: createTeam, isPending: isCreating } = useCreateTeam();
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setLogoFile(file);
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
setLogoPreview(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBannerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setBannerFile(file);
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
setBannerPreview(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = form.handleSubmit(async (data) => {
|
||||
try {
|
||||
let logoUrl = null;
|
||||
let bannerUrl = null;
|
||||
|
||||
if (logoFile) {
|
||||
const logoResult = await uploadFile(logoFile);
|
||||
logoUrl = logoResult.data.url;
|
||||
}
|
||||
|
||||
if (bannerFile) {
|
||||
const bannerResult = await uploadFile(bannerFile);
|
||||
bannerUrl = bannerResult.data.url;
|
||||
}
|
||||
|
||||
const result = await createTeam({
|
||||
...data,
|
||||
logo: logoUrl,
|
||||
banner: bannerUrl,
|
||||
});
|
||||
|
||||
navigate(`/teams/${result.data.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create team:', error);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
{/* Header */}
|
||||
<div className="bg-white border-b">
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||
<h1 className="text-3xl font-bold text-gray-900">Create Your Team</h1>
|
||||
<p className="text-gray-600 mt-1">Build your hackathon dream team</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||
<div className="bg-white rounded-lg shadow-md p-8">
|
||||
<form onSubmit={onSubmit} className="space-y-6">
|
||||
{/* Banner Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Team Banner <span className="text-gray-400">(Optional)</span>
|
||||
</label>
|
||||
{bannerPreview ? (
|
||||
<div className="relative">
|
||||
<img
|
||||
src={bannerPreview}
|
||||
alt="Banner preview"
|
||||
className="w-full h-48 object-cover rounded-lg border-2 border-gray-200"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setBannerFile(null);
|
||||
setBannerPreview('');
|
||||
}}
|
||||
className="absolute top-2 right-2 bg-red-500 text-white px-3 py-1 rounded-lg text-sm hover:bg-red-600"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
|
||||
<div className="text-center">
|
||||
<p className="text-gray-500">Click to upload banner</p>
|
||||
<p className="text-xs text-gray-400 mt-1">1200x400 recommended</p>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleBannerChange}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Logo Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Team Logo <span className="text-gray-400">(Optional, but highly recommended)</span>
|
||||
</label>
|
||||
<div className="flex items-center space-x-4">
|
||||
{logoPreview ? (
|
||||
<img
|
||||
src={logoPreview}
|
||||
alt="Logo preview"
|
||||
className="w-24 h-24 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-24 h-24 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-400 text-3xl">👥</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="logo" className="cursor-pointer">
|
||||
<span className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 inline-block">
|
||||
{logoPreview ? 'Change Logo' : 'Upload Logo'}
|
||||
</span>
|
||||
<input
|
||||
id="logo"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={handleLogoChange}
|
||||
/>
|
||||
</label>
|
||||
{logoPreview && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setLogoFile(null);
|
||||
setLogoPreview('');
|
||||
}}
|
||||
className="ml-3 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Team Name */}
|
||||
<ControlledInputField
|
||||
control={form.control}
|
||||
label="Team Name"
|
||||
placeholder="Enter your team name"
|
||||
name="name"
|
||||
/>
|
||||
|
||||
{/* City */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
City <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="city"
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<select
|
||||
{...field}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
>
|
||||
<option value="">Select city</option>
|
||||
{INDONESIAN_CITIES.map((city) => (
|
||||
<option key={city} value={city}>
|
||||
{city}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldState.error && (
|
||||
<p className="text-sm text-red-500 mt-1">{fieldState.error.message}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Description <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field, fieldState }) => (
|
||||
<div>
|
||||
<Textarea
|
||||
{...field}
|
||||
placeholder="Tell others about your team, what you're looking for, your goals..."
|
||||
rows={4}
|
||||
className="w-full"
|
||||
/>
|
||||
{fieldState.error && (
|
||||
<p className="text-sm text-red-500 mt-1">{fieldState.error.message}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Visibility */}
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Team Visibility <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name="visibility"
|
||||
render={({ field }) => (
|
||||
<div className="space-y-3">
|
||||
<label className="flex items-start space-x-3 cursor-pointer border rounded-lg p-4 hover:bg-gray-50">
|
||||
<input
|
||||
type="radio"
|
||||
{...field}
|
||||
value={ETeamVisibility.PUBLIC}
|
||||
checked={field.value === ETeamVisibility.PUBLIC}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">Public</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
Team will be visible in Browse Teams. Anyone can request to join.
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
<label className="flex items-start space-x-3 cursor-pointer border rounded-lg p-4 hover:bg-gray-50">
|
||||
<input
|
||||
type="radio"
|
||||
{...field}
|
||||
value={ETeamVisibility.PRIVATE}
|
||||
checked={field.value === ETeamVisibility.PRIVATE}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">Private</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
Team is hidden from Browse Teams. Members can only join via invitation.
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Warning */}
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
|
||||
<p className="text-sm text-yellow-800">
|
||||
<strong>Note:</strong> As team leader, you cannot leave or join another team after creating this team.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="flex space-x-3 pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => navigate('/dashboard')}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
className="flex-1"
|
||||
disabled={!form.formState.isValid || isCreating || isUploading}
|
||||
>
|
||||
{isCreating || isUploading ? 'Creating Team...' : 'Create Team'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateTeamPage;
|
||||
@@ -0,0 +1,144 @@
|
||||
import { FC, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router';
|
||||
import { useUserMe, useMyTeams } from '@imphnen-frontend-service/service';
|
||||
import { useSession } from '@imphnen-frontend-service/utils';
|
||||
|
||||
export const Navigation: FC = () => {
|
||||
const navigate = useNavigate();
|
||||
const [showUserMenu, setShowUserMenu] = useState(false);
|
||||
const { data: userData } = useUserMe();
|
||||
const { data: teamsData } = useMyTeams();
|
||||
const { signOut } = useSession();
|
||||
|
||||
const user = userData?.data;
|
||||
const myTeams = teamsData?.data || [];
|
||||
const hasTeam = myTeams.length > 0;
|
||||
|
||||
const handleLogout = async () => {
|
||||
await signOut();
|
||||
navigate('/auth/login');
|
||||
};
|
||||
|
||||
return (
|
||||
<nav className="bg-white border-b shadow-sm">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex justify-between items-center h-16">
|
||||
{/* Logo */}
|
||||
<Link to="/dashboard" className="flex items-center space-x-2">
|
||||
<span className="text-2xl">🏆</span>
|
||||
<span className="text-xl font-bold text-gray-900">Hackathon</span>
|
||||
</Link>
|
||||
|
||||
{/* Navigation Links */}
|
||||
<div className="hidden md:flex items-center space-x-6">
|
||||
<Link
|
||||
to="/dashboard"
|
||||
className="text-gray-700 hover:text-blue-600 font-medium transition-colors"
|
||||
>
|
||||
Dashboard
|
||||
</Link>
|
||||
<Link
|
||||
to="/teams/browse"
|
||||
className="text-gray-700 hover:text-blue-600 font-medium transition-colors"
|
||||
>
|
||||
Browse Teams
|
||||
</Link>
|
||||
{hasTeam && (
|
||||
<Link
|
||||
to={`/teams/${myTeams[0].id}`}
|
||||
className="text-gray-700 hover:text-blue-600 font-medium transition-colors"
|
||||
>
|
||||
My Team
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* User Menu */}
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowUserMenu(!showUserMenu)}
|
||||
className="flex items-center space-x-3 focus:outline-none"
|
||||
>
|
||||
{user?.avatar ? (
|
||||
<img
|
||||
src={user.avatar}
|
||||
alt={user.fullname}
|
||||
className="w-10 h-10 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
|
||||
<span className="text-gray-500">👤</span>
|
||||
</div>
|
||||
)}
|
||||
<span className="hidden md:block text-gray-700 font-medium">
|
||||
{user?.fullname}
|
||||
</span>
|
||||
<svg
|
||||
className="w-4 h-4 text-gray-500"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Dropdown Menu */}
|
||||
{showUserMenu && (
|
||||
<div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50">
|
||||
<div className="px-4 py-2 border-b border-gray-200">
|
||||
<p className="text-sm font-medium text-gray-900">{user?.fullname}</p>
|
||||
<p className="text-xs text-gray-600 truncate">{user?.email}</p>
|
||||
</div>
|
||||
<Link
|
||||
to="/dashboard"
|
||||
className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
|
||||
onClick={() => setShowUserMenu(false)}
|
||||
>
|
||||
Dashboard
|
||||
</Link>
|
||||
<Link
|
||||
to="/teams/browse"
|
||||
className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
|
||||
onClick={() => setShowUserMenu(false)}
|
||||
>
|
||||
Browse Teams
|
||||
</Link>
|
||||
{hasTeam && (
|
||||
<Link
|
||||
to={`/teams/${myTeams[0].id}`}
|
||||
className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
|
||||
onClick={() => setShowUserMenu(false)}
|
||||
>
|
||||
My Team
|
||||
</Link>
|
||||
)}
|
||||
<div className="border-t border-gray-200 mt-2 pt-2">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50"
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Close dropdown when clicking outside */}
|
||||
{showUserMenu && (
|
||||
<div
|
||||
className="fixed inset-0 z-40"
|
||||
onClick={() => setShowUserMenu(false)}
|
||||
/>
|
||||
)}
|
||||
</nav>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useTeamById, useTeamMembers, useUserMe, useTeamSubmission } from '@imphnen-frontend-service/service';
|
||||
|
||||
/**
|
||||
* Hook to check if current user is a member of the team
|
||||
*/
|
||||
export const useTeamMembership = (teamId: string) => {
|
||||
const { data: userData } = useUserMe();
|
||||
const { data: membersData } = useTeamMembers(teamId);
|
||||
|
||||
const currentUser = userData?.data;
|
||||
const members = membersData?.data || [];
|
||||
|
||||
const isMember = members.some(m => m.user_id === currentUser?.id);
|
||||
const currentMember = members.find(m => m.user_id === currentUser?.id);
|
||||
|
||||
return {
|
||||
isMember,
|
||||
currentMember,
|
||||
memberRole: currentMember?.role,
|
||||
memberStatus: currentMember?.status,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to check if current user is the team leader
|
||||
*/
|
||||
export const useIsTeamLeader = (teamId: string) => {
|
||||
const { data: teamData } = useTeamById(teamId);
|
||||
const { data: userData } = useUserMe();
|
||||
|
||||
const team = teamData?.data;
|
||||
const currentUser = userData?.data;
|
||||
|
||||
const isLeader = currentUser?.id === team?.leader_id;
|
||||
|
||||
return {
|
||||
isLeader,
|
||||
leaderId: team?.leader_id,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to get team submission status
|
||||
*/
|
||||
export const useTeamSubmissionStatus = (teamId: string) => {
|
||||
const { data: submissionData, isLoading } = useTeamSubmission(teamId, !!teamId);
|
||||
|
||||
const hasSubmission = !!submissionData?.data;
|
||||
const submission = submissionData?.data;
|
||||
const isSubmitted = submission?.status === 'submitted';
|
||||
|
||||
return {
|
||||
hasSubmission,
|
||||
isSubmitted,
|
||||
submission,
|
||||
isLoading,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to check if current user can perform team actions
|
||||
*/
|
||||
export const useTeamPermissions = (teamId: string) => {
|
||||
const { isLeader } = useIsTeamLeader(teamId);
|
||||
const { isMember } = useTeamMembership(teamId);
|
||||
const { hasSubmission } = useTeamSubmissionStatus(teamId);
|
||||
|
||||
return {
|
||||
canEditTeam: isLeader,
|
||||
canManageMembers: isLeader,
|
||||
canSubmitProject: isLeader && !hasSubmission,
|
||||
canViewTeam: isMember,
|
||||
canViewSubmission: isMember,
|
||||
canAccessChat: isMember,
|
||||
};
|
||||
};
|
||||
@@ -1 +1,136 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Bai+Jamjuree:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700&display=swap');
|
||||
@import 'tailwindcss';
|
||||
@source "../../../libs/ui/**/*.{ts,tsx}";
|
||||
|
||||
@theme {
|
||||
--color-primary-50: #f0f8ff;
|
||||
--color-primary-100: #e1f0fd;
|
||||
--color-primary-200: #bce1fb;
|
||||
--color-primary-300: #81cbf8;
|
||||
--color-primary-400: #3eb0f2;
|
||||
--color-primary-500: #23a1eb;
|
||||
--color-primary-600: #0877c1;
|
||||
--color-primary-700: #085f9c;
|
||||
--color-primary-800: #0b5181;
|
||||
--color-primary-900: #0f446b;
|
||||
--color-primary-950: #0a2b47;
|
||||
|
||||
--color-neutral-50: #f6f6f6;
|
||||
--color-neutral-100: #e7e7e7;
|
||||
--color-neutral-200: #d1d1d1;
|
||||
--color-neutral-300: #b0b0b0;
|
||||
--color-neutral-400: #888888;
|
||||
--color-neutral-500: #6d6d6d;
|
||||
--color-neutral-600: #5d5d5d;
|
||||
--color-neutral-700: #4f4f4f;
|
||||
--color-neutral-800: #454545;
|
||||
--color-neutral-900: #3d3d3d;
|
||||
--color-neutral-950: #2b2b2b;
|
||||
|
||||
--color-success-100: #e0fbd8;
|
||||
--color-success-200: #bcf8b0;
|
||||
--color-success-300: #8eea85;
|
||||
--color-success-400: #63d564;
|
||||
--color-success-500: #35ba43;
|
||||
--color-success-600: #269f3e;
|
||||
--color-success-700: #1a8439;
|
||||
--color-success-800: #106b32;
|
||||
--color-success-900: #0b592f;
|
||||
|
||||
--color-info-100: #ccfcfe;
|
||||
--color-info-200: #9bf3fd;
|
||||
--color-info-300: #67e3fb;
|
||||
--color-info-400: #42cdf8;
|
||||
--color-info-500: #04acf3;
|
||||
--color-info-600: #0185d0;
|
||||
--color-info-700: #0264af;
|
||||
--color-info-800: #01478d;
|
||||
--color-info-900: #003375;
|
||||
|
||||
--color-warning-100: #fffcd3;
|
||||
--color-warning-200: #fffaa9;
|
||||
--color-warning-300: #fff67d;
|
||||
--color-warning-400: #fff25d;
|
||||
--color-warning-500: #ffed27;
|
||||
--color-warning-600: #dbc91d;
|
||||
--color-warning-700: #b7a714;
|
||||
--color-warning-800: #93850b;
|
||||
--color-warning-900: #7a6d07;
|
||||
|
||||
--color-danger-100: #ffe8da;
|
||||
--color-danger-200: #ffcbb3;
|
||||
--color-danger-300: #ffaa8d;
|
||||
--color-danger-400: #ff8870;
|
||||
--color-danger-500: #ff5242;
|
||||
--color-danger-600: #da3030;
|
||||
--color-danger-700: #b7212d;
|
||||
--color-danger-800: #93152a;
|
||||
--color-danger-900: #7a0c27;
|
||||
|
||||
--radius-none: 0px;
|
||||
--radius-sm: 2px;
|
||||
--radius-md: 4px;
|
||||
--radius-lg: 8px;
|
||||
--radius-xl: 12px;
|
||||
--radius-2xl: 16px;
|
||||
--radius-3xl: 24px;
|
||||
--radius-full: 50%;
|
||||
|
||||
--font-bai-jamjuree: 'Bai Jamjuree', sans-serif;
|
||||
|
||||
--text-h1: 3.833rem;
|
||||
/* ~46px */
|
||||
--text-h2: 3.083rem;
|
||||
/* ~37px */
|
||||
--text-h3: 2.417rem;
|
||||
/* ~29px */
|
||||
--text-p1: 1.917rem;
|
||||
/* ~23px */
|
||||
--text-p2: 1.583rem;
|
||||
/* ~19px */
|
||||
--text-p3: 1.25rem;
|
||||
/* 15px */
|
||||
--text-label1: 1rem;
|
||||
/* 12px */
|
||||
--text-label2: 0.833rem;
|
||||
/* ~10px */
|
||||
--text-label3: 0.677rem;
|
||||
/* ~8px */
|
||||
}
|
||||
|
||||
@layer base {
|
||||
|
||||
*,
|
||||
::after,
|
||||
::before,
|
||||
::backdrop,
|
||||
::file-selector-button {
|
||||
border-color: var(--color-neutral-200, currentColor);
|
||||
}
|
||||
|
||||
/* Custom scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--color-neutral-50);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #cccccc;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--color-neutral-300);
|
||||
}
|
||||
|
||||
html {
|
||||
font-family: 'Bai Jamjuree', sans-serif;
|
||||
font-weight: 400;
|
||||
font-size: 12px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { middleware } from './middleware';
|
||||
import { StrictMode } from 'react';
|
||||
import { createBrowserRouter, RouteObject, RouterProvider } from 'react-router';
|
||||
import {
|
||||
@@ -24,8 +23,10 @@ add404PageToRoutesChildren(notFoundFiles, routes);
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
...routes,
|
||||
loader: middleware,
|
||||
shouldRevalidate: () => true,
|
||||
// MIDDLEWARE TEMPORARILY DISABLED - causing infinite loops with React Router v7
|
||||
// TODO: Implement auth checks at component level or use different pattern
|
||||
// loader: middleware,
|
||||
// shouldRevalidate: () => false,
|
||||
},
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,45 +1,128 @@
|
||||
import {
|
||||
PERMISSIONS,
|
||||
SessionToken,
|
||||
SessionUser,
|
||||
} from '@imphnen-frontend-service/utils';
|
||||
import { SessionUser } from '@imphnen-frontend-service/utils';
|
||||
import { supabase } from '@imphnen-frontend-service/service';
|
||||
import { LoaderFunctionArgs, redirect } from 'react-router';
|
||||
|
||||
const mappingPublicRoutes = [
|
||||
'/',
|
||||
];
|
||||
|
||||
const mappingOnboardingRoutes = [
|
||||
'/onboarding/user',
|
||||
];
|
||||
|
||||
const mappingRoutePermissions = [
|
||||
{
|
||||
path: '/dashboard',
|
||||
permissions: [],
|
||||
},
|
||||
{
|
||||
path: '/teams/browse',
|
||||
permissions: [],
|
||||
},
|
||||
{
|
||||
path: '/teams/create',
|
||||
permissions: [],
|
||||
},
|
||||
];
|
||||
|
||||
const mappingPublicPrefixRoutes = [
|
||||
'/hackathons',
|
||||
];
|
||||
|
||||
// Cache to prevent redundant checks (cache for 5 seconds)
|
||||
const onboardingCache = new Map<string, { hasLocation: boolean; timestamp: number }>();
|
||||
const CACHE_DURATION = 5000; // 5 seconds
|
||||
|
||||
export const middleware = async ({ request }: LoaderFunctionArgs) => {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
const session = SessionUser.get();
|
||||
const session_token = SessionToken.get();
|
||||
const token = session_token?.token?.access_token;
|
||||
const userPermissions =
|
||||
session?.role?.permissions?.map?.((perm) => perm?.name) ?? [];
|
||||
|
||||
console.log('[Middleware] Checking route:', pathname);
|
||||
|
||||
// Get session from Supabase (authoritative source)
|
||||
const { data: { session: supabaseSession }, error: sessionError } = await supabase.auth.getSession();
|
||||
|
||||
// Handle session errors
|
||||
if (sessionError) {
|
||||
console.error('[Middleware] Session error:', sessionError);
|
||||
// Don't redirect on session errors, let the app handle it
|
||||
}
|
||||
|
||||
// Allow to access the hackathon pages without authentication
|
||||
if (mappingPublicPrefixRoutes.some((prefix) => pathname.startsWith(prefix))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Public routes - redirect to dashboard if already authenticated
|
||||
if (mappingPublicRoutes.includes(pathname)) {
|
||||
if (token) return redirect('/dashboard');
|
||||
if (supabaseSession) return redirect('/dashboard');
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!session) return redirect('/');
|
||||
// Auth callback - allow without authentication check (for OAuth callback)
|
||||
if (pathname === '/auth/callback') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Auth routes (all /auth/* paths) - redirect to dashboard if already authenticated
|
||||
if (pathname.startsWith('/auth')) {
|
||||
if (supabaseSession) return redirect('/dashboard');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Require authentication for all other routes - ONLY check Supabase session
|
||||
if (!supabaseSession) {
|
||||
return redirect('/auth/login');
|
||||
}
|
||||
|
||||
// Check if user has completed onboarding by querying database (not localStorage!)
|
||||
// Skip onboarding check for onboarding routes themselves
|
||||
if (!mappingOnboardingRoutes.includes(pathname)) {
|
||||
try {
|
||||
const userId = supabaseSession.user.id;
|
||||
const now = Date.now();
|
||||
|
||||
// Check cache first
|
||||
const cached = onboardingCache.get(userId);
|
||||
let hasLocation = false;
|
||||
|
||||
if (cached && (now - cached.timestamp) < CACHE_DURATION) {
|
||||
console.log('[Middleware] Using cached onboarding status');
|
||||
hasLocation = cached.hasLocation;
|
||||
} else {
|
||||
console.log('[Middleware] Fetching fresh onboarding status');
|
||||
const { data: userData, error: userError } = await supabase
|
||||
.from('users')
|
||||
.select('location')
|
||||
.eq('id', userId)
|
||||
.single();
|
||||
|
||||
if (userError) {
|
||||
console.error('[Middleware] Failed to fetch user data:', userError);
|
||||
// If we can't fetch user data, allow access (don't break the app)
|
||||
return null;
|
||||
}
|
||||
|
||||
hasLocation = !!userData?.location;
|
||||
|
||||
// Update cache
|
||||
onboardingCache.set(userId, { hasLocation, timestamp: now });
|
||||
}
|
||||
|
||||
if (!hasLocation) {
|
||||
return redirect('/onboarding/user');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Middleware] Unexpected error checking onboarding:', error);
|
||||
// On error, allow access (fail open)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Check route permissions using fresh user data from Zustand (for UI metadata)
|
||||
const session = SessionUser.get();
|
||||
const userPermissions =
|
||||
session?.role?.permissions?.map?.((perm) => perm?.name) ?? [];
|
||||
|
||||
const matchedRoute = mappingRoutePermissions.find(
|
||||
(route) => route.path === pathname
|
||||
@@ -51,7 +134,7 @@ export const middleware = async ({ request }: LoaderFunctionArgs) => {
|
||||
matchedRoute.permissions.some((perm) => userPermissions.includes(perm));
|
||||
|
||||
if (!hasPermission) {
|
||||
return '/dashboard';
|
||||
return redirect('/dashboard');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,15 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/hackathon.Dockerfile
|
||||
args:
|
||||
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
|
||||
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
|
||||
ports:
|
||||
- '127.0.0.1:3004:80'
|
||||
restart: unless-stopped
|
||||
container_name: hackathon
|
||||
env_file:
|
||||
- .env.local
|
||||
environment:
|
||||
- VITE_SUPABASE_URL=${VITE_SUPABASE_URL}
|
||||
- VITE_SUPABASE_ANON_KEY=${VITE_SUPABASE_ANON_KEY}
|
||||
|
||||
@@ -7,6 +7,15 @@ FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
|
||||
# Accept build arguments
|
||||
ARG VITE_SUPABASE_URL
|
||||
ARG VITE_SUPABASE_ANON_KEY
|
||||
|
||||
# Set environment variables for build
|
||||
ENV VITE_SUPABASE_URL=$VITE_SUPABASE_URL
|
||||
ENV VITE_SUPABASE_ANON_KEY=$VITE_SUPABASE_ANON_KEY
|
||||
|
||||
RUN npm run hackathon:build
|
||||
|
||||
FROM nginx:alpine AS runner
|
||||
|
||||
@@ -65,3 +65,16 @@ export const postGoogleCallback = async (code: string, state: string): Promise<T
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getGitHubAuthUrl = async (): Promise<string> => {
|
||||
const baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8080';
|
||||
return `${baseUrl}/auth/github/login`;
|
||||
};
|
||||
|
||||
export const postGitHubCallback = async (code: string, state: string): Promise<TGoogleCallbackResponse> => {
|
||||
const { data } = await api({
|
||||
method: 'GET',
|
||||
url: `/auth/github/callback?code=${code}&state=${state}`,
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { api } from '../index';
|
||||
import type {
|
||||
TCreateTeamRequest,
|
||||
TUpdateTeamRequest,
|
||||
TInviteMemberRequest,
|
||||
TJoinTeamRequest,
|
||||
TManageMemberRequest,
|
||||
TSubmitProjectRequest,
|
||||
TTeamListResponse,
|
||||
TTeamDetailResponse,
|
||||
TTeamMembersResponse,
|
||||
TTeamInvitationsResponse,
|
||||
TTeamJoinRequestsResponse,
|
||||
TProjectSubmissionResponse,
|
||||
} from '../../types/teams';
|
||||
|
||||
const TEAMS_BASE_URL = '/teams';
|
||||
|
||||
// Team CRUD
|
||||
export const getTeams = async (params?: {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
city?: string;
|
||||
visibility?: string;
|
||||
search?: string;
|
||||
}) => {
|
||||
const response = await api.get<TTeamListResponse>(TEAMS_BASE_URL, { params });
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const getTeamById = async (teamId: string) => {
|
||||
const response = await api.get<TTeamDetailResponse>(`${TEAMS_BASE_URL}/${teamId}`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const createTeam = async (data: TCreateTeamRequest) => {
|
||||
const response = await api.post<TTeamDetailResponse>(TEAMS_BASE_URL, data);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const updateTeam = async (teamId: string, data: TUpdateTeamRequest) => {
|
||||
const response = await api.put<TTeamDetailResponse>(`${TEAMS_BASE_URL}/${teamId}`, data);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// Team Members
|
||||
export const getTeamMembers = async (teamId: string) => {
|
||||
const response = await api.get<TTeamMembersResponse>(`${TEAMS_BASE_URL}/${teamId}/members`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const inviteMember = async (teamId: string, data: TInviteMemberRequest) => {
|
||||
const response = await api.post(`${TEAMS_BASE_URL}/${teamId}/invite`, data);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const manageMember = async (teamId: string, userId: string, data: TManageMemberRequest) => {
|
||||
const response = await api.put(`${TEAMS_BASE_URL}/${teamId}/members/${userId}`, data);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const removeMember = async (teamId: string, userId: string) => {
|
||||
const response = await api.delete(`${TEAMS_BASE_URL}/${teamId}/members/${userId}`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// Join Requests
|
||||
export const joinTeam = async (teamId: string, data: TJoinTeamRequest) => {
|
||||
const response = await api.post(`${TEAMS_BASE_URL}/${teamId}/join-request`, data);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const getTeamJoinRequests = async (teamId: string) => {
|
||||
const response = await api.get<TTeamJoinRequestsResponse>(`${TEAMS_BASE_URL}/${teamId}/join-requests`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const respondToJoinRequest = async (teamId: string, requestId: string, action: 'approve' | 'reject') => {
|
||||
const response = await api.put(`${TEAMS_BASE_URL}/${teamId}/join-requests/${requestId}`, { action });
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// Invitations
|
||||
export const getMyInvitations = async () => {
|
||||
const response = await api.get<TTeamInvitationsResponse>(`${TEAMS_BASE_URL}/invitations/me`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const respondToInvitation = async (invitationId: string, action: 'accept' | 'reject') => {
|
||||
const response = await api.put(`${TEAMS_BASE_URL}/invitations/${invitationId}`, { action });
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// User's Teams
|
||||
export const getMyTeams = async () => {
|
||||
const response = await api.get<TTeamListResponse>(`${TEAMS_BASE_URL}/me`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// Project Submission
|
||||
export const submitProject = async (teamId: string, data: TSubmitProjectRequest) => {
|
||||
const response = await api.post<TProjectSubmissionResponse>(`${TEAMS_BASE_URL}/${teamId}/submission`, data);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const getTeamSubmission = async (teamId: string) => {
|
||||
const response = await api.get<TProjectSubmissionResponse>(`${TEAMS_BASE_URL}/${teamId}/submission`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const leaveTeam = async (teamId: string) => {
|
||||
const response = await api.post(`${TEAMS_BASE_URL}/${teamId}/leave`);
|
||||
return response.data;
|
||||
};
|
||||
@@ -1,83 +1,72 @@
|
||||
import { useMutation, UseMutationResult } from '@tanstack/react-query';
|
||||
import { postLogin, postRegister, postSendOtp, postVerifyEmail, getGoogleAuthUrl, postGoogleCallback } from '../../api/auth';
|
||||
import {
|
||||
TLoginRequest,
|
||||
TLoginResponse,
|
||||
TRegisterRequest,
|
||||
TSendOTPRequest,
|
||||
TVerifyEmailRequest,
|
||||
TGoogleCallbackResponse,
|
||||
} from '../../types/auth';
|
||||
import { supabase } from '../../supabase';
|
||||
|
||||
import { TResponseError, TResponseMessage } from '../../types/common';
|
||||
|
||||
export const usePostLogin = (): UseMutationResult<
|
||||
TLoginResponse,
|
||||
TResponseError,
|
||||
TLoginRequest,
|
||||
unknown
|
||||
> => {
|
||||
return useMutation({
|
||||
mutationKey: ['post-login'],
|
||||
mutationFn: async (payload) => await postLogin(payload),
|
||||
// Supabase GitHub OAuth hook
|
||||
export const useGitHubAuth = () => {
|
||||
const signInWithGitHub = async () => {
|
||||
const { data, error } = await supabase.auth.signInWithOAuth({
|
||||
provider: 'github',
|
||||
options: {
|
||||
redirectTo: `${globalThis.location.origin}/auth/callback`,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const usePostRegister = (): UseMutationResult<
|
||||
TResponseMessage,
|
||||
TResponseError,
|
||||
TRegisterRequest,
|
||||
unknown
|
||||
> => {
|
||||
return useMutation({
|
||||
mutationKey: ['post-register'],
|
||||
mutationFn: async (payload) => await postRegister(payload),
|
||||
});
|
||||
};
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
export const usePostVerifyEmail = (): UseMutationResult<
|
||||
TResponseMessage,
|
||||
TResponseError,
|
||||
TVerifyEmailRequest,
|
||||
unknown
|
||||
> => {
|
||||
return useMutation({
|
||||
mutationKey: ['post-verify-email'],
|
||||
mutationFn: async (payload) => await postVerifyEmail(payload),
|
||||
});
|
||||
};
|
||||
|
||||
export const usePostSendOTP = (): UseMutationResult<
|
||||
TResponseMessage,
|
||||
TResponseError,
|
||||
TSendOTPRequest,
|
||||
unknown
|
||||
> => {
|
||||
return useMutation({
|
||||
mutationKey: ['post-send-otp'],
|
||||
mutationFn: async (payload) => await postSendOtp(payload),
|
||||
});
|
||||
};
|
||||
|
||||
export const useGoogleAuth = () => {
|
||||
const redirectToGoogle = async (): Promise<string> => {
|
||||
return await getGoogleAuthUrl();
|
||||
// Return the OAuth URL for debugging
|
||||
return data;
|
||||
};
|
||||
|
||||
return {
|
||||
redirectToGoogle,
|
||||
signInWithGitHub,
|
||||
};
|
||||
};
|
||||
|
||||
export const useGoogleCallback = (): UseMutationResult<
|
||||
TGoogleCallbackResponse,
|
||||
TResponseError,
|
||||
{ code: string; state: string },
|
||||
unknown
|
||||
> => {
|
||||
return useMutation({
|
||||
mutationKey: ['google-callback'],
|
||||
mutationFn: async ({ code, state }) => await postGoogleCallback(code, state),
|
||||
// Supabase Email/Password authentication hook
|
||||
export const useEmailAuth = () => {
|
||||
const signInWithEmail = async (email: string, password: string) => {
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
const signUpWithEmail = async (email: string, password: string, fullname: string) => {
|
||||
const { data, error } = await supabase.auth.signUp({
|
||||
email,
|
||||
password,
|
||||
options: {
|
||||
data: {
|
||||
full_name: fullname,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
const signOut = async () => {
|
||||
const { error } = await supabase.auth.signOut();
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
signInWithEmail,
|
||||
signUpWithEmail,
|
||||
signOut,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -3,3 +3,5 @@ export * from './gacha';
|
||||
export * from './users';
|
||||
export * from './mentors';
|
||||
export * from './upload';
|
||||
export * from './teams';
|
||||
export * from './messages';
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { supabase } from '../../supabase';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export type Message = {
|
||||
id: string;
|
||||
team_id: string;
|
||||
user_id: string;
|
||||
message: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user?: {
|
||||
id: string;
|
||||
fullname: string;
|
||||
avatar: string;
|
||||
email: string;
|
||||
};
|
||||
};
|
||||
|
||||
// Query keys
|
||||
export const messageKeys = {
|
||||
all: ['messages'] as const,
|
||||
team: (teamId: string) => [...messageKeys.all, 'team', teamId] as const,
|
||||
};
|
||||
|
||||
// Fetch messages for a team
|
||||
export const useTeamMessages = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: messageKeys.team(teamId),
|
||||
queryFn: async () => {
|
||||
const { data: messages, error } = await supabase
|
||||
.from('team_messages')
|
||||
.select(`
|
||||
id,
|
||||
team_id,
|
||||
user_id,
|
||||
message,
|
||||
created_at,
|
||||
updated_at,
|
||||
user:users(id, fullname, avatar, email)
|
||||
`)
|
||||
.eq('team_id', teamId)
|
||||
.order('created_at', { ascending: true });
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to fetch messages:', error);
|
||||
throw new Error(error.message || 'Failed to fetch messages');
|
||||
}
|
||||
|
||||
return messages as Message[];
|
||||
},
|
||||
enabled: !!teamId,
|
||||
});
|
||||
|
||||
// Subscribe to realtime updates
|
||||
useEffect(() => {
|
||||
if (!teamId) return;
|
||||
|
||||
const channel = supabase
|
||||
.channel(`team_messages:${teamId}`)
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{
|
||||
event: 'INSERT',
|
||||
schema: 'public',
|
||||
table: 'team_messages',
|
||||
filter: `team_id=eq.${teamId}`,
|
||||
},
|
||||
async (payload) => {
|
||||
console.log('[Realtime] New message:', payload);
|
||||
|
||||
// Fetch the full message with user data
|
||||
const { data: newMessage } = await supabase
|
||||
.from('team_messages')
|
||||
.select(`
|
||||
id,
|
||||
team_id,
|
||||
user_id,
|
||||
message,
|
||||
created_at,
|
||||
updated_at,
|
||||
user:users(id, fullname, avatar, email)
|
||||
`)
|
||||
.eq('id', payload.new.id)
|
||||
.single();
|
||||
|
||||
if (newMessage) {
|
||||
queryClient.setQueryData<Message[]>(
|
||||
messageKeys.team(teamId),
|
||||
(old) => [...(old || []), newMessage as Message]
|
||||
);
|
||||
}
|
||||
}
|
||||
)
|
||||
.on(
|
||||
'postgres_changes',
|
||||
{
|
||||
event: 'DELETE',
|
||||
schema: 'public',
|
||||
table: 'team_messages',
|
||||
filter: `team_id=eq.${teamId}`,
|
||||
},
|
||||
(payload) => {
|
||||
console.log('[Realtime] Message deleted:', payload);
|
||||
queryClient.setQueryData<Message[]>(
|
||||
messageKeys.team(teamId),
|
||||
(old) => old?.filter((msg) => msg.id !== payload.old.id) || []
|
||||
);
|
||||
}
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
return () => {
|
||||
supabase.removeChannel(channel);
|
||||
};
|
||||
}, [teamId, queryClient]);
|
||||
|
||||
return query;
|
||||
};
|
||||
|
||||
// Send a message
|
||||
export const useSendMessage = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (message: string) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to send messages');
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('team_messages')
|
||||
.insert({
|
||||
team_id: teamId,
|
||||
user_id: session.user.id,
|
||||
message,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
throw new Error(error.message || 'Failed to send message');
|
||||
}
|
||||
|
||||
return data;
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Realtime will handle adding the message to the list
|
||||
// But we can invalidate to ensure consistency
|
||||
queryClient.invalidateQueries({ queryKey: messageKeys.team(teamId) });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Delete a message
|
||||
export const useDeleteMessage = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (messageId: string) => {
|
||||
const { error } = await supabase
|
||||
.from('team_messages')
|
||||
.delete()
|
||||
.eq('id', messageId);
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to delete message:', error);
|
||||
throw new Error(error.message || 'Failed to delete message');
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Realtime will handle removing the message from the list
|
||||
queryClient.invalidateQueries({ queryKey: messageKeys.team(teamId) });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,692 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import * as teamsApi from '../../api/teams';
|
||||
import { supabase, getAuthenticatedClient } from '../../supabase';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
import type {
|
||||
TCreateTeamRequest,
|
||||
TUpdateTeamRequest,
|
||||
TInviteMemberRequest,
|
||||
TJoinTeamRequest,
|
||||
TSubmitProjectRequest,
|
||||
} from '../../types/teams';
|
||||
|
||||
// Query keys
|
||||
export const teamKeys = {
|
||||
all: ['teams'] as const,
|
||||
lists: () => [...teamKeys.all, 'list'] as const,
|
||||
list: (filters?: Record<string, unknown>) => [...teamKeys.lists(), filters] as const,
|
||||
details: () => [...teamKeys.all, 'detail'] as const,
|
||||
detail: (id: string) => [...teamKeys.details(), id] as const,
|
||||
members: (id: string) => [...teamKeys.detail(id), 'members'] as const,
|
||||
joinRequests: (id: string) => [...teamKeys.detail(id), 'join-requests'] as const,
|
||||
submission: (id: string) => [...teamKeys.detail(id), 'submission'] as const,
|
||||
myTeams: () => [...teamKeys.all, 'my-teams'] as const,
|
||||
myInvitations: () => [...teamKeys.all, 'my-invitations'] as const,
|
||||
};
|
||||
|
||||
// Team CRUD Hooks
|
||||
export const useTeams = (params?: {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
city?: string;
|
||||
visibility?: string;
|
||||
search?: string;
|
||||
}) => {
|
||||
return useQuery({
|
||||
queryKey: teamKeys.list(params),
|
||||
queryFn: async () => {
|
||||
try {
|
||||
// Supabase client now has auth context from setSession()
|
||||
let query = supabase.from('teams').select('*');
|
||||
|
||||
// Filter by visibility
|
||||
if (params?.visibility) {
|
||||
query = query.eq('visibility', params.visibility);
|
||||
}
|
||||
|
||||
// Filter by city
|
||||
if (params?.city) {
|
||||
query = query.eq('city', params.city);
|
||||
}
|
||||
|
||||
// Search by name
|
||||
if (params?.search) {
|
||||
query = query.ilike('name', `%${params.search}%`);
|
||||
}
|
||||
|
||||
// Pagination
|
||||
if (params?.page && params?.limit) {
|
||||
const from = (params.page - 1) * params.limit;
|
||||
const to = from + params.limit - 1;
|
||||
query = query.range(from, to);
|
||||
}
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) {
|
||||
// If error is 401/403, it means RLS policies need to be set up
|
||||
// Return empty array for now
|
||||
console.warn('Teams query error (RLS policies may need to be configured):', error);
|
||||
return { data: [] };
|
||||
}
|
||||
|
||||
return { data: data || [] };
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch teams:', err);
|
||||
return { data: [] };
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useTeamById = (teamId: string, enabled = true) => {
|
||||
return useQuery({
|
||||
queryKey: teamKeys.detail(teamId),
|
||||
queryFn: async () => {
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { data: team, error } = await supabase
|
||||
.from('teams')
|
||||
.select(`
|
||||
*,
|
||||
leader:users!leader_id(id, email, fullname, avatar),
|
||||
members:team_members(
|
||||
id,
|
||||
role,
|
||||
status,
|
||||
joined_at,
|
||||
user:users(id, email, fullname, avatar)
|
||||
)
|
||||
`)
|
||||
.eq('id', teamId)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to fetch team:', error);
|
||||
throw new Error(error.message || 'Failed to fetch team');
|
||||
}
|
||||
|
||||
// Count active members
|
||||
const activeMemberCount = team?.members?.filter((m: any) => m.status === 'active').length || 0;
|
||||
|
||||
// Check if team has a submission
|
||||
const { data: submission } = await supabase
|
||||
.from('project_submissions')
|
||||
.select('id')
|
||||
.eq('team_id', teamId)
|
||||
.maybeSingle();
|
||||
|
||||
return {
|
||||
data: {
|
||||
...team,
|
||||
member_count: activeMemberCount,
|
||||
has_submission: !!submission,
|
||||
},
|
||||
};
|
||||
},
|
||||
enabled: enabled && !!teamId,
|
||||
});
|
||||
};
|
||||
|
||||
export const useCreateTeam = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: TCreateTeamRequest) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to create a team');
|
||||
}
|
||||
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { data: team, error: teamError } = await supabase
|
||||
.from('teams')
|
||||
.insert({
|
||||
name: data.name,
|
||||
logo: data.logo,
|
||||
banner: data.banner,
|
||||
description: data.description,
|
||||
city: data.city,
|
||||
visibility: data.visibility,
|
||||
leader_id: session.user.id,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (teamError) {
|
||||
console.error('Failed to create team:', teamError);
|
||||
throw new Error(teamError.message || 'Failed to create team');
|
||||
}
|
||||
|
||||
// Insert team creator as leader in team_members table
|
||||
const { error: memberError } = await supabase
|
||||
.from('team_members')
|
||||
.insert({
|
||||
team_id: team.id,
|
||||
user_id: session.user.id,
|
||||
role: 'leader',
|
||||
status: 'active',
|
||||
});
|
||||
|
||||
if (memberError) {
|
||||
// If duplicate key error (23505), it means leader is already a member (possibly by trigger)
|
||||
// This is acceptable, so we can ignore it
|
||||
if (memberError.code === '23505') {
|
||||
console.log('Team leader already exists in team_members (likely added by trigger)');
|
||||
} else {
|
||||
// For other errors, clean up and throw
|
||||
console.error('Failed to add team leader as member:', memberError);
|
||||
await supabase.from('teams').delete().eq('id', team.id);
|
||||
throw new Error('Failed to set up team membership');
|
||||
}
|
||||
}
|
||||
|
||||
return { data: team };
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.myTeams() });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateTeam = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: TUpdateTeamRequest) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to update a team');
|
||||
}
|
||||
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { data: team, error } = await supabase
|
||||
.from('teams')
|
||||
.update({
|
||||
name: data.name,
|
||||
logo: data.logo,
|
||||
banner: data.banner,
|
||||
description: data.description,
|
||||
city: data.city,
|
||||
visibility: data.visibility,
|
||||
})
|
||||
.eq('id', teamId)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to update team:', error);
|
||||
throw new Error(error.message || 'Failed to update team');
|
||||
}
|
||||
|
||||
return { data: team };
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Team Members Hooks
|
||||
export const useTeamMembers = (teamId: string, enabled = true) => {
|
||||
return useQuery({
|
||||
queryKey: teamKeys.members(teamId),
|
||||
queryFn: async () => {
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { data: members, error } = await supabase
|
||||
.from('team_members')
|
||||
.select(`
|
||||
id,
|
||||
team_id,
|
||||
user_id,
|
||||
role,
|
||||
status,
|
||||
joined_at,
|
||||
user:users(id, email, fullname, avatar)
|
||||
`)
|
||||
.eq('team_id', teamId)
|
||||
.order('joined_at', { ascending: true });
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to fetch team members:', error);
|
||||
throw new Error(error.message || 'Failed to fetch team members');
|
||||
}
|
||||
|
||||
return { data: members || [] };
|
||||
},
|
||||
enabled: enabled && !!teamId,
|
||||
});
|
||||
};
|
||||
|
||||
export const useInviteMember = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: TInviteMemberRequest) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to invite a member');
|
||||
}
|
||||
|
||||
// Insert invitation into team_invitations table
|
||||
const { data: invitation, error } = await supabase
|
||||
.from('team_invitations')
|
||||
.insert({
|
||||
team_id: teamId,
|
||||
inviter_id: session.user.id,
|
||||
invitee_email: data.email,
|
||||
status: 'pending',
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to create invitation:', error);
|
||||
throw new Error(error.message || 'Failed to send invitation');
|
||||
}
|
||||
|
||||
return { data: invitation };
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useManageMember = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ userId, data }: { userId: string; data: any }) =>
|
||||
teamsApi.manageMember(teamId, userId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useRemoveMember = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) => teamsApi.removeMember(teamId, userId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Join Requests Hooks
|
||||
export const useJoinTeam = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ teamId, data }: { teamId: string; data: TJoinTeamRequest }) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to join a team');
|
||||
}
|
||||
|
||||
// Insert join request into team_join_requests table
|
||||
const { data: joinRequest, error } = await supabase
|
||||
.from('team_join_requests')
|
||||
.insert({
|
||||
team_id: teamId,
|
||||
user_id: session.user.id,
|
||||
message: data.message,
|
||||
status: 'pending',
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to create join request:', error);
|
||||
throw new Error(error.message || 'Failed to send join request');
|
||||
}
|
||||
|
||||
return { data: joinRequest };
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useTeamJoinRequests = (teamId: string, enabled = true) => {
|
||||
return useQuery({
|
||||
queryKey: teamKeys.joinRequests(teamId),
|
||||
queryFn: async () => {
|
||||
// Fetch join requests with user information
|
||||
const { data: requests, error } = await supabase
|
||||
.from('team_join_requests')
|
||||
.select(`
|
||||
id,
|
||||
team_id,
|
||||
user_id,
|
||||
message,
|
||||
status,
|
||||
created_at,
|
||||
user:users(id, email, fullname, avatar)
|
||||
`)
|
||||
.eq('team_id', teamId)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to fetch join requests:', error);
|
||||
throw new Error(error.message || 'Failed to fetch join requests');
|
||||
}
|
||||
|
||||
return { data: requests || [] };
|
||||
},
|
||||
enabled: enabled && !!teamId,
|
||||
});
|
||||
};
|
||||
|
||||
export const useRespondToJoinRequest = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ requestId, action }: { requestId: string; action: 'approve' | 'reject' }) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to respond to join requests');
|
||||
}
|
||||
|
||||
// First, get the join request details
|
||||
const { data: joinRequest, error: fetchError } = await supabase
|
||||
.from('team_join_requests')
|
||||
.select('id, team_id, user_id, status')
|
||||
.eq('id', requestId)
|
||||
.single();
|
||||
|
||||
if (fetchError || !joinRequest) {
|
||||
throw new Error('Join request not found');
|
||||
}
|
||||
|
||||
if (joinRequest.status !== 'pending') {
|
||||
throw new Error('Join request has already been processed');
|
||||
}
|
||||
|
||||
if (action === 'approve') {
|
||||
// Update join request status
|
||||
const { error: updateError } = await supabase
|
||||
.from('team_join_requests')
|
||||
.update({ status: 'accepted' })
|
||||
.eq('id', requestId);
|
||||
|
||||
if (updateError) {
|
||||
throw new Error('Failed to update join request: ' + updateError.message);
|
||||
}
|
||||
|
||||
// Add user as team member
|
||||
const { error: memberError } = await supabase
|
||||
.from('team_members')
|
||||
.insert({
|
||||
team_id: joinRequest.team_id,
|
||||
user_id: joinRequest.user_id,
|
||||
role: 'member',
|
||||
status: 'active',
|
||||
});
|
||||
|
||||
if (memberError) {
|
||||
// If member creation fails, rollback join request update
|
||||
await supabase
|
||||
.from('team_join_requests')
|
||||
.update({ status: 'pending' })
|
||||
.eq('id', requestId);
|
||||
|
||||
throw new Error('Failed to add member to team: ' + memberError.message);
|
||||
}
|
||||
|
||||
return { success: true, action: 'accepted' };
|
||||
} else {
|
||||
// Reject join request
|
||||
const { error: updateError } = await supabase
|
||||
.from('team_join_requests')
|
||||
.update({ status: 'rejected' })
|
||||
.eq('id', requestId);
|
||||
|
||||
if (updateError) {
|
||||
throw new Error('Failed to update join request: ' + updateError.message);
|
||||
}
|
||||
|
||||
return { success: true, action: 'rejected' };
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.joinRequests(teamId) });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Invitations Hooks
|
||||
export const useMyInvitations = () => {
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useQuery({
|
||||
queryKey: teamKeys.myInvitations(),
|
||||
queryFn: async () => {
|
||||
if (!session?.user?.email) {
|
||||
return { data: [] };
|
||||
}
|
||||
|
||||
// Query team_invitations where invitee_email matches current user's email
|
||||
const { data: invitations, error } = await supabase
|
||||
.from('team_invitations')
|
||||
.select(`
|
||||
id,
|
||||
team_id,
|
||||
inviter_id,
|
||||
invitee_email,
|
||||
invitee_id,
|
||||
status,
|
||||
created_at,
|
||||
team:teams(
|
||||
id,
|
||||
name,
|
||||
logo,
|
||||
banner,
|
||||
description,
|
||||
city,
|
||||
visibility,
|
||||
leader_id
|
||||
),
|
||||
inviter:users!team_invitations_inviter_id_fkey(
|
||||
id,
|
||||
fullname,
|
||||
email,
|
||||
avatar
|
||||
)
|
||||
`)
|
||||
.eq('invitee_email', session.user.email)
|
||||
.eq('status', 'pending');
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to fetch invitations:', error);
|
||||
return { data: [] };
|
||||
}
|
||||
|
||||
return { data: invitations || [] };
|
||||
},
|
||||
enabled: !!session?.user?.email,
|
||||
});
|
||||
};
|
||||
|
||||
export const useRespondToInvitation = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ invitationId, action }: { invitationId: string; action: 'accept' | 'reject' }) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('User not authenticated');
|
||||
}
|
||||
|
||||
// First, get the invitation details
|
||||
const { data: invitation, error: fetchError } = await supabase
|
||||
.from('team_invitations')
|
||||
.select('id, team_id, invitee_email, status')
|
||||
.eq('id', invitationId)
|
||||
.single();
|
||||
|
||||
if (fetchError || !invitation) {
|
||||
throw new Error('Invitation not found');
|
||||
}
|
||||
|
||||
if (invitation.status !== 'pending') {
|
||||
throw new Error('Invitation has already been responded to');
|
||||
}
|
||||
|
||||
if (action === 'accept') {
|
||||
// Update invitation status and set invitee_id
|
||||
const { error: updateError } = await supabase
|
||||
.from('team_invitations')
|
||||
.update({
|
||||
status: 'accepted',
|
||||
invitee_id: session.user.id,
|
||||
})
|
||||
.eq('id', invitationId);
|
||||
|
||||
if (updateError) {
|
||||
throw new Error('Failed to update invitation: ' + updateError.message);
|
||||
}
|
||||
|
||||
// Create team_members record
|
||||
const { error: memberError } = await supabase
|
||||
.from('team_members')
|
||||
.insert({
|
||||
team_id: invitation.team_id,
|
||||
user_id: session.user.id,
|
||||
role: 'member',
|
||||
status: 'active',
|
||||
});
|
||||
|
||||
if (memberError) {
|
||||
// If member creation fails, rollback invitation update
|
||||
await supabase
|
||||
.from('team_invitations')
|
||||
.update({
|
||||
status: 'pending',
|
||||
invitee_id: null,
|
||||
})
|
||||
.eq('id', invitationId);
|
||||
|
||||
throw new Error('Failed to add member to team: ' + memberError.message);
|
||||
}
|
||||
|
||||
return { success: true, action: 'accepted' };
|
||||
} else {
|
||||
// Reject invitation
|
||||
const { error: updateError } = await supabase
|
||||
.from('team_invitations')
|
||||
.update({
|
||||
status: 'rejected',
|
||||
invitee_id: session.user.id,
|
||||
})
|
||||
.eq('id', invitationId);
|
||||
|
||||
if (updateError) {
|
||||
throw new Error('Failed to update invitation: ' + updateError.message);
|
||||
}
|
||||
|
||||
return { success: true, action: 'rejected' };
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.myInvitations() });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.myTeams() });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// User's Teams
|
||||
export const useMyTeams = () => {
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useQuery({
|
||||
queryKey: teamKeys.myTeams(),
|
||||
queryFn: async () => {
|
||||
if (!session?.user?.id) {
|
||||
return { data: [] };
|
||||
}
|
||||
|
||||
// Query team_members to find teams where user is a member
|
||||
const { data: memberships, error: membershipsError } = await supabase
|
||||
.from('team_members')
|
||||
.select(`
|
||||
team_id,
|
||||
team:teams(
|
||||
id,
|
||||
name,
|
||||
logo,
|
||||
banner,
|
||||
description,
|
||||
city,
|
||||
visibility,
|
||||
leader_id,
|
||||
created_at
|
||||
)
|
||||
`)
|
||||
.eq('user_id', session.user.id)
|
||||
.eq('status', 'active');
|
||||
|
||||
if (membershipsError) {
|
||||
console.error('Failed to fetch user teams:', membershipsError);
|
||||
return { data: [] };
|
||||
}
|
||||
|
||||
// Extract teams from memberships
|
||||
const teams = memberships?.map((m: any) => m.team).filter(Boolean) || [];
|
||||
|
||||
return { data: teams };
|
||||
},
|
||||
enabled: !!session?.user?.id,
|
||||
});
|
||||
};
|
||||
|
||||
// Project Submission Hooks
|
||||
export const useSubmitProject = (teamId: string) => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: TSubmitProjectRequest) => {
|
||||
return await teamsApi.submitProject(teamId, data);
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.submission(teamId) });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useTeamSubmission = (teamId: string, enabled = true) => {
|
||||
return useQuery({
|
||||
queryKey: teamKeys.submission(teamId),
|
||||
queryFn: async () => {
|
||||
const submission = await teamsApi.getTeamSubmission(teamId);
|
||||
return { data: submission };
|
||||
},
|
||||
enabled: enabled && !!teamId,
|
||||
});
|
||||
};
|
||||
|
||||
// Leave Team Hook
|
||||
export const useLeaveTeam = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (teamId: string) => {
|
||||
return await teamsApi.leaveTeam(teamId);
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.myTeams() });
|
||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -1,39 +1,119 @@
|
||||
import { useMutation, UseMutationResult } from '@tanstack/react-query';
|
||||
import { uploadService, UploadResponse } from '../../api/upload';
|
||||
import { TResponseError } from '../../types/common';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { supabase, getAuthenticatedClient } from '../../supabase';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
|
||||
// Supabase Storage-based upload hooks
|
||||
|
||||
export const useUploadFile = () => {
|
||||
const { session } = useAuthStore();
|
||||
|
||||
export const useUploadFile = (): UseMutationResult<
|
||||
UploadResponse,
|
||||
TResponseError,
|
||||
File,
|
||||
unknown
|
||||
> => {
|
||||
return useMutation({
|
||||
mutationKey: ['upload-file'],
|
||||
mutationFn: (file) => uploadService.uploadFile(file),
|
||||
mutationFn: async (file: File) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to upload files');
|
||||
}
|
||||
|
||||
// Generate a unique file name
|
||||
const fileExt = file.name.split('.').pop();
|
||||
const fileName = `${session.user.id}-${Date.now()}.${fileExt}`;
|
||||
const filePath = `teams/${fileName}`;
|
||||
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { error } = await supabase.storage
|
||||
.from('hackathon-uploads')
|
||||
.upload(filePath, file, {
|
||||
cacheControl: '3600',
|
||||
upsert: true,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to upload file:', error);
|
||||
throw new Error(error.message || 'Failed to upload file');
|
||||
}
|
||||
|
||||
// Get public URL
|
||||
const { data: publicUrlData } = supabase.storage
|
||||
.from('hackathon-uploads')
|
||||
.getPublicUrl(filePath);
|
||||
|
||||
return { data: { url: publicUrlData.publicUrl } };
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useUploadAvatar = (): UseMutationResult<
|
||||
UploadResponse,
|
||||
TResponseError,
|
||||
File,
|
||||
unknown
|
||||
> => {
|
||||
export const useUploadAvatar = () => {
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: ['upload-avatar'],
|
||||
mutationFn: (file) => uploadService.uploadAvatar(file),
|
||||
mutationFn: async (file: File) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to upload avatar');
|
||||
}
|
||||
|
||||
// Generate a unique file name
|
||||
const fileExt = file.name.split('.').pop();
|
||||
const fileName = `${session.user.id}-${Date.now()}.${fileExt}`;
|
||||
const filePath = `avatars/${fileName}`;
|
||||
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { error } = await supabase.storage
|
||||
.from('hackathon-uploads')
|
||||
.upload(filePath, file, {
|
||||
cacheControl: '3600',
|
||||
upsert: true,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to upload avatar:', error);
|
||||
throw new Error(error.message || 'Failed to upload avatar');
|
||||
}
|
||||
|
||||
// Get public URL
|
||||
const { data: publicUrlData } = supabase.storage
|
||||
.from('hackathon-uploads')
|
||||
.getPublicUrl(filePath);
|
||||
|
||||
return { data: { url: publicUrlData.publicUrl } };
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useUploadCV = (): UseMutationResult<
|
||||
UploadResponse,
|
||||
TResponseError,
|
||||
File,
|
||||
unknown
|
||||
> => {
|
||||
export const useUploadCV = () => {
|
||||
const { session } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: ['upload-cv'],
|
||||
mutationFn: (file) => uploadService.uploadCV(file),
|
||||
mutationFn: async (file: File) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to upload CV');
|
||||
}
|
||||
|
||||
// Generate a unique file name
|
||||
const fileExt = file.name.split('.').pop();
|
||||
const fileName = `${session.user.id}-${Date.now()}.${fileExt}`;
|
||||
const filePath = `cvs/${fileName}`;
|
||||
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { error } = await supabase.storage
|
||||
.from('hackathon-uploads')
|
||||
.upload(filePath, file, {
|
||||
cacheControl: '3600',
|
||||
upsert: true,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to upload CV:', error);
|
||||
throw new Error(error.message || 'Failed to upload CV');
|
||||
}
|
||||
|
||||
// Get public URL
|
||||
const { data: publicUrlData } = supabase.storage
|
||||
.from('hackathon-uploads')
|
||||
.getPublicUrl(filePath);
|
||||
|
||||
return { data: { url: publicUrlData.publicUrl } };
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,44 +1,94 @@
|
||||
import { useQuery, useMutation, UseQueryResult, UseMutationResult, UseQueryOptions } from '@tanstack/react-query';
|
||||
import { userService, UserDetailResponseDto, UserUpdateRequestDto } from '../../api/users';
|
||||
import { TResponseError } from '../../types/common';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { userService } from '../../api/users';
|
||||
import { supabase, getAuthenticatedClient } from '../../supabase';
|
||||
import { useAuthStore } from '@imphnen-frontend-service/utils';
|
||||
|
||||
export const useUserMe = (options?: UseQueryOptions<UserDetailResponseDto, TResponseError>): UseQueryResult<UserDetailResponseDto, TResponseError> => {
|
||||
// Supabase-based user hooks
|
||||
|
||||
export const useUserMe = () => {
|
||||
return useQuery({
|
||||
queryKey: ['user-me'],
|
||||
queryFn: () => userService.getUserMe(),
|
||||
...options,
|
||||
queryFn: async () => {
|
||||
const user = await userService.getUserMe();
|
||||
return { data: user };
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useUserById = (id: string, options?: UseQueryOptions<UserDetailResponseDto, TResponseError>): UseQueryResult<UserDetailResponseDto, TResponseError> => {
|
||||
export const useUserById = (id: string) => {
|
||||
return useQuery({
|
||||
queryKey: ['user-by-id', id],
|
||||
queryFn: () => userService.getUserById(id),
|
||||
queryFn: async () => {
|
||||
const user = await userService.getUserById(id);
|
||||
return { data: user };
|
||||
},
|
||||
enabled: !!id,
|
||||
...options,
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateUserMe = (): UseMutationResult<
|
||||
UserDetailResponseDto,
|
||||
TResponseError,
|
||||
UserUpdateRequestDto,
|
||||
unknown
|
||||
> => {
|
||||
export const useUpdateUserMe = () => {
|
||||
const queryClient = useQueryClient();
|
||||
const { session, setSession } = useAuthStore();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: ['update-user-me'],
|
||||
mutationFn: (data) => userService.updateUserMe(data),
|
||||
mutationFn: async (data: any) => {
|
||||
if (!session?.user?.id) {
|
||||
throw new Error('You must be logged in to update profile');
|
||||
}
|
||||
|
||||
// Supabase client now has auth context from setSession()
|
||||
const { data: updatedUser, error } = await supabase
|
||||
.from('users')
|
||||
.update({
|
||||
fullname: data.fullname,
|
||||
bio: data.bio,
|
||||
location: data.location,
|
||||
avatar: data.avatar,
|
||||
skills: data.skills,
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', session.user.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to update user profile:', error);
|
||||
throw new Error(error.message || 'Failed to update profile');
|
||||
}
|
||||
return { data: updatedUser };
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
// Update Zustand session store with new user data
|
||||
if (session && result.data) {
|
||||
setSession({
|
||||
token: session.token,
|
||||
user: {
|
||||
...session.user,
|
||||
fullname: result.data.fullname || session.user.fullname,
|
||||
bio: result.data.bio || '',
|
||||
location: result.data.location || '',
|
||||
avatar: result.data.avatar || session.user.avatar,
|
||||
skills: result.data.skills || [],
|
||||
},
|
||||
});
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['user-me'] });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateUserById = (): UseMutationResult<
|
||||
UserDetailResponseDto,
|
||||
TResponseError,
|
||||
{ id: string; data: UserUpdateRequestDto },
|
||||
unknown
|
||||
> => {
|
||||
export const useUpdateUserById = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: ['update-user-by-id'],
|
||||
mutationFn: ({ id, data }) => userService.updateUserById(id, data),
|
||||
mutationFn: async ({ id, data }: { id: string; data: any }) => {
|
||||
const updated = await userService.updateUserById(id, data);
|
||||
return { data: updated };
|
||||
},
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['user-by-id', variables.id] });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -2,3 +2,4 @@ export * from './api';
|
||||
export * from './hooks';
|
||||
export * from './types';
|
||||
export * from './schemas';
|
||||
export * from './supabase';
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from './auth';
|
||||
export * from './gacha';
|
||||
export * from './teams';
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { z } from 'zod';
|
||||
import { ETeamVisibility } from '../../types/teams';
|
||||
|
||||
export const teamCreateSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(3, 'Nama tim minimal 3 karakter')
|
||||
.max(50, 'Nama tim maksimal 50 karakter'),
|
||||
logo: z.string().url('Logo harus berupa URL yang valid').nullable(),
|
||||
banner: z.string().url('Banner harus berupa URL yang valid').nullable(),
|
||||
description: z
|
||||
.string()
|
||||
.min(10, 'Deskripsi minimal 10 karakter')
|
||||
.max(500, 'Deskripsi maksimal 500 karakter'),
|
||||
city: z.string().min(1, 'Kota harus diisi'),
|
||||
visibility: z.nativeEnum(ETeamVisibility, {
|
||||
errorMap: () => ({ message: 'Visibilitas tidak valid' }),
|
||||
}),
|
||||
});
|
||||
|
||||
export const teamUpdateSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.min(3, 'Nama tim minimal 3 karakter')
|
||||
.max(50, 'Nama tim maksimal 50 karakter')
|
||||
.optional(),
|
||||
logo: z.string().url('Logo harus berupa URL yang valid').nullable().optional(),
|
||||
banner: z.string().url('Banner harus berupa URL yang valid').nullable().optional(),
|
||||
description: z
|
||||
.string()
|
||||
.min(10, 'Deskripsi minimal 10 karakter')
|
||||
.max(500, 'Deskripsi maksimal 500 karakter')
|
||||
.optional(),
|
||||
city: z.string().min(1, 'Kota harus diisi').optional(),
|
||||
visibility: z
|
||||
.nativeEnum(ETeamVisibility, {
|
||||
errorMap: () => ({ message: 'Visibilitas tidak valid' }),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const inviteMemberSchema = z.object({
|
||||
email: z.string().email('Email tidak valid'),
|
||||
});
|
||||
|
||||
export const joinTeamSchema = z.object({
|
||||
message: z
|
||||
.string()
|
||||
.min(10, 'Pesan minimal 10 karakter')
|
||||
.max(200, 'Pesan maksimal 200 karakter'),
|
||||
});
|
||||
|
||||
export const projectSubmissionSchema = z.object({
|
||||
project_name: z
|
||||
.string()
|
||||
.min(3, 'Nama project minimal 3 karakter')
|
||||
.max(100, 'Nama project maksimal 100 karakter'),
|
||||
description: z
|
||||
.string()
|
||||
.min(20, 'Deskripsi minimal 20 karakter')
|
||||
.max(1000, 'Deskripsi maksimal 1000 karakter'),
|
||||
repository_url: z.string().url('URL repository tidak valid'),
|
||||
demo_url: z.string().url('URL demo tidak valid').optional().or(z.literal('')),
|
||||
presentation_url: z.string().url('URL presentasi tidak valid').optional().or(z.literal('')),
|
||||
screenshots: z.array(z.string().url('URL screenshot tidak valid')).optional(),
|
||||
});
|
||||
|
||||
export const userOnboardingSchema = z.object({
|
||||
fullname: z.string().min(3, 'Nama lengkap minimal 3 karakter').optional(),
|
||||
avatar: z.string().url('Avatar harus berupa URL yang valid').nullable().optional(),
|
||||
location: z.string().min(1, 'Domisili harus diisi'),
|
||||
bio: z.string().max(500, 'Bio maksimal 500 karakter').optional(),
|
||||
skills: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
export type TTeamCreateForm = z.infer<typeof teamCreateSchema>;
|
||||
export type TTeamUpdateForm = z.infer<typeof teamUpdateSchema>;
|
||||
export type TInviteMemberForm = z.infer<typeof inviteMemberSchema>;
|
||||
export type TJoinTeamForm = z.infer<typeof joinTeamSchema>;
|
||||
export type TProjectSubmissionForm = z.infer<typeof projectSubmissionSchema>;
|
||||
export type TUserOnboardingForm = z.infer<typeof userOnboardingSchema>;
|
||||
@@ -0,0 +1,41 @@
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
|
||||
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
|
||||
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
|
||||
|
||||
if (!supabaseUrl || !supabaseAnonKey) {
|
||||
throw new Error('Missing Supabase environment variables');
|
||||
}
|
||||
|
||||
// Create Supabase client with proper session management enabled
|
||||
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
|
||||
auth: {
|
||||
autoRefreshToken: true, // ✅ Auto-refresh expired tokens
|
||||
persistSession: true, // ✅ Persist session in storage
|
||||
detectSessionInUrl: true, // ✅ Auto-detect OAuth callback
|
||||
storage: typeof window !== 'undefined' ? window.localStorage : undefined,
|
||||
},
|
||||
global: {
|
||||
headers: {
|
||||
'X-Client-Info': 'supabase-js-web',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Helper to create authenticated client (kept for backward compatibility)
|
||||
// NOTE: With proper session management, this should no longer be needed
|
||||
// Once session is set via supabase.auth.setSession(), the base client will have auth context
|
||||
export const getAuthenticatedClient = (accessToken: string) => {
|
||||
return createClient(supabaseUrl, supabaseAnonKey, {
|
||||
auth: {
|
||||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
detectSessionInUrl: false,
|
||||
},
|
||||
global: {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from './client';
|
||||
@@ -4,3 +4,4 @@ export * from './users';
|
||||
export * from './roles';
|
||||
export * from './permissions';
|
||||
export * from './mentors';
|
||||
export * from './teams';
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
npm warn exec The following package was not found and will be installed: supabase@2.58.5
|
||||
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
|
||||
supabase start is not running.
|
||||
Try rerunning the command with --debug to troubleshoot the error.
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { TUserItem } from '../users';
|
||||
|
||||
export enum ETeamVisibility {
|
||||
PUBLIC = 'public',
|
||||
PRIVATE = 'private',
|
||||
}
|
||||
|
||||
export enum ETeamMemberRole {
|
||||
LEADER = 'leader',
|
||||
MEMBER = 'member',
|
||||
}
|
||||
|
||||
export enum ETeamMemberStatus {
|
||||
ACTIVE = 'active',
|
||||
PENDING = 'pending',
|
||||
REQUESTED = 'requested',
|
||||
}
|
||||
|
||||
export enum EInvitationStatus {
|
||||
PENDING = 'pending',
|
||||
ACCEPTED = 'accepted',
|
||||
REJECTED = 'rejected',
|
||||
}
|
||||
|
||||
export enum ESubmissionStatus {
|
||||
DRAFT = 'draft',
|
||||
SUBMITTED = 'submitted',
|
||||
}
|
||||
|
||||
export type TTeamItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
logo: string | null;
|
||||
banner: string | null;
|
||||
description: string;
|
||||
city: string;
|
||||
visibility: ETeamVisibility;
|
||||
leader_id: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type TTeamDetailItem = TTeamItem & {
|
||||
leader: TUserItem;
|
||||
members: TTeamMemberItem[];
|
||||
member_count: number;
|
||||
has_submission: boolean;
|
||||
};
|
||||
|
||||
export type TTeamMemberItem = {
|
||||
id: string;
|
||||
team_id: string;
|
||||
user_id: string;
|
||||
role: ETeamMemberRole;
|
||||
status: ETeamMemberStatus;
|
||||
joined_at: string;
|
||||
user: TUserItem;
|
||||
};
|
||||
|
||||
export type TTeamInvitationItem = {
|
||||
id: string;
|
||||
team_id: string;
|
||||
inviter_id: string;
|
||||
invitee_email: string;
|
||||
invitee_id: string | null;
|
||||
status: EInvitationStatus;
|
||||
created_at: string;
|
||||
team: TTeamItem;
|
||||
inviter: TUserItem;
|
||||
};
|
||||
|
||||
export type TTeamJoinRequestItem = {
|
||||
id: string;
|
||||
team_id: string;
|
||||
user_id: string;
|
||||
status: EInvitationStatus;
|
||||
message: string;
|
||||
created_at: string;
|
||||
user: TUserItem;
|
||||
team: TTeamItem;
|
||||
};
|
||||
|
||||
export type TProjectSubmissionItem = {
|
||||
id: string;
|
||||
team_id: string;
|
||||
project_name: string;
|
||||
description: string;
|
||||
repository_url: string;
|
||||
demo_url: string | null;
|
||||
presentation_url: string | null;
|
||||
screenshots: string[];
|
||||
status: ESubmissionStatus;
|
||||
submitted_at: string | null;
|
||||
submitted_by: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
// Request/Response DTOs
|
||||
export type TCreateTeamRequest = {
|
||||
name: string;
|
||||
logo: string | null;
|
||||
banner: string | null;
|
||||
description: string;
|
||||
city: string;
|
||||
visibility: ETeamVisibility;
|
||||
};
|
||||
|
||||
export type TUpdateTeamRequest = Partial<TCreateTeamRequest>;
|
||||
|
||||
export type TInviteMemberRequest = {
|
||||
email: string;
|
||||
};
|
||||
|
||||
export type TJoinTeamRequest = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type TManageMemberRequest = {
|
||||
action: 'approve' | 'reject' | 'remove';
|
||||
};
|
||||
|
||||
export type TSubmitProjectRequest = {
|
||||
project_name: string;
|
||||
description: string;
|
||||
repository_url: string;
|
||||
demo_url?: string;
|
||||
presentation_url?: string;
|
||||
screenshots?: string[];
|
||||
};
|
||||
|
||||
export type TTeamListResponse = {
|
||||
data: TTeamItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
};
|
||||
|
||||
export type TTeamDetailResponse = {
|
||||
data: TTeamDetailItem;
|
||||
};
|
||||
|
||||
export type TTeamMembersResponse = {
|
||||
data: TTeamMemberItem[];
|
||||
};
|
||||
|
||||
export type TTeamInvitationsResponse = {
|
||||
data: TTeamInvitationItem[];
|
||||
};
|
||||
|
||||
export type TTeamJoinRequestsResponse = {
|
||||
data: TTeamJoinRequestItem[];
|
||||
};
|
||||
|
||||
export type TProjectSubmissionResponse = {
|
||||
data: TProjectSubmissionItem;
|
||||
};
|
||||
@@ -10,6 +10,9 @@ export type TUserItem = {
|
||||
is_active: boolean;
|
||||
phone_number: string;
|
||||
role: TRoleDetailItem;
|
||||
location?: string;
|
||||
bio?: string;
|
||||
skills?: string[];
|
||||
};
|
||||
|
||||
// Re-export types from API for convenience
|
||||
|
||||
@@ -9,9 +9,16 @@ import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons'; // Import
|
||||
import { cn } from '@imphnen-frontend-service/utils';
|
||||
import { Button } from '../button';
|
||||
|
||||
type TInputType = 'text' | 'email' | 'number' | 'password' | 'file' | 'date' | 'time';
|
||||
type TInputType =
|
||||
| 'text'
|
||||
| 'email'
|
||||
| 'number'
|
||||
| 'password'
|
||||
| 'file'
|
||||
| 'date'
|
||||
| 'time';
|
||||
type TInputSize = 'sm' | 'md' | 'lg';
|
||||
type Width = 'standard' | 'custom'
|
||||
type Width = 'standard' | 'custom';
|
||||
|
||||
type TInputProps = Omit<
|
||||
DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>,
|
||||
@@ -49,7 +56,9 @@ export const Input: FC<TInputProps> = ({
|
||||
};
|
||||
|
||||
const mergedClassName = cn(
|
||||
`px-[12px] py-[8px] text-neutral-800 bg-white placeholder:text-neutral-300 border border-neutral-200 hover:border-blue-300 focus:outline-1 focus:outline-blue-500 rounded-md font-bai-jamjuree ${widthform === "standard" ? "min-w-70" : ""}`,
|
||||
`px-[12px] py-[8px] text-neutral-800 bg-white placeholder:text-neutral-300 border border-neutral-200 hover:border-blue-300 focus:outline-1 focus:outline-blue-500 rounded-md font-bai-jamjuree w-full ${
|
||||
widthform === 'standard' ? 'min-w-70' : ''
|
||||
}`,
|
||||
sizeClasses[size].textSize,
|
||||
disabled && disabledClass,
|
||||
className
|
||||
@@ -65,14 +74,14 @@ export const Input: FC<TInputProps> = ({
|
||||
{...rest}
|
||||
/>
|
||||
{type === 'password' && (
|
||||
<div className="absolute end-0 px-[12px] h-full flex items-center">
|
||||
<div className="absolute end-0 px-3 h-full flex items-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="text"
|
||||
size={size}
|
||||
onClick={togglePasswordVisibility}
|
||||
className={cn(
|
||||
'relative aspect-square -me-[8px] p-[6px]',
|
||||
'relative aspect-square -me-2 p-1.5',
|
||||
sizeClasses[size].iconSize,
|
||||
disabled && 'cursor-not-allowed'
|
||||
)}
|
||||
|
||||
@@ -1,29 +1,10 @@
|
||||
import { TVerifyOtpRequest, usePostVerifyEmail } from '@imphnen-frontend-service/service';
|
||||
import { toast } from 'sonner';
|
||||
import { useNavigate, useSearchParams } from 'react-router';
|
||||
|
||||
// OTP verification is not used with GitHub OAuth authentication
|
||||
// This hook is kept for backward compatibility but is not used
|
||||
export const useOtp = () => {
|
||||
const navigate = useNavigate();
|
||||
const { mutate, isPending } = usePostVerifyEmail();
|
||||
const [ searchParams ] = useSearchParams();
|
||||
|
||||
const otp = (payload: TVerifyOtpRequest) => {
|
||||
mutate({ ...payload, email: searchParams.get("email") || "" }, {
|
||||
onSuccess: (data) => {
|
||||
toast.success('Berhasil Registrasi');
|
||||
navigate("/auth/register/success");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err?.response?.data?.message ??
|
||||
'Terjadi Kesalahan yang tidak diketahui'
|
||||
);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
otp,
|
||||
isLoading: isPending,
|
||||
otp: () => {
|
||||
console.warn('OTP verification is not used with GitHub OAuth authentication');
|
||||
},
|
||||
isLoading: false,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,28 +1,10 @@
|
||||
import { TRegisterRequest, usePostRegister } from '@imphnen-frontend-service/service';
|
||||
import { toast } from 'sonner';
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
// Registration is handled through GitHub OAuth
|
||||
// This hook is kept for backward compatibility but is not used
|
||||
export const useRegister = () => {
|
||||
const navigate = useNavigate();
|
||||
const { mutate, isPending } = usePostRegister();
|
||||
|
||||
const register = (payload: TRegisterRequest) => {
|
||||
mutate(payload, {
|
||||
onSuccess: (data) => {
|
||||
toast.success('Berhasil Registrasi');
|
||||
navigate(`/auth/register/otp?email=${payload.email}`);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err?.response?.data?.message ??
|
||||
'Terjadi Kesalahan yang tidak diketahui'
|
||||
);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
register,
|
||||
isLoading: isPending,
|
||||
register: () => {
|
||||
console.warn('Registration is handled through GitHub OAuth');
|
||||
},
|
||||
isLoading: false,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,25 +1,10 @@
|
||||
import { TSendOTPRequest, usePostSendOTP } from '@imphnen-frontend-service/service';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
// OTP is not used with GitHub OAuth authentication
|
||||
// This hook is kept for backward compatibility but is not used
|
||||
export const useSendOTP = () => {
|
||||
const { mutate, isPending } = usePostSendOTP();
|
||||
|
||||
const resendOTP = (payload: TSendOTPRequest) => {
|
||||
mutate(payload, {
|
||||
onSuccess: (data) => {
|
||||
toast.success('Berhasil Mengirim Ulang OTP');
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err?.response?.data?.message ??
|
||||
'Terjadi Kesalahan yang tidak diketahui'
|
||||
);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
resendOTP,
|
||||
isLoading: isPending,
|
||||
resendOTP: () => {
|
||||
console.warn('OTP is not used with GitHub OAuth authentication');
|
||||
},
|
||||
isLoading: false,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,41 +1,21 @@
|
||||
import { TLoginRequest, usePostLogin } from '@imphnen-frontend-service/service';
|
||||
import { supabase } from '@imphnen-frontend-service/service';
|
||||
import { useAuthStore } from './';
|
||||
import { toast } from 'sonner';
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
export const useSession = () => {
|
||||
const navigate = useNavigate();
|
||||
const { mutate, isPending } = usePostLogin();
|
||||
const { setLoading, setSession, clearSession, session, status } =
|
||||
useAuthStore();
|
||||
const { clearSession, session, status } = useAuthStore();
|
||||
const isAuthenticated = status === 'authenticated';
|
||||
|
||||
const signIn = (payload: TLoginRequest) => {
|
||||
setLoading(true);
|
||||
mutate(payload, {
|
||||
onSuccess: (data) => {
|
||||
toast.success('Login sukses');
|
||||
setSession(data.data);
|
||||
navigate(0);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err?.response?.data?.message ??
|
||||
'Terjadi Kesalahan yang tidak diketahui'
|
||||
);
|
||||
const signOut = async () => {
|
||||
await supabase.auth.signOut();
|
||||
clearSession();
|
||||
},
|
||||
});
|
||||
};
|
||||
const signOut = () => {
|
||||
clearSession();
|
||||
navigate(0);
|
||||
navigate('/auth/login');
|
||||
};
|
||||
|
||||
return {
|
||||
session,
|
||||
signIn,
|
||||
signOut,
|
||||
isLoading: isPending,
|
||||
isAuthenticated,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -23,6 +23,9 @@ type TUserItem = {
|
||||
is_active: boolean;
|
||||
phone_number: string;
|
||||
role: TRoleItem;
|
||||
bio?: string;
|
||||
location?: string;
|
||||
skills?: string[];
|
||||
};
|
||||
|
||||
export const SessionUser = {
|
||||
|
||||
Generated
+301
-673
File diff suppressed because it is too large
Load Diff
+8
-3
@@ -7,18 +7,22 @@
|
||||
"gacha:build": "nx build gacha",
|
||||
"gacha:test": "nx test gacha",
|
||||
"gacha:prod": "serve ./dist/apps/gacha",
|
||||
"gacha:lint": "nx run gacha:lint",
|
||||
"backoffice:dev": "nx dev backoffice",
|
||||
"backoffice:build": "nx build backoffice",
|
||||
"backoffice:test": "nx test backoffice",
|
||||
"backoffice:prod": "serve ./dist/apps/backoffice",
|
||||
"backoffice:lint": "nx run backoffice:lint",
|
||||
"dimentorin:dev": "nx dev dimentorin",
|
||||
"dimentorin:test": "nx test dimentorin",
|
||||
"dimentorin:build": "nx build dimentorin",
|
||||
"dimentorin:prod": "serve ./dist/apps/dimentorin",
|
||||
"dimentorin:lint": "nx run dimentorin:lint",
|
||||
"hackathon:dev": "nx dev hackathon",
|
||||
"hackathon:build": "nx build hackathon",
|
||||
"hackathon:test": "nx test hackathon",
|
||||
"hackathon:prod": "serve ./dist/apps/hackathon",
|
||||
"hackathon:lint": "nx run hackathon:lint",
|
||||
"landing:dev": "nx serve landing",
|
||||
"landing:build": "nx build landing",
|
||||
"landing:prod": "cd ./dist/apps/landing && npx next start",
|
||||
@@ -35,8 +39,9 @@
|
||||
"@radix-ui/react-label": "^2.1.7",
|
||||
"@radix-ui/react-slot": "^1.2.0",
|
||||
"@redocly/ajv": "^8.11.2",
|
||||
"@supabase/supabase-js": "^2.84.0",
|
||||
"@tanstack/react-query": "^5.74.4",
|
||||
"@tanstack/react-store": "^0.7.0",
|
||||
"@tanstack/react-store": "^0.8.0",
|
||||
"@tanstack/react-table": "^8.21.2",
|
||||
"axios": "^1.8.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
@@ -45,7 +50,7 @@
|
||||
"framer-motion": "^12.9.2",
|
||||
"graphql": "^16.11.0",
|
||||
"js-cookie": "^3.0.5",
|
||||
"next": "~15.2.4",
|
||||
"next": "~16.0.3",
|
||||
"next-themes": "^0.4.6",
|
||||
"openapi-fetch": "^0.15.0",
|
||||
"openapi-react-query": "^0.5.0",
|
||||
@@ -68,7 +73,7 @@
|
||||
"@eslint/compat": "^1.1.1",
|
||||
"@eslint/eslintrc": "^3.3.1",
|
||||
"@eslint/js": "^9.8.0",
|
||||
"@next/eslint-plugin-next": "^15.2.4",
|
||||
"@next/eslint-plugin-next": "^16.0.3",
|
||||
"@nx/devkit": "22.1.1",
|
||||
"@nx/eslint": "22.1.1",
|
||||
"@nx/eslint-plugin": "22.1.1",
|
||||
|
||||
Reference in New Issue
Block a user