Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0017aff5f4 | ||
|
|
e52776e68a | ||
|
|
cd06a71a9e | ||
|
|
0fcd93cb7d | ||
|
|
3470853858 | ||
|
|
ff9a02c020 | ||
|
|
f81a7c334e | ||
|
|
2700f7cbb7 | ||
|
|
cfcdfa527c | ||
|
|
c6579d5295 | ||
|
|
a1640cfe1d | ||
|
|
00df69fb93 | ||
|
|
810dbaa0ca | ||
|
|
cb09709800 | ||
|
|
7e385c6385 | ||
|
|
19aa5bb452 | ||
|
|
e8de897dc9 | ||
|
|
eff89d28ed | ||
|
|
b75a88677a | ||
|
|
7642fef3e6 | ||
|
|
f40e0e35b9 | ||
|
|
c6c0d6fded | ||
|
|
fcaa449630 | ||
|
|
4988980384 | ||
|
|
9547d34f5c | ||
|
|
aeb23a7255 |
@@ -10,13 +10,7 @@
|
|||||||
"Bash(ren page.tsx page-original.tsx)",
|
"Bash(ren page.tsx page-original.tsx)",
|
||||||
"Bash(ren:*)",
|
"Bash(ren:*)",
|
||||||
"Bash(npx supabase:*)",
|
"Bash(npx supabase:*)",
|
||||||
"Bash(libs/service/src/types/supabase.ts)",
|
"Bash(libs/service/src/types/supabase.ts)"
|
||||||
"Bash(npx nx build:*)",
|
|
||||||
"Bash(git add:*)",
|
|
||||||
"Bash(git commit:*)",
|
|
||||||
"Bash(git push)",
|
|
||||||
"Bash(findstr:*)",
|
|
||||||
"Bash(ls:*)"
|
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"mcpServers": {
|
|
||||||
"nx-mcp": {
|
|
||||||
"type": "stdio",
|
|
||||||
"command": "npx",
|
|
||||||
"args": ["nx", "mcp"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<!-- nx configuration start-->
|
|
||||||
<!-- Leave the start & end comments to automatically receive updates. -->
|
|
||||||
|
|
||||||
# General Guidelines for working with Nx
|
|
||||||
|
|
||||||
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling directly
|
|
||||||
- You have access to the Nx MCP server and its tools, use them to help the user
|
|
||||||
- When answering questions about the repository, use the `nx_workspace` tool first to gain an understanding of the workspace architecture where applicable.
|
|
||||||
- When working in individual projects, use the `nx_project_details` mcp tool to analyze and understand the specific project structure and dependencies
|
|
||||||
- For questions around nx configuration, best practices or if you're unsure, use the `nx_docs` tool to get relevant, up-to-date docs. Always use this instead of assuming things about nx configuration
|
|
||||||
- If the user needs help with an Nx configuration or project graph error, use the `nx_workspace` tool to get any errors
|
|
||||||
|
|
||||||
<!-- nx configuration end-->
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { BackofficeWrapper } from '@imphnen-frontend-service/ui/organisms';
|
|
||||||
import { FC, ReactElement } from 'react';
|
|
||||||
|
|
||||||
export const HackathonDashboardPage: FC = (): ReactElement => {
|
|
||||||
return (
|
|
||||||
<BackofficeWrapper title="IMPHNEN x Kolosal.ai Hackathon 2025">
|
|
||||||
<h1 className="mb-8 text-p1 font-semibold text-neutral-700">Dashboard</h1>
|
|
||||||
|
|
||||||
<section className="grid grid-cols-5 gap-5">
|
|
||||||
{/* Participant */}
|
|
||||||
<div className="bg-white px-6 py-4 rounded-md shadow">
|
|
||||||
<h3 className="text-primary-500 text-p2 font-semibold mb-2.5">
|
|
||||||
1261
|
|
||||||
</h3>
|
|
||||||
<p className="text-neutral-400 text-p3">Total Participants</p>
|
|
||||||
</div>
|
|
||||||
{/* Team */}
|
|
||||||
<div className="bg-white px-6 py-4 rounded-md shadow">
|
|
||||||
<h3 className="text-primary-500 text-p2 font-semibold mb-2.5">206</h3>
|
|
||||||
<p className="text-neutral-400 text-p3">Total Teams</p>
|
|
||||||
</div>
|
|
||||||
{/* Project Submitted */}
|
|
||||||
<div className="bg-white px-6 py-4 rounded-md shadow">
|
|
||||||
<h3 className="text-primary-500 text-p2 font-semibold mb-2.5">0</h3>
|
|
||||||
<p className="text-neutral-400 text-p3">Total Project Submitted</p>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</BackofficeWrapper>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default HackathonDashboardPage;
|
|
||||||
@@ -1,128 +0,0 @@
|
|||||||
import { FC, ReactElement, useState } from 'react';
|
|
||||||
import {
|
|
||||||
BackofficeWrapper,
|
|
||||||
DataTable,
|
|
||||||
} from '@imphnen-frontend-service/ui/organisms';
|
|
||||||
import {
|
|
||||||
ColumnDef,
|
|
||||||
getCoreRowModel,
|
|
||||||
getPaginationRowModel,
|
|
||||||
PaginationState,
|
|
||||||
RowSelectionState,
|
|
||||||
useReactTable,
|
|
||||||
} from '@tanstack/react-table';
|
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
|
||||||
import { cn } from '@imphnen-frontend-service/utils';
|
|
||||||
import { EditOutlined } from '@ant-design/icons';
|
|
||||||
|
|
||||||
export const HackathonUsersPage: FC = (): ReactElement => {
|
|
||||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
|
|
||||||
const [pagination, setPagination] = useState<PaginationState>({
|
|
||||||
pageIndex: 0,
|
|
||||||
pageSize: 9,
|
|
||||||
});
|
|
||||||
|
|
||||||
const mockData: any[] = Array.from({ length: 90 }, (_, i) => ({
|
|
||||||
id: i + 1,
|
|
||||||
project_name: `Project ${i + 1}`,
|
|
||||||
repository_url: `https://github.com/user/repo${i + 1}`,
|
|
||||||
demo_url: `https://demo.example.com/project${i + 1}`,
|
|
||||||
presentation_url: `https://slides.example.com/project${i + 1}`,
|
|
||||||
}));
|
|
||||||
|
|
||||||
type UserStatus = 'active' | 'inactive';
|
|
||||||
|
|
||||||
interface SubmissionType {
|
|
||||||
id: number;
|
|
||||||
project_name: string;
|
|
||||||
repository_url: string;
|
|
||||||
demo_url: string;
|
|
||||||
presentation_url: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const columns: ColumnDef<SubmissionType>[] = [
|
|
||||||
{
|
|
||||||
header: 'Project Name',
|
|
||||||
accessorKey: 'project_name',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Repository URL',
|
|
||||||
accessorKey: 'repository_url',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Demo URL',
|
|
||||||
accessorKey: 'demo_url',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Presentation URL',
|
|
||||||
accessorKey: 'presentation_url',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Action',
|
|
||||||
meta: { cellClassName: cn('w-72') },
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="sm"
|
|
||||||
className="flex items-center gap-2 w-max"
|
|
||||||
onClick={() => {
|
|
||||||
// View detail logic
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<EditOutlined className="text-base" /> View & Manage
|
|
||||||
</Button>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const table = useReactTable({
|
|
||||||
data: mockData,
|
|
||||||
columns,
|
|
||||||
state: {
|
|
||||||
pagination,
|
|
||||||
rowSelection,
|
|
||||||
},
|
|
||||||
enableRowSelection: true,
|
|
||||||
onRowSelectionChange: setRowSelection,
|
|
||||||
getCoreRowModel: getCoreRowModel(),
|
|
||||||
getPaginationRowModel: getPaginationRowModel(),
|
|
||||||
onPaginationChange: setPagination,
|
|
||||||
pageCount: Math.ceil(mockData.length / pagination.pageSize),
|
|
||||||
manualPagination: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<BackofficeWrapper title="IMPHNEN x Kolosal.ai Hackathon 2025">
|
|
||||||
<h1 className="mb-8 text-p1 font-semibold text-neutral-700">
|
|
||||||
Project Submission
|
|
||||||
</h1>
|
|
||||||
{/* Filters and actions */}
|
|
||||||
<section className="bg-white rounded-md shadow p-8 flex flex-col gap-6">
|
|
||||||
<div className="flex flex-wrap gap-3 items-center">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
className="border border-neutral-200 rounded-md px-3 py-2 text-label1 w-full sm:w-64"
|
|
||||||
placeholder="Search name or email"
|
|
||||||
/>
|
|
||||||
<select className="border border-neutral-200 rounded-md px-3 py-2 text-label1 w-full sm:w-40">
|
|
||||||
<option value="all">All Status</option>
|
|
||||||
<option value="active">Active</option>
|
|
||||||
<option value="suspended">Suspended</option>
|
|
||||||
</select>
|
|
||||||
<select className="border border-neutral-200 rounded-md px-3 py-2 text-label1 w-full sm:w-40">
|
|
||||||
<option value="all">All City</option>
|
|
||||||
<option value="jakarta">Jakarta</option>
|
|
||||||
<option value="bandung">Bandung</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Table */}
|
|
||||||
<DataTable data={mockData} columns={columns} table={table} />
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Modals extracted into shared backoffice components */}
|
|
||||||
</BackofficeWrapper>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default HackathonUsersPage;
|
|
||||||
-822
@@ -1,822 +0,0 @@
|
|||||||
import { FC, useState, useEffect, useMemo, useRef } from 'react';
|
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
|
||||||
import { cn } from '@imphnen-frontend-service/utils';
|
|
||||||
import TeamBannerPlaceholder from './team-banner-placeholder';
|
|
||||||
import { CityFilterSelect } from '../../../../components/city-filter-select';
|
|
||||||
import {
|
|
||||||
TeamOutlined,
|
|
||||||
CalendarOutlined,
|
|
||||||
SaveOutlined,
|
|
||||||
CloseOutlined,
|
|
||||||
ExclamationOutlined,
|
|
||||||
UserOutlined,
|
|
||||||
DeleteOutlined,
|
|
||||||
EyeOutlined,
|
|
||||||
EyeInvisibleOutlined,
|
|
||||||
CrownOutlined,
|
|
||||||
CheckCircleOutlined,
|
|
||||||
ClockCircleOutlined,
|
|
||||||
CloseCircleOutlined,
|
|
||||||
CameraOutlined,
|
|
||||||
UploadOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
|
|
||||||
interface TeamMember {
|
|
||||||
id: string;
|
|
||||||
joined_at: string;
|
|
||||||
role: 'leader' | 'member';
|
|
||||||
status: 'pending' | 'accepted' | 'rejected';
|
|
||||||
team_id: string;
|
|
||||||
user: {
|
|
||||||
avatar?: string;
|
|
||||||
bio?: string;
|
|
||||||
created_at: string;
|
|
||||||
email: string;
|
|
||||||
fullname: string;
|
|
||||||
id: string;
|
|
||||||
is_active: boolean;
|
|
||||||
location: string;
|
|
||||||
phone_number?: string;
|
|
||||||
skills: string[];
|
|
||||||
updated_at: string;
|
|
||||||
};
|
|
||||||
user_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TeamType {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
city: string;
|
|
||||||
banner?: string;
|
|
||||||
logo?: string;
|
|
||||||
visibility: 'public' | 'private';
|
|
||||||
member_count: number;
|
|
||||||
has_submission: boolean;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
leader_id: string;
|
|
||||||
members: TeamMember[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ModalProps {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
team: TeamType | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ModalTeamDetail: FC<ModalProps> = ({ isOpen, onClose, team }) => {
|
|
||||||
const [formData, setFormData] = useState<TeamType | null>(null);
|
|
||||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
|
||||||
const [activeTab, setActiveTab] = useState<'details' | 'members'>('details');
|
|
||||||
const [showLogoMenu, setShowLogoMenu] = useState(false);
|
|
||||||
const logoInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
const bannerInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
|
|
||||||
// Initialize form data when modal opens
|
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
if (team) {
|
|
||||||
// Edit existing team
|
|
||||||
setFormData({ ...team });
|
|
||||||
} else {
|
|
||||||
// Create new team
|
|
||||||
setFormData({
|
|
||||||
id: '', // Will be generated by backend
|
|
||||||
name: '',
|
|
||||||
description: '',
|
|
||||||
city: '',
|
|
||||||
banner: undefined,
|
|
||||||
logo: undefined,
|
|
||||||
visibility: 'public',
|
|
||||||
member_count: 1,
|
|
||||||
has_submission: false,
|
|
||||||
created_at: new Date().toISOString(),
|
|
||||||
updated_at: new Date().toISOString(),
|
|
||||||
leader_id: '',
|
|
||||||
members: [],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [isOpen, team]);
|
|
||||||
|
|
||||||
// Check if form has changes
|
|
||||||
const hasChanges = useMemo(() => {
|
|
||||||
if (!formData) return false;
|
|
||||||
if (!team) return true; // New team always has changes
|
|
||||||
return (
|
|
||||||
formData.name !== team.name ||
|
|
||||||
formData.description !== team.description ||
|
|
||||||
formData.city !== team.city ||
|
|
||||||
formData.visibility !== team.visibility ||
|
|
||||||
formData.logo !== team.logo ||
|
|
||||||
formData.banner !== team.banner
|
|
||||||
);
|
|
||||||
}, [formData, team]);
|
|
||||||
|
|
||||||
// Check if required fields are filled
|
|
||||||
const isFormValid = useMemo(() => {
|
|
||||||
if (!formData) return false;
|
|
||||||
return formData.name.trim() !== '' && formData.city.trim() !== '';
|
|
||||||
}, [formData]);
|
|
||||||
|
|
||||||
const canSave = hasChanges && isFormValid;
|
|
||||||
|
|
||||||
// Get leader and other members
|
|
||||||
const leader = team?.members.find((m) => m.role === 'leader');
|
|
||||||
const acceptedMembers =
|
|
||||||
team?.members.filter((m) => m.status === 'accepted') || [];
|
|
||||||
const pendingMembers =
|
|
||||||
team?.members.filter((m) => m.status === 'pending') || [];
|
|
||||||
|
|
||||||
if (!isOpen || !formData) return null;
|
|
||||||
|
|
||||||
const handleInputChange = (
|
|
||||||
field: keyof TeamType,
|
|
||||||
value: string | boolean | 'public' | 'private' | undefined
|
|
||||||
) => {
|
|
||||||
setFormData((prev) => (prev ? { ...prev, [field]: value } : null));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = () => {
|
|
||||||
if (!formData) return;
|
|
||||||
|
|
||||||
console.log('Saving team:', formData);
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = () => {
|
|
||||||
if (!team) return;
|
|
||||||
|
|
||||||
console.log('Deleting team:', team.id);
|
|
||||||
setShowDeleteConfirm(false);
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLogoUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = event.target.files?.[0];
|
|
||||||
if (file) {
|
|
||||||
if (!file.type.startsWith('image/')) {
|
|
||||||
alert('Please select an image file');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (file.size > 5 * 1024 * 1024) {
|
|
||||||
alert('Image size must be less than 5MB');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = (e) => {
|
|
||||||
const logoUrl = e.target?.result as string;
|
|
||||||
handleInputChange('logo', logoUrl);
|
|
||||||
setShowLogoMenu(false);
|
|
||||||
};
|
|
||||||
reader.readAsDataURL(file);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleBannerUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = event.target.files?.[0];
|
|
||||||
if (file) {
|
|
||||||
if (!file.type.startsWith('image/')) {
|
|
||||||
alert('Please select an image file');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (file.size > 5 * 1024 * 1024) {
|
|
||||||
alert('Image size must be less than 5MB');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = (e) => {
|
|
||||||
const bannerUrl = e.target?.result as string;
|
|
||||||
handleInputChange('banner', bannerUrl);
|
|
||||||
};
|
|
||||||
reader.readAsDataURL(file);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRemoveLogo = () => {
|
|
||||||
handleInputChange('logo', undefined);
|
|
||||||
setShowLogoMenu(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRemoveBanner = () => {
|
|
||||||
handleInputChange('banner', undefined);
|
|
||||||
};
|
|
||||||
|
|
||||||
const triggerLogoUpload = () => {
|
|
||||||
logoInputRef.current?.click();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
|
||||||
<div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="flex items-center justify-between p-6 border-b border-neutral-200">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="w-10 h-10 rounded-full bg-primary-100 flex items-center justify-center">
|
|
||||||
<TeamOutlined className="text-primary-600 text-lg" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h2 className="text-xl font-semibold text-neutral-900">
|
|
||||||
{team ? 'Team Details' : 'Create New Team'}
|
|
||||||
</h2>
|
|
||||||
<p className="text-sm text-neutral-500">
|
|
||||||
{team
|
|
||||||
? 'View and manage team information'
|
|
||||||
: 'Add a new team to the hackathon'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
className="p-2 hover:bg-neutral-100 rounded-lg transition-colors cursor-pointer"
|
|
||||||
onClick={() => {
|
|
||||||
setShowLogoMenu(false);
|
|
||||||
onClose();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CloseOutlined className="text-neutral-400 text-lg" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content */}
|
|
||||||
<div className="p-6 space-y-6" onClick={() => setShowLogoMenu(false)}>
|
|
||||||
{/* Hidden File Inputs */}
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
ref={logoInputRef}
|
|
||||||
onChange={handleLogoUpload}
|
|
||||||
accept="image/*"
|
|
||||||
className="hidden"
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
ref={bannerInputRef}
|
|
||||||
onChange={handleBannerUpload}
|
|
||||||
accept="image/*"
|
|
||||||
className="hidden"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Interactive Banner Section */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Team Banner
|
|
||||||
<span className="text-xs text-neutral-500 ml-2">
|
|
||||||
(3:1 aspect ratio recommended)
|
|
||||||
</span>
|
|
||||||
</label>
|
|
||||||
<div className="relative group">
|
|
||||||
<TeamBannerPlaceholder
|
|
||||||
banner={formData.banner}
|
|
||||||
teamName={formData.name || 'Team Name'}
|
|
||||||
className="rounded-lg border border-neutral-200 transition-all group-hover:border-primary-300"
|
|
||||||
/>
|
|
||||||
{/* Banner Action Buttons */}
|
|
||||||
<div className="absolute inset-0 bg-black/40 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3">
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="sm"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
bannerInputRef.current?.click();
|
|
||||||
}}
|
|
||||||
className="bg-white/90 hover:bg-white text-neutral-700 border-transparent shadow-sm gap-2"
|
|
||||||
>
|
|
||||||
<UploadOutlined className="text-sm" />
|
|
||||||
{formData.banner ? 'Change Banner' : 'Add Banner'}
|
|
||||||
</Button>
|
|
||||||
{formData.banner && (
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
handleRemoveBanner();
|
|
||||||
}}
|
|
||||||
className="bg-white/90 hover:bg-white text-red-600 border-transparent shadow-sm hover:text-red-700 gap-2"
|
|
||||||
>
|
|
||||||
<DeleteOutlined className="text-sm" />
|
|
||||||
Delete Banner
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Team Logo & Name Row */}
|
|
||||||
<div className="grid grid-cols-12 gap-4 items-start">
|
|
||||||
{/* Interactive Team Logo */}
|
|
||||||
<div className="col-span-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700 mb-2">
|
|
||||||
Logo
|
|
||||||
</label>
|
|
||||||
<div className="relative group">
|
|
||||||
<div className="w-24 h-24 rounded-full bg-neutral-100 flex items-center justify-center overflow-hidden border border-neutral-200 group-hover:border-primary-300 transition-colors">
|
|
||||||
{formData.logo ? (
|
|
||||||
<img
|
|
||||||
src={formData.logo}
|
|
||||||
alt={formData.name || 'Team Logo'}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<TeamOutlined className="text-neutral-400 text-xl" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{/* Logo Hover Overlay - Full circle */}
|
|
||||||
<button
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setShowLogoMenu(!showLogoMenu);
|
|
||||||
}}
|
|
||||||
className="absolute inset-0 bg-neutral-300/80 cursor-pointer rounded-full opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center w-24 h-24"
|
|
||||||
>
|
|
||||||
<CameraOutlined className="text-white text-lg" />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Logo Menu Dropdown */}
|
|
||||||
{showLogoMenu && (
|
|
||||||
<div className="absolute top-full left-0 mt-2 bg-white rounded-lg shadow-lg border border-neutral-200 py-2 min-w-[140px] z-10">
|
|
||||||
<button
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
triggerLogoUpload();
|
|
||||||
}}
|
|
||||||
className="w-full px-4 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-50 flex items-center gap-2 cursor-pointer"
|
|
||||||
>
|
|
||||||
<UploadOutlined className="text-sm" />
|
|
||||||
{formData.logo ? 'Change Logo' : 'Upload Logo'}
|
|
||||||
</button>
|
|
||||||
{formData.logo && (
|
|
||||||
<button
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
handleRemoveLogo();
|
|
||||||
}}
|
|
||||||
className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50 flex items-center gap-2 cursor-pointer"
|
|
||||||
>
|
|
||||||
<DeleteOutlined className="text-sm" />
|
|
||||||
Remove Logo
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Team Name */}
|
|
||||||
<div className="col-span-10 space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Team Name <span className="text-danger-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
className="w-full border border-neutral-200 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:outline-none"
|
|
||||||
placeholder="Enter team name"
|
|
||||||
value={formData.name}
|
|
||||||
onChange={(e) => handleInputChange('name', e.target.value)}
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-neutral-500">
|
|
||||||
Click logo to upload or change team logo (circular format)
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Team Description */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Description
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
className="w-full border border-neutral-200 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:outline-none resize-none"
|
|
||||||
placeholder="Enter team description (optional)"
|
|
||||||
rows={3}
|
|
||||||
value={formData.description || ''}
|
|
||||||
onChange={(e) => handleInputChange('description', e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* City */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
City <span className="text-danger-500">*</span>
|
|
||||||
</label>
|
|
||||||
<CityFilterSelect
|
|
||||||
value={formData.city || 'all'}
|
|
||||||
onChange={(city) =>
|
|
||||||
handleInputChange('city', city === 'all' ? '' : city)
|
|
||||||
}
|
|
||||||
className="w-full"
|
|
||||||
placeholder="Search cities..."
|
|
||||||
allOptionLabel="Select a city"
|
|
||||||
filterIcon={false}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Visibility */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Team Visibility
|
|
||||||
</label>
|
|
||||||
<div className="flex gap-4">
|
|
||||||
<label className="flex items-center gap-2 cursor-pointer">
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
name="visibility"
|
|
||||||
value="public"
|
|
||||||
checked={formData.visibility === 'public'}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleInputChange('visibility', e.target.value as 'public')
|
|
||||||
}
|
|
||||||
className="text-primary-600"
|
|
||||||
/>
|
|
||||||
<EyeOutlined className="text-info-600" />
|
|
||||||
<span className="text-sm">Public</span>
|
|
||||||
</label>
|
|
||||||
<label className="flex items-center gap-2 cursor-pointer">
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
name="visibility"
|
|
||||||
value="private"
|
|
||||||
checked={formData.visibility === 'private'}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleInputChange('visibility', e.target.value as 'private')
|
|
||||||
}
|
|
||||||
className="text-primary-600"
|
|
||||||
/>
|
|
||||||
<EyeInvisibleOutlined className="text-neutral-600" />
|
|
||||||
<span className="text-sm">Private</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Team Information (Read-only for existing teams) */}
|
|
||||||
{team && (
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Members
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-2 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<UserOutlined className="text-neutral-500" />
|
|
||||||
<span className="text-sm text-neutral-700">
|
|
||||||
{team.member_count} member
|
|
||||||
{team.member_count !== 1 ? 's' : ''}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Submission Status
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-2 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'w-2 h-2 rounded-full',
|
|
||||||
team.has_submission ? 'bg-success-500' : 'bg-danger-500'
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'text-sm font-medium',
|
|
||||||
team.has_submission
|
|
||||||
? 'text-success-700'
|
|
||||||
: 'text-danger-700'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{team.has_submission ? 'Submitted' : 'Not Submitted'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Tabs for Details and Members */}
|
|
||||||
{team && (
|
|
||||||
<div>
|
|
||||||
<div className="flex border-b border-neutral-200">
|
|
||||||
<button
|
|
||||||
className={cn(
|
|
||||||
'px-4 py-2 text-sm font-medium border-b-2 transition-colors cursor-pointer',
|
|
||||||
activeTab === 'details'
|
|
||||||
? 'border-primary-500 text-primary-600'
|
|
||||||
: 'border-transparent text-neutral-500 hover:text-neutral-700'
|
|
||||||
)}
|
|
||||||
onClick={() => setActiveTab('details')}
|
|
||||||
>
|
|
||||||
Team Details
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className={cn(
|
|
||||||
'px-4 py-2 text-sm font-medium border-b-2 transition-colors cursor-pointer',
|
|
||||||
activeTab === 'members'
|
|
||||||
? 'border-primary-500 text-primary-600'
|
|
||||||
: 'border-transparent text-neutral-500 hover:text-neutral-700'
|
|
||||||
)}
|
|
||||||
onClick={() => setActiveTab('members')}
|
|
||||||
>
|
|
||||||
Members ({team.member_count})
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="pt-4">
|
|
||||||
{activeTab === 'details' && (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{/* Leader Information */}
|
|
||||||
{leader && (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Team Leader
|
|
||||||
</label>
|
|
||||||
<div className="p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="w-10 h-10 rounded-full bg-neutral-200 flex items-center justify-center overflow-hidden">
|
|
||||||
{leader.user.avatar ? (
|
|
||||||
<img
|
|
||||||
src={leader.user.avatar}
|
|
||||||
alt={leader.user.fullname}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<CrownOutlined className="text-yellow-600 text-sm" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-neutral-900">
|
|
||||||
{leader.user.fullname}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-neutral-500">
|
|
||||||
{leader.user.email}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Timestamps */}
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Created
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-2 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<CalendarOutlined className="text-neutral-500" />
|
|
||||||
<span className="text-sm text-neutral-700">
|
|
||||||
{new Date(team.created_at).toLocaleDateString(
|
|
||||||
'en-US',
|
|
||||||
{
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Last Updated
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-2 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<CalendarOutlined className="text-neutral-500" />
|
|
||||||
<span className="text-sm text-neutral-700">
|
|
||||||
{new Date(team.updated_at).toLocaleDateString(
|
|
||||||
'en-US',
|
|
||||||
{
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{activeTab === 'members' && (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{/* Accepted Members */}
|
|
||||||
<div>
|
|
||||||
<h4 className="text-sm font-medium text-neutral-700 mb-3">
|
|
||||||
Active Members ({acceptedMembers.length})
|
|
||||||
</h4>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{acceptedMembers.map((member) => (
|
|
||||||
<div
|
|
||||||
key={member.id}
|
|
||||||
className="flex items-center gap-3 p-3 bg-neutral-50 rounded-lg"
|
|
||||||
>
|
|
||||||
<div className="w-10 h-10 rounded-full bg-neutral-200 flex items-center justify-center overflow-hidden">
|
|
||||||
{member.user.avatar ? (
|
|
||||||
<img
|
|
||||||
src={member.user.avatar}
|
|
||||||
alt={member.user.fullname}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<UserOutlined className="text-neutral-500" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<p className="text-sm font-medium text-neutral-900">
|
|
||||||
{member.user.fullname}
|
|
||||||
</p>
|
|
||||||
{member.role === 'leader' && (
|
|
||||||
<CrownOutlined className="text-yellow-600 text-xs" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-neutral-500">
|
|
||||||
{member.user.email}
|
|
||||||
</p>
|
|
||||||
{member.user.skills.length > 0 && (
|
|
||||||
<div className="flex flex-wrap gap-1 mt-1">
|
|
||||||
{member.user.skills
|
|
||||||
.slice(0, 2)
|
|
||||||
.map((skill, idx) => (
|
|
||||||
<span
|
|
||||||
key={idx}
|
|
||||||
className="px-1 py-0.5 bg-primary-100 text-primary-700 text-xs rounded"
|
|
||||||
>
|
|
||||||
{skill}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
{member.user.skills.length > 2 && (
|
|
||||||
<span className="text-xs text-neutral-400">
|
|
||||||
+{member.user.skills.length - 2}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-neutral-500">
|
|
||||||
Joined{' '}
|
|
||||||
{new Date(member.joined_at).toLocaleDateString()}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Pending Members */}
|
|
||||||
{pendingMembers.length > 0 && (
|
|
||||||
<div>
|
|
||||||
<h4 className="text-sm font-medium text-neutral-700 mb-3">
|
|
||||||
Pending Members ({pendingMembers.length})
|
|
||||||
</h4>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{pendingMembers.map((member) => (
|
|
||||||
<div
|
|
||||||
key={member.id}
|
|
||||||
className="flex items-center gap-3 p-3 bg-orange-50 border border-orange-200 rounded-lg"
|
|
||||||
>
|
|
||||||
<div className="w-10 h-10 rounded-full bg-neutral-200 flex items-center justify-center overflow-hidden">
|
|
||||||
{member.user.avatar ? (
|
|
||||||
<img
|
|
||||||
src={member.user.avatar}
|
|
||||||
alt={member.user.fullname}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<UserOutlined className="text-neutral-500" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<p className="text-sm font-medium text-neutral-900">
|
|
||||||
{member.user.fullname}
|
|
||||||
</p>
|
|
||||||
<ClockCircleOutlined className="text-orange-600 text-xs" />
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-neutral-500">
|
|
||||||
{member.user.email}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="sm"
|
|
||||||
className="flex items-center gap-1"
|
|
||||||
onClick={() =>
|
|
||||||
console.log('Accept member:', member.id)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<CheckCircleOutlined className="text-xs" />
|
|
||||||
Accept
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
className="flex items-center gap-1"
|
|
||||||
onClick={() =>
|
|
||||||
console.log('Reject member:', member.id)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<CloseCircleOutlined className="text-xs" />
|
|
||||||
Reject
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Footer */}
|
|
||||||
<div className="flex items-center justify-between p-6 border-t border-neutral-200">
|
|
||||||
<div>
|
|
||||||
{team && (
|
|
||||||
<Button
|
|
||||||
variant="danger"
|
|
||||||
size="md"
|
|
||||||
onClick={() => setShowDeleteConfirm(true)}
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<DeleteOutlined />
|
|
||||||
Delete Team
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button variant="secondary" size="md" onClick={onClose}>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="md"
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={!canSave}
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<SaveOutlined />
|
|
||||||
{team ? 'Save Changes' : 'Create Team'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Delete Confirmation Modal */}
|
|
||||||
{showDeleteConfirm && (
|
|
||||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-60 p-4">
|
|
||||||
<div className="bg-white rounded-lg shadow-xl w-full max-w-md">
|
|
||||||
<div className="p-6">
|
|
||||||
<div className="flex items-center gap-4 mb-4">
|
|
||||||
<div className="w-12 h-12 rounded-full bg-danger-100 flex items-center justify-center">
|
|
||||||
<ExclamationOutlined className="text-danger-600 text-xl" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold text-neutral-900">
|
|
||||||
Delete Team
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-neutral-500">
|
|
||||||
This action cannot be undone.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p className="text-sm text-neutral-700 mb-6">
|
|
||||||
Are you sure you want to delete "{team?.name}"? This will
|
|
||||||
permanently remove the team and all associated data.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3 justify-end">
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="md"
|
|
||||||
onClick={() => setShowDeleteConfirm(false)}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="danger"
|
|
||||||
size="md"
|
|
||||||
onClick={handleDelete}
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<DeleteOutlined />
|
|
||||||
Delete Team
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default ModalTeamDetail;
|
|
||||||
@@ -1,216 +0,0 @@
|
|||||||
import { FC } from 'react';
|
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
|
||||||
import {
|
|
||||||
CloseOutlined,
|
|
||||||
LinkOutlined,
|
|
||||||
ProjectOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
|
|
||||||
interface SubmissionModalProps {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
teamId: string;
|
|
||||||
teamName: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SubmissionModal: FC<SubmissionModalProps> = ({
|
|
||||||
isOpen,
|
|
||||||
onClose,
|
|
||||||
teamId,
|
|
||||||
teamName,
|
|
||||||
}) => {
|
|
||||||
if (!isOpen) return null;
|
|
||||||
|
|
||||||
// Mock submission data
|
|
||||||
const mockSubmission = {
|
|
||||||
id: `submission-${teamId}`,
|
|
||||||
project_name: `${teamName} Project`,
|
|
||||||
repository_url: `https://github.com/${teamName
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/\s+/g, '-')}/hackathon-project`,
|
|
||||||
demo_url: `https://${teamName
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/\s+/g, '-')}.vercel.app`,
|
|
||||||
presentation_url: `https://docs.google.com/presentation/d/${teamId}/edit`,
|
|
||||||
submitted_at: new Date().toISOString(),
|
|
||||||
status: 'submitted',
|
|
||||||
description:
|
|
||||||
'An innovative solution built during the IMPHNEN x Kolosal.ai Hackathon 2025.',
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
|
||||||
<div className="bg-white rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="flex items-center justify-between p-6 border-b border-neutral-200">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="w-10 h-10 rounded-full bg-success-100 flex items-center justify-center">
|
|
||||||
<ProjectOutlined className="text-success-600 text-lg" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h2 className="text-xl font-semibold text-neutral-900">
|
|
||||||
Project Submission
|
|
||||||
</h2>
|
|
||||||
<p className="text-sm text-neutral-500">
|
|
||||||
{teamName} - Hackathon Submission Details
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
className="p-2 hover:bg-neutral-100 rounded-lg transition-colors cursor-pointer"
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
<CloseOutlined className="text-neutral-400 text-lg" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content */}
|
|
||||||
<div className="p-6 space-y-6">
|
|
||||||
{/* Submission Status */}
|
|
||||||
<div className="flex items-center gap-3 p-4 bg-success-50 border border-success-200 rounded-lg">
|
|
||||||
<div className="w-3 h-3 rounded-full bg-success-500"></div>
|
|
||||||
<div>
|
|
||||||
<p className="text-sm font-medium text-success-800">
|
|
||||||
Submission Completed
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-success-600">
|
|
||||||
Submitted on{' '}
|
|
||||||
{new Date(mockSubmission.submitted_at).toLocaleDateString(
|
|
||||||
'en-UK',
|
|
||||||
{
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Project Information */}
|
|
||||||
<div className="grid gap-6">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Project Name
|
|
||||||
</label>
|
|
||||||
<p className="text-sm text-neutral-900 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
{mockSubmission.project_name}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Project Description
|
|
||||||
</label>
|
|
||||||
<p className="text-sm text-neutral-900 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
{mockSubmission.description}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Links Section */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Repository
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-2 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<span className="text-sm text-neutral-700 flex-1 truncate">
|
|
||||||
{mockSubmission.repository_url}
|
|
||||||
</span>
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
className="shrink-0"
|
|
||||||
onClick={() =>
|
|
||||||
window.open(mockSubmission.repository_url, '_blank')
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<LinkOutlined className="text-xs" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Live Demo
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-2 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<span className="text-sm text-neutral-700 flex-1 truncate">
|
|
||||||
{mockSubmission.demo_url}
|
|
||||||
</span>
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
className="shrink-0"
|
|
||||||
onClick={() =>
|
|
||||||
window.open(mockSubmission.demo_url, '_blank')
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<LinkOutlined className="text-xs" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="block text-sm font-medium text-neutral-700">
|
|
||||||
Presentation
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-2 p-3 bg-neutral-50 rounded-lg">
|
|
||||||
<span className="text-sm text-neutral-700 flex-1 truncate">
|
|
||||||
{mockSubmission.presentation_url}
|
|
||||||
</span>
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
className="shrink-0"
|
|
||||||
onClick={() =>
|
|
||||||
window.open(mockSubmission.presentation_url, '_blank')
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<LinkOutlined className="text-xs" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Action Note */}
|
|
||||||
<div className="p-4 bg-info-50 border border-info-200 rounded-lg">
|
|
||||||
<p className="text-sm text-info-800">
|
|
||||||
<strong>Note:</strong> This is a submission preview. The team has
|
|
||||||
successfully submitted their project. You can review the
|
|
||||||
submission details and access the project links above.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Footer */}
|
|
||||||
<div className="flex items-center justify-end p-6 border-t border-neutral-200">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button variant="secondary" size="md" onClick={onClose}>
|
|
||||||
Close
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="md"
|
|
||||||
onClick={() => {
|
|
||||||
// Navigate to hackathon-submissions page
|
|
||||||
console.log('Navigate to full submissions page');
|
|
||||||
// You can implement navigation here
|
|
||||||
onClose();
|
|
||||||
}}
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<ProjectOutlined />
|
|
||||||
View All Submissions
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default SubmissionModal;
|
|
||||||
-82
@@ -1,82 +0,0 @@
|
|||||||
import { FC } from 'react';
|
|
||||||
import { TeamOutlined } from '@ant-design/icons';
|
|
||||||
import { cn } from '@imphnen-frontend-service/utils';
|
|
||||||
|
|
||||||
interface TeamBannerPlaceholderProps {
|
|
||||||
banner?: string;
|
|
||||||
teamName: string;
|
|
||||||
className?: string;
|
|
||||||
showPlaceholder?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
const TeamBannerPlaceholder: FC<TeamBannerPlaceholderProps> = ({
|
|
||||||
banner,
|
|
||||||
teamName,
|
|
||||||
className = '',
|
|
||||||
showPlaceholder = true,
|
|
||||||
}) => {
|
|
||||||
const aspectRatioClass = 'aspect-[3/1]'; // 3:1 aspect ratio
|
|
||||||
|
|
||||||
if (!banner && !showPlaceholder) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (banner) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'w-full bg-gray-100 overflow-hidden relative',
|
|
||||||
aspectRatioClass,
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src={banner}
|
|
||||||
alt={`${teamName} banner`}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
onError={(e) => {
|
|
||||||
// Fallback to placeholder if image fails to load
|
|
||||||
const target = e.target as HTMLImageElement;
|
|
||||||
target.style.display = 'none';
|
|
||||||
const placeholder = target.nextElementSibling as HTMLElement;
|
|
||||||
if (placeholder) {
|
|
||||||
placeholder.style.display = 'flex';
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{/* Fallback placeholder (hidden by default, shown on image error) */}
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'absolute inset-0 bg-linear-to-r from-gray-100 to-gray-200 flex items-center justify-center',
|
|
||||||
'hidden' // Hidden by default
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="text-center">
|
|
||||||
<TeamOutlined className="text-4xl text-gray-400 mb-2" />
|
|
||||||
<p className="text-sm text-gray-500 font-medium">{teamName}</p>
|
|
||||||
<p className="text-xs text-gray-400">Team Banner</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// No banner - show placeholder
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'w-full bg-linear-to-r from-gray-100 to-gray-200 flex items-center justify-center',
|
|
||||||
aspectRatioClass,
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="text-center">
|
|
||||||
<TeamOutlined className="text-4xl text-gray-400 mb-2" />
|
|
||||||
<p className="text-sm text-gray-500 font-medium">{teamName}</p>
|
|
||||||
<p className="text-xs text-gray-400">No Banner</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default TeamBannerPlaceholder;
|
|
||||||
@@ -1,684 +0,0 @@
|
|||||||
import { FC, ReactElement, useState, useMemo, useCallback } from 'react';
|
|
||||||
import ModalTeamDetail from './_components/modal-team-detail-new';
|
|
||||||
import SubmissionModal from './_components/submission-modal';
|
|
||||||
import { CityFilterSelect } from '../../../components/city-filter-select';
|
|
||||||
import INDONESIAN_CITIES from '../../../constants/cities';
|
|
||||||
import {
|
|
||||||
BackofficeWrapper,
|
|
||||||
DataTable,
|
|
||||||
} from '@imphnen-frontend-service/ui/organisms';
|
|
||||||
import { ColumnDef } from '@tanstack/react-table';
|
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
|
||||||
import { cn } from '@imphnen-frontend-service/utils';
|
|
||||||
import {
|
|
||||||
EditOutlined,
|
|
||||||
TeamOutlined,
|
|
||||||
SearchOutlined,
|
|
||||||
FilterOutlined,
|
|
||||||
PlusOutlined,
|
|
||||||
UserOutlined,
|
|
||||||
ArrowRightOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
|
|
||||||
// Define interface outside component
|
|
||||||
interface TeamMember {
|
|
||||||
id: string;
|
|
||||||
joined_at: string;
|
|
||||||
role: 'leader' | 'member';
|
|
||||||
status: 'pending' | 'accepted' | 'rejected';
|
|
||||||
team_id: string;
|
|
||||||
user: {
|
|
||||||
avatar?: string;
|
|
||||||
bio?: string;
|
|
||||||
created_at: string;
|
|
||||||
email: string;
|
|
||||||
fullname: string;
|
|
||||||
id: string;
|
|
||||||
is_active: boolean;
|
|
||||||
location: string;
|
|
||||||
phone_number?: string;
|
|
||||||
skills: string[];
|
|
||||||
updated_at: string;
|
|
||||||
};
|
|
||||||
user_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TeamType {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
city: string;
|
|
||||||
banner?: string;
|
|
||||||
logo?: string;
|
|
||||||
visibility: 'public' | 'private';
|
|
||||||
member_count: number;
|
|
||||||
has_submission: boolean;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
leader_id: string;
|
|
||||||
members: TeamMember[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Move mock data outside component to prevent recreation
|
|
||||||
// Sample data for popular cities from the INDONESIAN_CITIES constant
|
|
||||||
const cities = INDONESIAN_CITIES.slice(0, 20); // Use first 20 cities for variety
|
|
||||||
const teamNames = [
|
|
||||||
'Innovators',
|
|
||||||
'Hackers',
|
|
||||||
'Builders',
|
|
||||||
'Creators',
|
|
||||||
'Pioneers',
|
|
||||||
'Developers',
|
|
||||||
'Engineers',
|
|
||||||
'Coders',
|
|
||||||
'Tech Stars',
|
|
||||||
'Digital Wizards',
|
|
||||||
];
|
|
||||||
|
|
||||||
const descriptions = [
|
|
||||||
'Building innovative solutions for modern problems with cutting-edge technology',
|
|
||||||
'Passionate developers creating the next generation of web applications',
|
|
||||||
'Focused on sustainable tech solutions that make a positive impact',
|
|
||||||
'Experienced team working on scalable fintech innovations',
|
|
||||||
'Creative minds developing user-centric mobile applications',
|
|
||||||
'Full-stack developers building comprehensive business solutions',
|
|
||||||
'AI enthusiasts creating intelligent automation tools',
|
|
||||||
'Open source advocates building community-driven platforms',
|
|
||||||
];
|
|
||||||
|
|
||||||
const skills = [
|
|
||||||
'Frontend Developer',
|
|
||||||
'Backend Developer',
|
|
||||||
'Full Stack Developer',
|
|
||||||
'DevOps Engineer',
|
|
||||||
'UI/UX Designer',
|
|
||||||
'Product Manager',
|
|
||||||
'Data Scientist',
|
|
||||||
'Mobile Developer',
|
|
||||||
];
|
|
||||||
|
|
||||||
const generateMembers = (
|
|
||||||
count: number,
|
|
||||||
teamId: string,
|
|
||||||
leaderId: string
|
|
||||||
): TeamMember[] => {
|
|
||||||
return Array.from({ length: count }, (_, i) => {
|
|
||||||
const isLeader = i === 0;
|
|
||||||
const memberId = isLeader ? leaderId : `user-${teamId}-${i}`;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: `member-${teamId}-${i}`,
|
|
||||||
joined_at: new Date(
|
|
||||||
Date.now() - (count - i) * 86400000 * Math.random() * 5
|
|
||||||
).toISOString(),
|
|
||||||
role: isLeader ? 'leader' : 'member',
|
|
||||||
status: Math.random() > 0.8 ? 'pending' : 'accepted',
|
|
||||||
team_id: teamId,
|
|
||||||
user: {
|
|
||||||
id: memberId,
|
|
||||||
avatar:
|
|
||||||
Math.random() > 0.6
|
|
||||||
? `https://ui-avatars.com/api/?name=${encodeURIComponent(
|
|
||||||
`User ${i}`
|
|
||||||
)}`
|
|
||||||
: undefined,
|
|
||||||
bio:
|
|
||||||
Math.random() > 0.5
|
|
||||||
? `Passionate ${skills[
|
|
||||||
Math.floor(Math.random() * skills.length)
|
|
||||||
].toLowerCase()} with ${
|
|
||||||
Math.floor(Math.random() * 8) + 1
|
|
||||||
}+ years experience`
|
|
||||||
: undefined,
|
|
||||||
created_at: new Date(
|
|
||||||
Date.now() - Math.random() * 365 * 86400000
|
|
||||||
).toISOString(),
|
|
||||||
email: `user${i}.team${teamId}@example.com`,
|
|
||||||
fullname: `${
|
|
||||||
['Ahmad', 'Sofia', 'Budi', 'Sari', 'Rizki', 'Maya', 'Andi', 'Dina'][
|
|
||||||
Math.floor(Math.random() * 8)
|
|
||||||
]
|
|
||||||
} ${
|
|
||||||
[
|
|
||||||
'Wijuana',
|
|
||||||
'Santoso',
|
|
||||||
'Pratama',
|
|
||||||
'Dewi',
|
|
||||||
'Nugroho',
|
|
||||||
'Sari',
|
|
||||||
'Putra',
|
|
||||||
'Lestari',
|
|
||||||
][Math.floor(Math.random() * 8)]
|
|
||||||
}`,
|
|
||||||
is_active: true,
|
|
||||||
location: cities[Math.floor(Math.random() * cities.length)],
|
|
||||||
phone_number:
|
|
||||||
Math.random() > 0.7
|
|
||||||
? `+62${Math.floor(Math.random() * 9000000000) + 1000000000}`
|
|
||||||
: undefined,
|
|
||||||
skills: skills.slice(0, Math.floor(Math.random() * 3) + 1),
|
|
||||||
updated_at: new Date().toISOString(),
|
|
||||||
},
|
|
||||||
user_id: memberId,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockData: TeamType[] = Array.from({ length: 50 }, (_, i) => {
|
|
||||||
const teamId = `team-${String(i + 1).padStart(3, '0')}`;
|
|
||||||
const memberCount = Math.floor(Math.random() * 5) + 1; // 1-5 members
|
|
||||||
const leaderId = `leader-${teamId}`;
|
|
||||||
const members = generateMembers(memberCount, teamId, leaderId);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: teamId,
|
|
||||||
name: `Team ${teamNames[i % teamNames.length]} ${
|
|
||||||
Math.floor(i / teamNames.length) + 1
|
|
||||||
}`,
|
|
||||||
description:
|
|
||||||
i % 4 === 0 ? undefined : descriptions[i % descriptions.length],
|
|
||||||
city: cities[i % cities.length],
|
|
||||||
banner:
|
|
||||||
i % 3 === 0 ? undefined : `https://picsum.photos/600/200?random=${i}`, // 3:1 aspect ratio
|
|
||||||
logo:
|
|
||||||
i % 4 === 0
|
|
||||||
? undefined
|
|
||||||
: `https://ui-avatars.com/api/?name=${encodeURIComponent(
|
|
||||||
teamNames[i % teamNames.length]
|
|
||||||
)}&background=random&size=120`,
|
|
||||||
visibility: i % 4 === 0 ? 'private' : 'public',
|
|
||||||
member_count: memberCount,
|
|
||||||
has_submission: i % 3 !== 0,
|
|
||||||
created_at: new Date(
|
|
||||||
Date.now() - i * 86400000 * (Math.random() * 15 + 1)
|
|
||||||
).toISOString(),
|
|
||||||
updated_at: new Date().toISOString(),
|
|
||||||
leader_id: leaderId,
|
|
||||||
members: members,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
export const HackathonTeamsPage: FC = (): ReactElement => {
|
|
||||||
const [showDetailModal, setShowDetailModal] = useState(false);
|
|
||||||
const [showNewTeamModal, setShowNewTeamModal] = useState(false);
|
|
||||||
const [showSubmissionModal, setShowSubmissionModal] = useState(false);
|
|
||||||
const [selectedTeam, setSelectedTeam] = useState<TeamType | null>(null);
|
|
||||||
const [selectedSubmissionTeam, setSelectedSubmissionTeam] =
|
|
||||||
useState<TeamType | null>(null);
|
|
||||||
const [globalFilter, setGlobalFilter] = useState('');
|
|
||||||
|
|
||||||
// Advanced filtering states
|
|
||||||
const [visibilityFilter, setVisibilityFilter] = useState('all');
|
|
||||||
const [cityFilter, setCityFilter] = useState('all');
|
|
||||||
const [submissionFilter, setSubmissionFilter] = useState('all');
|
|
||||||
const [memberCountFilter, setMemberCountFilter] = useState('all');
|
|
||||||
|
|
||||||
// Constants
|
|
||||||
const pageSize = 10;
|
|
||||||
|
|
||||||
// Memoize the callback to prevent recreation
|
|
||||||
const handleShowDetailModal = useCallback((team: TeamType) => {
|
|
||||||
setSelectedTeam(team);
|
|
||||||
setShowDetailModal(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleCloseDetailModal = useCallback(() => {
|
|
||||||
setShowDetailModal(false);
|
|
||||||
setSelectedTeam(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleShowNewTeamModal = useCallback(() => {
|
|
||||||
setShowNewTeamModal(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleCloseNewTeamModal = useCallback(() => {
|
|
||||||
setShowNewTeamModal(false);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleShowSubmissionModal = useCallback((team: TeamType) => {
|
|
||||||
setSelectedSubmissionTeam(team);
|
|
||||||
setShowSubmissionModal(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleCloseSubmissionModal = useCallback(() => {
|
|
||||||
setShowSubmissionModal(false);
|
|
||||||
setSelectedSubmissionTeam(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Filter data based on current filter states
|
|
||||||
const filteredData = useMemo(() => {
|
|
||||||
return mockData.filter((team) => {
|
|
||||||
// Global search filter
|
|
||||||
if (globalFilter) {
|
|
||||||
const searchTerm = globalFilter.toLowerCase();
|
|
||||||
const leaderName =
|
|
||||||
team.members.find((m) => m.role === 'leader')?.user.fullname || '';
|
|
||||||
const memberNames = team.members.map((m) => m.user.fullname).join(' ');
|
|
||||||
|
|
||||||
if (
|
|
||||||
!team.name.toLowerCase().includes(searchTerm) &&
|
|
||||||
!team.city.toLowerCase().includes(searchTerm) &&
|
|
||||||
!leaderName.toLowerCase().includes(searchTerm) &&
|
|
||||||
!memberNames.toLowerCase().includes(searchTerm)
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Visibility filter
|
|
||||||
if (visibilityFilter !== 'all' && team.visibility !== visibilityFilter) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// City filter
|
|
||||||
if (cityFilter !== 'all' && team.city !== cityFilter) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Submission filter
|
|
||||||
if (submissionFilter !== 'all') {
|
|
||||||
const hasSubmission = submissionFilter === 'submitted';
|
|
||||||
if (team.has_submission !== hasSubmission) return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Member count filter
|
|
||||||
if (memberCountFilter !== 'all') {
|
|
||||||
const count = parseInt(memberCountFilter);
|
|
||||||
if (team.member_count !== count) return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}, [
|
|
||||||
globalFilter,
|
|
||||||
visibilityFilter,
|
|
||||||
cityFilter,
|
|
||||||
submissionFilter,
|
|
||||||
memberCountFilter,
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Memoize columns to prevent recreation on every render
|
|
||||||
const columns: ColumnDef<TeamType>[] = useMemo(
|
|
||||||
() => [
|
|
||||||
{
|
|
||||||
accessorKey: 'name',
|
|
||||||
header: 'Team',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const team = row.original;
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
{/* Team Logo */}
|
|
||||||
<div className="w-10 h-10 rounded-full bg-neutral-100 flex items-center justify-center shrink-0 overflow-hidden">
|
|
||||||
{team.logo ? (
|
|
||||||
<img
|
|
||||||
src={team.logo}
|
|
||||||
alt={team.name}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<TeamOutlined className="text-neutral-400 text-lg" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{/* Team Name & Description */}
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<p className="font-medium text-neutral-900 truncate">
|
|
||||||
{team.name}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
enableSorting: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'city',
|
|
||||||
header: 'City',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<span className="text-neutral-700">{row.original.city}</span>
|
|
||||||
),
|
|
||||||
enableSorting: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'visibility',
|
|
||||||
header: 'Visibility',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const isPublic = row.original.visibility === 'public';
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'inline-flex items-center gap-1 px-2 py-1 rounded-2xl text-xs font-medium',
|
|
||||||
isPublic
|
|
||||||
? 'bg-success-100 text-success-800'
|
|
||||||
: 'bg-neutral-100 text-neutral-700'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{isPublic ? 'Public' : 'Private'}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
enableSorting: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'member_count',
|
|
||||||
header: 'Members',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<UserOutlined className="text-neutral-400 text-sm" />
|
|
||||||
<span className="text-sm text-neutral-700">
|
|
||||||
{row.original.member_count}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
enableSorting: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'leader',
|
|
||||||
header: 'Leader',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const leader = row.original.members.find(
|
|
||||||
(m) => m.role === 'leader'
|
|
||||||
)?.user;
|
|
||||||
return leader ? (
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium text-neutral-900">
|
|
||||||
{leader.fullname}
|
|
||||||
</div>
|
|
||||||
<div className="text-xs text-neutral-500">{leader.email}</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-neutral-400 italic">No leader</span>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
enableSorting: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'has_submission',
|
|
||||||
header: 'Submission',
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const hasSubmission = row.original.has_submission;
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'w-2 h-2 rounded-full',
|
|
||||||
hasSubmission ? 'bg-success-500' : 'bg-danger-500'
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'text-sm font-medium',
|
|
||||||
hasSubmission ? 'text-success-700' : 'text-danger-700'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{hasSubmission ? 'Submitted' : 'Not Submitted'}
|
|
||||||
</span>
|
|
||||||
{hasSubmission && (
|
|
||||||
<button
|
|
||||||
className="text-xs text-primary-600 hover:text-primary-800 text-left cursor-pointer"
|
|
||||||
onClick={() => handleShowSubmissionModal(row.original)}
|
|
||||||
>
|
|
||||||
View Submission <ArrowRightOutlined />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
enableSorting: true,
|
|
||||||
sortingFn: (rowA, rowB) => {
|
|
||||||
const aSubmission = rowA.original.has_submission;
|
|
||||||
const bSubmission = rowB.original.has_submission;
|
|
||||||
if (aSubmission && !bSubmission) return -1;
|
|
||||||
if (!aSubmission && bSubmission) return 1;
|
|
||||||
return 0;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'created_at',
|
|
||||||
header: 'Created',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<span className="text-neutral-900 text-sm">
|
|
||||||
{new Date(row.original.created_at).toLocaleDateString('en-UK', {
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'short',
|
|
||||||
day: 'numeric',
|
|
||||||
})}
|
|
||||||
</span>
|
|
||||||
),
|
|
||||||
enableSorting: true,
|
|
||||||
sortingFn: 'datetime',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'actions',
|
|
||||||
header: 'Actions',
|
|
||||||
meta: { cellClassName: cn('w-48') },
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="sm"
|
|
||||||
className="flex items-center gap-2 text-sm px-4 py-2"
|
|
||||||
onClick={() => handleShowDetailModal(row.original)}
|
|
||||||
>
|
|
||||||
<EditOutlined className="text-sm" />
|
|
||||||
Manage
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
enableSorting: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[handleShowDetailModal, handleShowSubmissionModal]
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<BackofficeWrapper title="IMPHNEN x Kolosal.ai Hackathon 2025">
|
|
||||||
<h1 className="mb-8 text-p1 font-semibold text-neutral-700">
|
|
||||||
Team Management
|
|
||||||
</h1>
|
|
||||||
{/* Filters and actions */}
|
|
||||||
<section className="bg-white rounded-md shadow p-8 flex flex-col gap-6">
|
|
||||||
<div className="flex flex-wrap gap-3 items-center justify-between">
|
|
||||||
{/* Left side - Search & filters */}
|
|
||||||
<div className="flex flex-wrap gap-3 items-center">
|
|
||||||
{/* Search bar */}
|
|
||||||
<div className="relative">
|
|
||||||
<SearchOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm" />
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
className="border border-neutral-200 rounded-lg pl-10 pr-4 py-2.5 text-sm w-full sm:w-80 focus:border-primary-500 focus:outline-none"
|
|
||||||
placeholder="Search teams by name, city, or leader..."
|
|
||||||
value={globalFilter}
|
|
||||||
onChange={(e) => setGlobalFilter(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Visibility Filter */}
|
|
||||||
<div className="relative">
|
|
||||||
<FilterOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm pointer-events-none z-10" />
|
|
||||||
<select
|
|
||||||
className="border border-neutral-200 rounded-lg pl-10 pr-10 py-2.5 text-sm w-full sm:w-40 focus:border-primary-500 focus:outline-none appearance-none bg-white cursor-pointer"
|
|
||||||
value={visibilityFilter}
|
|
||||||
onChange={(e) => setVisibilityFilter(e.target.value)}
|
|
||||||
>
|
|
||||||
<option value="all">All Visibility</option>
|
|
||||||
<option value="public">Public</option>
|
|
||||||
<option value="private">Private</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* City Filter */}
|
|
||||||
<CityFilterSelect
|
|
||||||
value={cityFilter}
|
|
||||||
onChange={setCityFilter}
|
|
||||||
className="w-full sm:w-44"
|
|
||||||
placeholder="Search cities..."
|
|
||||||
allOptionLabel="All Cities"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Member Count Filter */}
|
|
||||||
<div className="relative">
|
|
||||||
<FilterOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm pointer-events-none z-10" />
|
|
||||||
<select
|
|
||||||
className="border border-neutral-200 rounded-lg pl-10 pr-10 py-2.5 text-sm w-full sm:w-55 focus:border-primary-500 focus:outline-none appearance-none bg-white cursor-pointer"
|
|
||||||
value={memberCountFilter}
|
|
||||||
onChange={(e) => setMemberCountFilter(e.target.value)}
|
|
||||||
>
|
|
||||||
<option value="all">All Member Count</option>
|
|
||||||
<option value="1">1 Member</option>
|
|
||||||
<option value="2">2 Members</option>
|
|
||||||
<option value="3">3 Members</option>
|
|
||||||
<option value="4">4 Members</option>
|
|
||||||
<option value="5">5 Members</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Submission Filter */}
|
|
||||||
<div className="relative">
|
|
||||||
<FilterOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm pointer-events-none z-10" />
|
|
||||||
<select
|
|
||||||
className="border border-neutral-200 rounded-lg pl-10 pr-10 py-2.5 text-sm w-full sm:w-44 focus:border-primary-500 focus:outline-none appearance-none bg-white cursor-pointer"
|
|
||||||
value={submissionFilter}
|
|
||||||
onChange={(e) => setSubmissionFilter(e.target.value)}
|
|
||||||
>
|
|
||||||
<option value="all">All Submissions</option>
|
|
||||||
<option value="submitted">Submitted</option>
|
|
||||||
<option value="not_submitted">Not Submitted</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right side - Add Team Button */}
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="md"
|
|
||||||
className="flex items-center gap-2 px-4 py-2"
|
|
||||||
onClick={handleShowNewTeamModal}
|
|
||||||
>
|
|
||||||
<PlusOutlined className="text-sm" />
|
|
||||||
Add Team
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Active filters display */}
|
|
||||||
{(visibilityFilter !== 'all' ||
|
|
||||||
cityFilter !== 'all' ||
|
|
||||||
submissionFilter !== 'all' ||
|
|
||||||
memberCountFilter !== 'all') && (
|
|
||||||
<div className="flex flex-wrap gap-2 items-center">
|
|
||||||
<span className="text-sm text-neutral-600">Active filters:</span>
|
|
||||||
|
|
||||||
{/* Visibility filter badge */}
|
|
||||||
{visibilityFilter !== 'all' && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-1 bg-info-100 text-info-800 rounded-2xl text-sm">
|
|
||||||
Visibility: {visibilityFilter}
|
|
||||||
<button
|
|
||||||
onClick={() => setVisibilityFilter('all')}
|
|
||||||
className="text-info-600 hover:text-info-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* City filter badge */}
|
|
||||||
{cityFilter !== 'all' && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-800 rounded-2xl text-sm">
|
|
||||||
City: {cityFilter}
|
|
||||||
<button
|
|
||||||
onClick={() => setCityFilter('all')}
|
|
||||||
className="text-green-600 hover:text-green-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Member count filter badge */}
|
|
||||||
{memberCountFilter !== 'all' && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-1 bg-blue-100 text-blue-800 rounded-2xl text-sm">
|
|
||||||
Members: {memberCountFilter}
|
|
||||||
<button
|
|
||||||
onClick={() => setMemberCountFilter('all')}
|
|
||||||
className="text-blue-600 hover:text-blue-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Submission filter badge */}
|
|
||||||
{submissionFilter !== 'all' && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-1 bg-purple-100 text-purple-800 rounded-2xl text-sm">
|
|
||||||
Submission: {submissionFilter}
|
|
||||||
<button
|
|
||||||
onClick={() => setSubmissionFilter('all')}
|
|
||||||
className="text-purple-600 hover:text-purple-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Clear all filters */}
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => {
|
|
||||||
setVisibilityFilter('all');
|
|
||||||
setCityFilter('all');
|
|
||||||
setSubmissionFilter('all');
|
|
||||||
setMemberCountFilter('all');
|
|
||||||
setGlobalFilter('');
|
|
||||||
}}
|
|
||||||
className="text-sm text-neutral-600"
|
|
||||||
>
|
|
||||||
Clear All
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Pagination-aware results display */}
|
|
||||||
{filteredData.length > 0 && (
|
|
||||||
<div className="text-sm text-neutral-600">
|
|
||||||
Showing {Math.min(pageSize, filteredData.length)} of{' '}
|
|
||||||
{filteredData.length} teams
|
|
||||||
{filteredData.length > pageSize}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Table */}
|
|
||||||
<DataTable data={filteredData} columns={columns} pageSize={10} />
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Modals component */}
|
|
||||||
<ModalTeamDetail
|
|
||||||
isOpen={showDetailModal}
|
|
||||||
onClose={handleCloseDetailModal}
|
|
||||||
team={selectedTeam}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* New Team Modal */}
|
|
||||||
<ModalTeamDetail
|
|
||||||
isOpen={showNewTeamModal}
|
|
||||||
onClose={handleCloseNewTeamModal}
|
|
||||||
team={null} // null indicates creating new team
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Submission Modal */}
|
|
||||||
{selectedSubmissionTeam && (
|
|
||||||
<SubmissionModal
|
|
||||||
isOpen={showSubmissionModal}
|
|
||||||
onClose={handleCloseSubmissionModal}
|
|
||||||
teamId={selectedSubmissionTeam.id}
|
|
||||||
teamName={selectedSubmissionTeam.name}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</BackofficeWrapper>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default HackathonTeamsPage;
|
|
||||||
-651
@@ -1,651 +0,0 @@
|
|||||||
import { FC, useState, useEffect, useMemo, useRef } from 'react';
|
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
|
||||||
import { cn } from '@imphnen-frontend-service/utils';
|
|
||||||
import {
|
|
||||||
UserOutlined,
|
|
||||||
EnvironmentOutlined,
|
|
||||||
CalendarOutlined,
|
|
||||||
SaveOutlined,
|
|
||||||
CloseOutlined,
|
|
||||||
ExclamationOutlined,
|
|
||||||
CameraOutlined,
|
|
||||||
DeleteOutlined,
|
|
||||||
UploadOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
|
|
||||||
interface UserType {
|
|
||||||
id: string;
|
|
||||||
avatar?: string;
|
|
||||||
fullname: string;
|
|
||||||
bio?: string;
|
|
||||||
location: string;
|
|
||||||
is_active: boolean;
|
|
||||||
skills: string[];
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ModalProps {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
user: UserType | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ModalUserDetail: FC<ModalProps> = ({ isOpen, onClose, user }) => {
|
|
||||||
const [formData, setFormData] = useState<UserType | null>(null);
|
|
||||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
|
||||||
const [showAvatarMenu, setShowAvatarMenu] = useState(false);
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
|
|
||||||
// Initialize form data when modal opens
|
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
if (user) {
|
|
||||||
// Edit existing user
|
|
||||||
setFormData({ ...user });
|
|
||||||
} else {
|
|
||||||
// Create new user
|
|
||||||
setFormData({
|
|
||||||
id: '', // Will be generated by backend
|
|
||||||
fullname: '',
|
|
||||||
bio: '',
|
|
||||||
location: '',
|
|
||||||
is_active: true,
|
|
||||||
skills: [],
|
|
||||||
avatar: undefined,
|
|
||||||
created_at: new Date().toISOString(),
|
|
||||||
updated_at: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [isOpen, user]);
|
|
||||||
|
|
||||||
// Check if form has changes
|
|
||||||
const hasChanges = useMemo(() => {
|
|
||||||
if (!formData) return false;
|
|
||||||
if (!user) return true; // New user always has changes
|
|
||||||
return (
|
|
||||||
formData.fullname !== user.fullname ||
|
|
||||||
formData.location !== user.location ||
|
|
||||||
formData.is_active !== user.is_active ||
|
|
||||||
formData.avatar !== user.avatar ||
|
|
||||||
JSON.stringify(formData.skills) !== JSON.stringify(user.skills) ||
|
|
||||||
formData.bio !== user.bio
|
|
||||||
);
|
|
||||||
}, [formData, user]);
|
|
||||||
|
|
||||||
// Check if required fields are filled
|
|
||||||
const isFormValid = useMemo(() => {
|
|
||||||
if (!formData) return false;
|
|
||||||
return formData.fullname.trim() !== '' && formData.location.trim() !== '';
|
|
||||||
}, [formData]);
|
|
||||||
|
|
||||||
const canSave = hasChanges && isFormValid;
|
|
||||||
|
|
||||||
if (!isOpen || !formData) return null;
|
|
||||||
|
|
||||||
const handleInputChange = (
|
|
||||||
field: keyof UserType,
|
|
||||||
value: string | boolean | string[] | undefined
|
|
||||||
) => {
|
|
||||||
setFormData((prev) => (prev ? { ...prev, [field]: value } : null));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSkillsChange = (skills: string[]) => {
|
|
||||||
setFormData((prev) => (prev ? { ...prev, skills } : null));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = () => {
|
|
||||||
if (!formData) return;
|
|
||||||
|
|
||||||
if (user) {
|
|
||||||
// Update existing user
|
|
||||||
console.log('Update user data:', formData);
|
|
||||||
} else {
|
|
||||||
// Create new user
|
|
||||||
console.log('Create new user:', formData);
|
|
||||||
}
|
|
||||||
// Here you would typically make an API call to save the data
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = () => {
|
|
||||||
if (user) {
|
|
||||||
setFormData({ ...user }); // Reset to original for edit mode
|
|
||||||
}
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDeleteAccount = () => {
|
|
||||||
if (!user) return; // Can't delete new user
|
|
||||||
console.log('Delete user:', user.id);
|
|
||||||
setShowDeleteConfirm(false);
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleAvatarUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = event.target.files?.[0];
|
|
||||||
if (file) {
|
|
||||||
// Validate file type
|
|
||||||
if (!file.type.startsWith('image/')) {
|
|
||||||
alert('Please select an image file');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file size (max 5MB)
|
|
||||||
if (file.size > 5 * 1024 * 1024) {
|
|
||||||
alert('Image size must be less than 5MB');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create preview URL
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = (e) => {
|
|
||||||
const avatarUrl = e.target?.result as string;
|
|
||||||
handleInputChange('avatar', avatarUrl);
|
|
||||||
setShowAvatarMenu(false);
|
|
||||||
};
|
|
||||||
reader.readAsDataURL(file);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRemoveAvatar = () => {
|
|
||||||
handleInputChange('avatar', undefined);
|
|
||||||
setShowAvatarMenu(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const triggerFileUpload = () => {
|
|
||||||
fileInputRef.current?.click();
|
|
||||||
};
|
|
||||||
|
|
||||||
const availableSkills = [
|
|
||||||
'Frontend Developer',
|
|
||||||
'Backend Developer',
|
|
||||||
'Full Stack Developer',
|
|
||||||
'DevOps Engineer',
|
|
||||||
'UI/UX Designer',
|
|
||||||
'Product Manager',
|
|
||||||
'Data Scientist',
|
|
||||||
'Mobile Developer',
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50">
|
|
||||||
<div
|
|
||||||
className="fixed inset-0 bg-black/50"
|
|
||||||
onClick={(e) => {
|
|
||||||
setShowAvatarMenu(false);
|
|
||||||
onClose();
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
|
||||||
<div
|
|
||||||
className="bg-white rounded-xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto"
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
{/* Hidden File Input */}
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
ref={fileInputRef}
|
|
||||||
onChange={handleAvatarUpload}
|
|
||||||
accept="image/*"
|
|
||||||
className="hidden"
|
|
||||||
/>
|
|
||||||
{/* Header */}
|
|
||||||
<div className="border-b border-neutral-200 px-8 py-6 flex justify-between items-start">
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
{/* Interactive User Avatar */}
|
|
||||||
<div className="relative group ">
|
|
||||||
<div className="w-16 h-16 rounded-full bg-neutral-200 flex items-center justify-center overflow-hidden border-2 border-transparent group-hover:border-primary-300 transition-colors">
|
|
||||||
{formData.avatar ? (
|
|
||||||
<img
|
|
||||||
src={formData.avatar}
|
|
||||||
alt={formData.fullname}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<UserOutlined className="text-neutral-500 text-2xl" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Avatar Hover Overlay */}
|
|
||||||
<button
|
|
||||||
onClick={() => setShowAvatarMenu(!showAvatarMenu)}
|
|
||||||
className="absolute inset-0 bg-neutral-400 cursor-pointer rounded-full opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
|
|
||||||
>
|
|
||||||
<CameraOutlined className="text-white text-lg" />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{/* Avatar Menu Dropdown */}
|
|
||||||
{showAvatarMenu && (
|
|
||||||
<div className="absolute top-full left-0 mt-2 bg-white rounded-lg shadow-lg border border-neutral-200 py-2 min-w-[140px] z-10">
|
|
||||||
<button
|
|
||||||
onClick={triggerFileUpload}
|
|
||||||
className="w-full px-4 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-50 flex items-center gap-2 cursor-pointer"
|
|
||||||
>
|
|
||||||
<UploadOutlined className="text-sm" />
|
|
||||||
{formData.avatar ? 'Change Photo' : 'Upload Photo'}
|
|
||||||
</button>
|
|
||||||
{formData.avatar && (
|
|
||||||
<button
|
|
||||||
onClick={handleRemoveAvatar}
|
|
||||||
className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50 flex items-center gap-2 cursor-pointer"
|
|
||||||
>
|
|
||||||
<DeleteOutlined className="text-sm" />
|
|
||||||
Remove Photo
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="flex items-center gap-3 mb-2">
|
|
||||||
<h2 className="text-2xl font-bold text-neutral-900">
|
|
||||||
{user ? 'Edit User Profile' : 'Create New User'}
|
|
||||||
</h2>
|
|
||||||
{user && (
|
|
||||||
<span className="px-3 py-1 bg-info-100 text-info-700 text-xs font-medium rounded-2xl">
|
|
||||||
Hover avatar to change
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="text-sm text-neutral-500">
|
|
||||||
{user
|
|
||||||
? `Make changes to ${
|
|
||||||
formData.fullname || 'this user'
|
|
||||||
}'s profile information`
|
|
||||||
: 'Fill in the information below to create a new user account'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
className="p-2 hover:bg-neutral-100 rounded-lg transition-colors"
|
|
||||||
onClick={() => {
|
|
||||||
setShowAvatarMenu(false);
|
|
||||||
handleCancel();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CloseOutlined className="text-neutral-400 text-lg cursor-pointer" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content */}
|
|
||||||
<div className="p-8" onClick={() => setShowAvatarMenu(false)}>
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
|
||||||
{/* Left Column - Basic Info */}
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold text-neutral-900 mb-4">
|
|
||||||
Basic Information
|
|
||||||
</h3>
|
|
||||||
<div className="space-y-4">
|
|
||||||
{/* Full Name - Required */}
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<UserOutlined className="text-neutral-400" />
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="text-sm text-neutral-500 block mb-1">
|
|
||||||
Full Name <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={formData.fullname}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleInputChange('fullname', e.target.value)
|
|
||||||
}
|
|
||||||
className={cn(
|
|
||||||
'w-full border rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:outline-none',
|
|
||||||
formData.fullname.trim() === ''
|
|
||||||
? 'border-red-300 bg-red-50'
|
|
||||||
: 'border-neutral-300'
|
|
||||||
)}
|
|
||||||
placeholder="Enter full name"
|
|
||||||
/>
|
|
||||||
{formData.fullname.trim() === '' && (
|
|
||||||
<p className="text-red-500 text-xs mt-1">
|
|
||||||
Full name is required
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Location - Required */}
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<EnvironmentOutlined className="text-neutral-400" />
|
|
||||||
<div className="flex-1">
|
|
||||||
<label className="text-sm text-neutral-500 block mb-1">
|
|
||||||
Location <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={formData.location}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleInputChange('location', e.target.value)
|
|
||||||
}
|
|
||||||
className={cn(
|
|
||||||
'w-full border rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:outline-none bg-white',
|
|
||||||
formData.location.trim() === ''
|
|
||||||
? 'border-red-300 bg-red-50'
|
|
||||||
: 'border-neutral-300'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<option value="">Select location</option>
|
|
||||||
<option value="Jakarta">Jakarta</option>
|
|
||||||
<option value="Bandung">Bandung</option>
|
|
||||||
<option value="Surabaya">Surabaya</option>
|
|
||||||
<option value="Medan">Medan</option>
|
|
||||||
<option value="Yogyakarta">Yogyakarta</option>
|
|
||||||
</select>
|
|
||||||
{formData.location.trim() === '' && (
|
|
||||||
<p className="text-red-500 text-xs mt-1">
|
|
||||||
Location is required
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Joined Date - Read Only - Only show for existing users */}
|
|
||||||
{user && (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<CalendarOutlined className="text-neutral-400" />
|
|
||||||
<div>
|
|
||||||
<p className="text-sm text-neutral-500">
|
|
||||||
Joined Date
|
|
||||||
</p>
|
|
||||||
<p className="font-medium">
|
|
||||||
{new Date(formData.created_at).toLocaleDateString(
|
|
||||||
'en-US',
|
|
||||||
{
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
day: 'numeric',
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Bio Section - Optional */}
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold text-neutral-900 mb-3">
|
|
||||||
Bio{' '}
|
|
||||||
<span className="text-neutral-400 text-sm font-normal">
|
|
||||||
(Optional)
|
|
||||||
</span>
|
|
||||||
</h3>
|
|
||||||
<textarea
|
|
||||||
value={formData.bio || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleInputChange('bio', e.target.value || undefined)
|
|
||||||
}
|
|
||||||
placeholder="Tell us about yourself..."
|
|
||||||
rows={4}
|
|
||||||
className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:outline-none resize-none"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right Column - Skills & Status */}
|
|
||||||
<div className="space-y-6">
|
|
||||||
{/* Account Status - Enhanced Tab Design */}
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold text-neutral-900 mb-4">
|
|
||||||
Account Status
|
|
||||||
</h3>
|
|
||||||
<div className="flex bg-neutral-100 p-1 rounded-lg">
|
|
||||||
<button
|
|
||||||
onClick={() => handleInputChange('is_active', true)}
|
|
||||||
className={cn(
|
|
||||||
'flex-1 px-4 py-2 text-sm font-medium rounded-md transition-all duration-200 cursor-pointer',
|
|
||||||
formData.is_active
|
|
||||||
? 'bg-white text-success-700 shadow-sm ring-1 ring-success-200'
|
|
||||||
: 'text-neutral-600 hover:text-neutral-800'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-center gap-2">
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'w-2 h-2 rounded-full',
|
|
||||||
formData.is_active
|
|
||||||
? 'bg-success-500'
|
|
||||||
: 'bg-neutral-400'
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
Active
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => handleInputChange('is_active', false)}
|
|
||||||
className={cn(
|
|
||||||
'flex-1 px-4 py-2 text-sm font-medium rounded-md transition-all duration-200 cursor-pointer',
|
|
||||||
!formData.is_active
|
|
||||||
? 'bg-white text-neutral-700 shadow-sm ring-1 ring-neutral-200'
|
|
||||||
: 'text-neutral-600 hover:text-neutral-800'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-center gap-2">
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'w-2 h-2 rounded-full',
|
|
||||||
!formData.is_active
|
|
||||||
? 'bg-neutral-500'
|
|
||||||
: 'bg-neutral-400'
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
Inactive
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-neutral-500 mt-2">
|
|
||||||
{formData.is_active
|
|
||||||
? 'User can access their account and participate in activities'
|
|
||||||
: 'User account is suspended and cannot access services'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Skills Section - Optional */}
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold text-neutral-900 mb-4">
|
|
||||||
Skills & Expertise{' '}
|
|
||||||
<span className="text-neutral-400 text-sm font-normal">
|
|
||||||
(Optional)
|
|
||||||
</span>
|
|
||||||
</h3>
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex flex-wrap gap-2 min-h-10 p-3 border border-neutral-300 rounded-lg bg-neutral-50">
|
|
||||||
{formData.skills.length > 0 ? (
|
|
||||||
formData.skills.map((skill, index) => (
|
|
||||||
<span
|
|
||||||
key={index}
|
|
||||||
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-2xl text-sm font-medium bg-blue-100 text-blue-800"
|
|
||||||
>
|
|
||||||
{skill}
|
|
||||||
<button
|
|
||||||
onClick={() =>
|
|
||||||
handleSkillsChange(
|
|
||||||
formData.skills.filter((_, i) => i !== index)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
className="text-blue-600 hover:text-blue-800 ml-1 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
))
|
|
||||||
) : (
|
|
||||||
<span className="text-neutral-400 text-sm">
|
|
||||||
No skills added yet
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<select
|
|
||||||
value=""
|
|
||||||
onChange={(e) => {
|
|
||||||
if (
|
|
||||||
e.target.value &&
|
|
||||||
!formData.skills.includes(e.target.value)
|
|
||||||
) {
|
|
||||||
handleSkillsChange([
|
|
||||||
...formData.skills,
|
|
||||||
e.target.value,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm focus:border-primary-500 focus:outline-none bg-white"
|
|
||||||
>
|
|
||||||
<option value="">Add a skill...</option>
|
|
||||||
{availableSkills
|
|
||||||
.filter((skill) => !formData.skills.includes(skill))
|
|
||||||
.map((skill) => (
|
|
||||||
<option key={skill} value={skill}>
|
|
||||||
{skill}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Account Details - Read Only - Only show for existing users */}
|
|
||||||
{user && (
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold text-neutral-900 mb-4">
|
|
||||||
Account Details
|
|
||||||
</h3>
|
|
||||||
<div className="space-y-3 bg-neutral-50 p-4 rounded-lg">
|
|
||||||
<div className="flex justify-between items-center py-1">
|
|
||||||
<span className="text-neutral-600 text-sm">
|
|
||||||
User ID
|
|
||||||
</span>
|
|
||||||
<span className="font-mono text-sm text-neutral-800">
|
|
||||||
{formData.id}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex justify-between items-center py-1">
|
|
||||||
<span className="text-neutral-600 text-sm">
|
|
||||||
Last Updated
|
|
||||||
</span>
|
|
||||||
<span className="text-sm text-neutral-800">
|
|
||||||
{new Date(formData.updated_at).toLocaleDateString(
|
|
||||||
'en-US',
|
|
||||||
{
|
|
||||||
month: 'short',
|
|
||||||
day: 'numeric',
|
|
||||||
year: 'numeric',
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Footer Actions */}
|
|
||||||
<div className="border-t border-neutral-200 px-8 py-6">
|
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<div className="text-sm text-neutral-500">
|
|
||||||
{canSave
|
|
||||||
? 'Ready to save changes'
|
|
||||||
: hasChanges
|
|
||||||
? 'Please fill required fields'
|
|
||||||
: 'No changes made'}
|
|
||||||
</div>
|
|
||||||
{/* Delete Account Button - Only show for existing users */}
|
|
||||||
{user && (
|
|
||||||
<button
|
|
||||||
onClick={() => setShowDeleteConfirm(true)}
|
|
||||||
className="text-red-600 hover:text-red-700 text-sm font-medium transition-colors cursor-pointer"
|
|
||||||
>
|
|
||||||
Delete Account
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleCancel}
|
|
||||||
className="px-6"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={!canSave}
|
|
||||||
className={cn(
|
|
||||||
'flex items-center gap-2 px-6',
|
|
||||||
!canSave && 'opacity-50 cursor-not-allowed'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<SaveOutlined className="text-sm" />
|
|
||||||
{user ? 'Save Changes' : 'Create User'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Delete Confirmation Modal */}
|
|
||||||
{showDeleteConfirm && (
|
|
||||||
<div className="fixed inset-0 z-60">
|
|
||||||
<div
|
|
||||||
className="fixed inset-0 bg-black/50"
|
|
||||||
onClick={() => setShowDeleteConfirm(false)}
|
|
||||||
/>
|
|
||||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
|
||||||
<div className="bg-white rounded-xl shadow-2xl w-full max-w-md">
|
|
||||||
<div className="p-6">
|
|
||||||
<div className="flex items-center gap-3 mb-4">
|
|
||||||
<div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
|
|
||||||
<ExclamationOutlined className="text-red-600 text-lg" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold text-neutral-900">
|
|
||||||
Delete Account
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-neutral-500">
|
|
||||||
This action cannot be undone
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p className="text-neutral-700 mb-6">
|
|
||||||
Are you sure you want to permanently delete{' '}
|
|
||||||
<strong>{formData.fullname}</strong>'s account? This will
|
|
||||||
remove all their data and cannot be reversed.
|
|
||||||
</p>
|
|
||||||
<div className="flex gap-3 justify-end">
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setShowDeleteConfirm(false)}
|
|
||||||
className="px-4"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleDeleteAccount}
|
|
||||||
className="px-4 bg-red-600 hover:bg-red-700 border-red-600"
|
|
||||||
>
|
|
||||||
Delete Account
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default ModalUserDetail;
|
|
||||||
@@ -1,479 +0,0 @@
|
|||||||
import { FC, ReactElement, useState, useMemo, useCallback } from 'react';
|
|
||||||
import ModalUserDetail from './_components/modal-user-detail';
|
|
||||||
import {
|
|
||||||
BackofficeWrapper,
|
|
||||||
DataTable,
|
|
||||||
} from '@imphnen-frontend-service/ui/organisms';
|
|
||||||
import { ColumnDef } from '@tanstack/react-table';
|
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
|
||||||
import { cn } from '@imphnen-frontend-service/utils';
|
|
||||||
import {
|
|
||||||
EditOutlined,
|
|
||||||
UserOutlined,
|
|
||||||
SearchOutlined,
|
|
||||||
FilterOutlined,
|
|
||||||
PlusOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
import { CityFilterSelect } from '../../../components/city-filter-select';
|
|
||||||
|
|
||||||
// Define interface outside component
|
|
||||||
interface UserType {
|
|
||||||
id: string; // UUID
|
|
||||||
avatar?: string;
|
|
||||||
fullname: string;
|
|
||||||
bio?: string;
|
|
||||||
location: string;
|
|
||||||
is_active: boolean; // admin can deactivate
|
|
||||||
skills: string[]; // Frontend Developer, Backend Developer, etc.
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Move mock data outside component to prevent recreation
|
|
||||||
const skillsOptions = [
|
|
||||||
'Frontend Developer',
|
|
||||||
'Backend Developer',
|
|
||||||
'Full Stack Developer',
|
|
||||||
'DevOps Engineer',
|
|
||||||
'UI/UX Designer',
|
|
||||||
'Product Manager',
|
|
||||||
'Data Scientist',
|
|
||||||
'Mobile Developer',
|
|
||||||
];
|
|
||||||
|
|
||||||
const locations = ['Jakarta', 'Bandung', 'Surabaya', 'Medan', 'Yogyakarta'];
|
|
||||||
const bios = [
|
|
||||||
'Passionate developer with 5+ years experience',
|
|
||||||
'Tech enthusiast and problem solver',
|
|
||||||
'Building scalable solutions for modern problems',
|
|
||||||
'Creative designer with technical background',
|
|
||||||
'Data-driven decision maker',
|
|
||||||
];
|
|
||||||
|
|
||||||
const mockData: UserType[] = Array.from({ length: 50 }, (_, i) => {
|
|
||||||
const randomSkillsCount = Math.floor(Math.random() * 3) + 1; // 1-3 skills
|
|
||||||
const randomSkills = skillsOptions
|
|
||||||
.sort(() => 0.5 - Math.random())
|
|
||||||
.slice(0, randomSkillsCount);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: `24db9e4d-ca4c-46aa-ac36-8ef04bbe01${String(i).padStart(2, '0')}`,
|
|
||||||
avatar:
|
|
||||||
i % 4 === 0
|
|
||||||
? `https://ui-avatars.com/api/?name=${encodeURIComponent(
|
|
||||||
i % 3 === 0 ? 'Ahmad Wijuana' : 'Sofia Wijuana'
|
|
||||||
)}&background=random`
|
|
||||||
: undefined,
|
|
||||||
fullname:
|
|
||||||
i % 3 === 0
|
|
||||||
? 'Ahmad Wijuana'
|
|
||||||
: i % 3 === 1
|
|
||||||
? 'Sofia Wijuana'
|
|
||||||
: 'Budi Santoso',
|
|
||||||
bio: i % 4 === 0 ? bios[i % bios.length] : undefined,
|
|
||||||
location: locations[i % locations.length],
|
|
||||||
is_active: i % 7 !== 0, // More realistic distribution
|
|
||||||
skills: randomSkills,
|
|
||||||
created_at: new Date(
|
|
||||||
Date.now() - i * 86400000 * (Math.random() * 30 + 1)
|
|
||||||
).toISOString(), // Random within last 30-60 days
|
|
||||||
updated_at: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
export const HackathonUsersPage: FC = (): ReactElement => {
|
|
||||||
const [showDetailModal, setShowDetailModal] = useState(false);
|
|
||||||
const [showNewUserModal, setShowNewUserModal] = useState(false);
|
|
||||||
const [selectedUser, setSelectedUser] = useState<UserType | null>(null);
|
|
||||||
const [globalFilter, setGlobalFilter] = useState('');
|
|
||||||
|
|
||||||
// Advanced filtering states
|
|
||||||
const [statusFilter, setStatusFilter] = useState('all');
|
|
||||||
const [cityFilter, setCityFilter] = useState('all');
|
|
||||||
const [skillsFilter, setSkillsFilter] = useState<string[]>([]);
|
|
||||||
|
|
||||||
// Constants
|
|
||||||
const pageSize = 10;
|
|
||||||
|
|
||||||
// Memoize the callback to prevent recreation
|
|
||||||
const handleShowDetailModal = useCallback((user: UserType) => {
|
|
||||||
setSelectedUser(user);
|
|
||||||
setShowDetailModal(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleCloseDetailModal = useCallback(() => {
|
|
||||||
setShowDetailModal(false);
|
|
||||||
setSelectedUser(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleShowNewUserModal = useCallback(() => {
|
|
||||||
setShowNewUserModal(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleCloseNewUserModal = useCallback(() => {
|
|
||||||
setShowNewUserModal(false);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Filter data based on current filter states
|
|
||||||
const filteredData = useMemo(() => {
|
|
||||||
return mockData.filter((user) => {
|
|
||||||
// Status filter
|
|
||||||
if (statusFilter !== 'all') {
|
|
||||||
const isActive = statusFilter === 'active';
|
|
||||||
if (user.is_active !== isActive) return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// City filter
|
|
||||||
if (cityFilter !== 'all' && user.location !== cityFilter) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skills filter
|
|
||||||
if (skillsFilter.length > 0) {
|
|
||||||
const hasMatchingSkill = skillsFilter.some((skill) =>
|
|
||||||
user.skills.includes(skill)
|
|
||||||
);
|
|
||||||
if (!hasMatchingSkill) return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}, [statusFilter, cityFilter, skillsFilter]);
|
|
||||||
|
|
||||||
// Memoize columns to prevent recreation on every render
|
|
||||||
const columns: ColumnDef<UserType>[] = useMemo(
|
|
||||||
() => [
|
|
||||||
{
|
|
||||||
accessorKey: 'fullname',
|
|
||||||
header: 'User',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
{/* Avatar */}
|
|
||||||
<div className="w-10 h-10 rounded-full bg-neutral-200 flex items-center justify-center overflow-hidden shrink-0">
|
|
||||||
{row.original.avatar ? (
|
|
||||||
<img
|
|
||||||
src={row.original.avatar}
|
|
||||||
alt={row.original.fullname}
|
|
||||||
className="w-full h-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<UserOutlined className="text-neutral-500 text-lg" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{/* Name only */}
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<p className="font-medium text-neutral-900 truncate">
|
|
||||||
{row.original.fullname}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
enableSorting: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'skills',
|
|
||||||
header: 'Skills',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex flex-wrap gap-1 max-w-xs">
|
|
||||||
{row.original.skills.slice(0, 2).map((skill, index) => (
|
|
||||||
<span
|
|
||||||
key={index}
|
|
||||||
className="inline-flex items-center px-2 py-1 rounded-2xl text-xs font-medium bg-success-100 text-success-800"
|
|
||||||
>
|
|
||||||
{skill.replace(' Developer', '').replace(' Engineer', '')}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
{row.original.skills.length > 2 && (
|
|
||||||
<span className="inline-flex items-center px-2 py-1 rounded-2xl text-xs font-medium bg-success-200 text-success-700">
|
|
||||||
+{row.original.skills.length - 2}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
enableSorting: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'location',
|
|
||||||
header: 'Location',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<span className="text-neutral-700">{row.original.location}</span>
|
|
||||||
),
|
|
||||||
enableSorting: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'is_active',
|
|
||||||
header: 'Status',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'w-2 h-2 rounded-full',
|
|
||||||
row.original.is_active ? 'bg-success-500' : 'bg-neutral-400'
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'text-sm font-medium',
|
|
||||||
row.original.is_active ? 'text-success-700' : 'text-neutral-500'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{row.original.is_active ? 'Active' : 'Inactive'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
enableSorting: true,
|
|
||||||
sortingFn: (rowA, rowB) => {
|
|
||||||
const aActive = rowA.original.is_active;
|
|
||||||
const bActive = rowB.original.is_active;
|
|
||||||
if (aActive && !bActive) return -1;
|
|
||||||
if (!aActive && bActive) return 1;
|
|
||||||
return 0;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'created_at',
|
|
||||||
header: 'Joined',
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<span className="text-neutral-900 text-sm">
|
|
||||||
{new Date(row.original.created_at).toLocaleDateString('en-US', {
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'short',
|
|
||||||
day: 'numeric',
|
|
||||||
})}
|
|
||||||
</span>
|
|
||||||
),
|
|
||||||
enableSorting: true,
|
|
||||||
sortingFn: 'datetime',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'actions',
|
|
||||||
header: 'Actions',
|
|
||||||
meta: { cellClassName: cn('w-48') },
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="sm"
|
|
||||||
className="flex items-center gap-2 text-sm px-4 py-2"
|
|
||||||
onClick={() => handleShowDetailModal(row.original)}
|
|
||||||
>
|
|
||||||
<EditOutlined className="text-sm" />
|
|
||||||
Manage
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
className="text-sm px-4 py-2"
|
|
||||||
onClick={() => {
|
|
||||||
// Toggle user status - implement later
|
|
||||||
console.log(`Toggle status for ${row.original.fullname}`);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{row.original.is_active ? 'Deactivate' : 'Activate'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
enableSorting: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[handleShowDetailModal]
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<BackofficeWrapper title="IMPHNEN x Kolosal.ai Hackathon 2025">
|
|
||||||
<h1 className="mb-8 text-p1 font-semibold text-neutral-700">
|
|
||||||
User Management
|
|
||||||
</h1>
|
|
||||||
{/* Filters and actions */}
|
|
||||||
<section className="bg-white rounded-md shadow p-8 flex flex-col gap-6">
|
|
||||||
<div className="flex flex-wrap gap-3 items-center justify-between">
|
|
||||||
{/* Left side - Search & filters */}
|
|
||||||
<div className="flex flex-wrap gap-3 items-center">
|
|
||||||
{/* Search bar */}
|
|
||||||
<div className="relative">
|
|
||||||
<SearchOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm" />
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
className="border border-neutral-200 rounded-lg pl-10 pr-4 py-2.5 text-sm w-full sm:w-80 focus:border-primary-500 focus:outline-none"
|
|
||||||
placeholder="Search users by name or location..."
|
|
||||||
value={globalFilter}
|
|
||||||
onChange={(e) => setGlobalFilter(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Status Filter */}
|
|
||||||
<div className="relative">
|
|
||||||
<FilterOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm pointer-events-none z-10" />
|
|
||||||
<select
|
|
||||||
className="border border-neutral-200 rounded-lg pl-10 pr-10 py-2.5 text-sm w-full sm:w-36 focus:border-primary-500 focus:outline-none appearance-none bg-white cursor-pointer"
|
|
||||||
value={statusFilter}
|
|
||||||
onChange={(e) => setStatusFilter(e.target.value)}
|
|
||||||
>
|
|
||||||
<option value="all">All Status</option>
|
|
||||||
<option value="active">Active</option>
|
|
||||||
<option value="inactive">Inactive</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* City Filter */}
|
|
||||||
<CityFilterSelect
|
|
||||||
value={cityFilter}
|
|
||||||
onChange={setCityFilter}
|
|
||||||
className="w-full sm:w-44"
|
|
||||||
placeholder="Search cities..."
|
|
||||||
allOptionLabel="All Cities"
|
|
||||||
/>
|
|
||||||
{cityFilter !== 'all' && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-800 rounded-2xl text-sm">
|
|
||||||
Location: {cityFilter}
|
|
||||||
<button
|
|
||||||
onClick={() => setCityFilter('all')}
|
|
||||||
className="text-green-600 hover:text-green-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Skills Filter with Icon */}
|
|
||||||
<div className="relative">
|
|
||||||
<FilterOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm pointer-events-none z-10" />
|
|
||||||
<select
|
|
||||||
className="border border-neutral-200 rounded-lg pl-10 pr-10 py-2.5 text-sm w-full sm:w-44 focus:border-primary-500 focus:outline-none appearance-none bg-white cursor-pointer"
|
|
||||||
value=""
|
|
||||||
onChange={(e) => {
|
|
||||||
if (
|
|
||||||
e.target.value &&
|
|
||||||
!skillsFilter.includes(e.target.value)
|
|
||||||
) {
|
|
||||||
setSkillsFilter((prev) => [...prev, e.target.value]);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<option value="">Add Skill Filter</option>
|
|
||||||
{skillsOptions.map((skill) => (
|
|
||||||
<option
|
|
||||||
key={skill}
|
|
||||||
value={skill}
|
|
||||||
disabled={skillsFilter.includes(skill)}
|
|
||||||
>
|
|
||||||
{skill}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Right side - Add User Button */}
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
size="md"
|
|
||||||
className="flex items-center gap-2 px-4 py-2"
|
|
||||||
onClick={handleShowNewUserModal}
|
|
||||||
>
|
|
||||||
<PlusOutlined className="text-sm" />
|
|
||||||
Add User
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Active filters display */}
|
|
||||||
{(skillsFilter.length > 0 ||
|
|
||||||
statusFilter !== 'all' ||
|
|
||||||
cityFilter !== 'all') && (
|
|
||||||
<div className="flex flex-wrap gap-2 items-center">
|
|
||||||
<span className="text-sm text-neutral-600">Active filters:</span>
|
|
||||||
|
|
||||||
{/* Status filter badge */}
|
|
||||||
{statusFilter !== 'all' && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-1 bg-info-100 text-info-800 rounded-2xl text-sm">
|
|
||||||
Status: {statusFilter}
|
|
||||||
<button
|
|
||||||
onClick={() => setStatusFilter('all')}
|
|
||||||
className="text-info-600 hover:text-info-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Location filter badge */}
|
|
||||||
{cityFilter !== 'all' && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-800 rounded-2xl text-sm">
|
|
||||||
City: {cityFilter}
|
|
||||||
<button
|
|
||||||
onClick={() => setCityFilter('all')}
|
|
||||||
className="text-green-600 hover:text-green-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Skills filter badges */}
|
|
||||||
{skillsFilter.map((skill) => (
|
|
||||||
<span
|
|
||||||
key={skill}
|
|
||||||
className="inline-flex items-center gap-1 px-2 py-1 bg-purple-100 text-purple-800 rounded-2xl text-sm"
|
|
||||||
>
|
|
||||||
{skill.replace(' Developer', '').replace(' Engineer', '')}
|
|
||||||
<button
|
|
||||||
onClick={() =>
|
|
||||||
setSkillsFilter((prev) => prev.filter((s) => s !== skill))
|
|
||||||
}
|
|
||||||
className="text-purple-600 hover:text-purple-800 cursor-pointer"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Clear all filters */}
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => {
|
|
||||||
setStatusFilter('all');
|
|
||||||
setCityFilter('all');
|
|
||||||
setSkillsFilter([]);
|
|
||||||
setGlobalFilter('');
|
|
||||||
}}
|
|
||||||
className="text-sm text-neutral-600"
|
|
||||||
>
|
|
||||||
Clear All
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Pagination-aware results display */}
|
|
||||||
{filteredData.length > 0 && (
|
|
||||||
<div className="text-sm text-neutral-600">
|
|
||||||
Showing {Math.min(pageSize, filteredData.length)} of{' '}
|
|
||||||
{filteredData.length} users
|
|
||||||
{filteredData.length > pageSize}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Table */}
|
|
||||||
<DataTable data={filteredData} columns={columns} pageSize={10} />
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Modals component */}
|
|
||||||
<ModalUserDetail
|
|
||||||
isOpen={showDetailModal}
|
|
||||||
onClose={handleCloseDetailModal}
|
|
||||||
user={selectedUser}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* New User Modal */}
|
|
||||||
<ModalUserDetail
|
|
||||||
isOpen={showNewUserModal}
|
|
||||||
onClose={handleCloseNewUserModal}
|
|
||||||
user={null} // null indicates creating new user
|
|
||||||
/>
|
|
||||||
</BackofficeWrapper>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default HackathonUsersPage;
|
|
||||||
@@ -1,51 +1,13 @@
|
|||||||
import { FC, ReactElement, useState } from 'react';
|
import { FC, ReactElement } from 'react';
|
||||||
import { Outlet } from 'react-router-dom';
|
import { Outlet } from 'react-router-dom';
|
||||||
import { BackofficeSidebar } from '@imphnen-frontend-service/ui/organisms';
|
import { BackofficeSidebar } from '@imphnen-frontend-service/ui/organisms';
|
||||||
|
|
||||||
export const AppLayout: FC = (): ReactElement => {
|
export const AppLayout: FC = (): ReactElement => {
|
||||||
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-primary-50 min-h-screen flex justify-center">
|
<div className="bg-primary-50 min-h-screen flex justify-center">
|
||||||
<div className="bg-primary-50 min-h-screen w-full flex">
|
<div className="bg-primary-50 min-h-screen w-full flex">
|
||||||
<BackofficeSidebar
|
<BackofficeSidebar />
|
||||||
isOpen={mobileSidebarOpen}
|
|
||||||
onClose={() => setMobileSidebarOpen(false)}
|
|
||||||
/>
|
|
||||||
<div className="flex-1 overflow-auto">
|
<div className="flex-1 overflow-auto">
|
||||||
{/* Sticky top header */}
|
|
||||||
<header
|
|
||||||
className={
|
|
||||||
'lg:hidden sticky top-0 bg-white border-b border-primary-200 px-4 py-3 flex items-center gap-3 ' +
|
|
||||||
(mobileSidebarOpen ? 'z-0' : 'z-30')
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{/* Mobile menu button (shown on small screens) */}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="lg:hidden p-2 rounded-md hover:bg-gray-100 text-gray-700"
|
|
||||||
onClick={() => setMobileSidebarOpen(true)}
|
|
||||||
aria-label="Open sidebar"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
className="w-5 h-5"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth={2}
|
|
||||||
d="M4 6h16M4 12h16M4 18h16"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
<h1 className="text-p3 font-semibold text-primary-700">
|
|
||||||
IMPHNEN Backoffice
|
|
||||||
</h1>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,29 +1,19 @@
|
|||||||
import { SearchOutlined } from '@ant-design/icons';
|
import { SearchOutlined } from "@ant-design/icons";
|
||||||
import { Button, Input, Select } from '@imphnen-frontend-service/ui/atoms';
|
import { Button, Input, Select } from "@imphnen-frontend-service/ui/atoms";
|
||||||
import {
|
import { BackofficeWrapper, DataTable } from "@imphnen-frontend-service/ui/organisms";
|
||||||
BackofficeWrapper,
|
import { cn, For } from "@imphnen-frontend-service/utils";
|
||||||
DataTable,
|
import { ColumnDef, getCoreRowModel, getPaginationRowModel, PaginationState, RowSelectionState, useReactTable } from "@tanstack/react-table";
|
||||||
} from '@imphnen-frontend-service/ui/organisms';
|
import { ReactElement, useState } from "react";
|
||||||
import { cn, For } from '@imphnen-frontend-service/utils';
|
import { ModalDetailUser } from "./_components/modal/detail";
|
||||||
import {
|
|
||||||
ColumnDef,
|
|
||||||
getCoreRowModel,
|
|
||||||
getPaginationRowModel,
|
|
||||||
PaginationState,
|
|
||||||
RowSelectionState,
|
|
||||||
useReactTable,
|
|
||||||
} from '@tanstack/react-table';
|
|
||||||
import { ReactElement, useState } from 'react';
|
|
||||||
import { ModalDetailUser } from './_components/modal/detail';
|
|
||||||
|
|
||||||
type UserStatus = 'active' | 'inactive';
|
type UserStatus = 'active' | 'inactive';
|
||||||
|
|
||||||
interface UserType {
|
interface UserType {
|
||||||
id: number;
|
id: number
|
||||||
name: string;
|
name: string
|
||||||
email: string;
|
email: string
|
||||||
rating: number;
|
rating: number
|
||||||
status: UserStatus;
|
status: UserStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
const mockData: UserType[] = Array.from({ length: 90 }, (_, i) => ({
|
const mockData: UserType[] = Array.from({ length: 90 }, (_, i) => ({
|
||||||
@@ -32,15 +22,15 @@ const mockData: UserType[] = Array.from({ length: 90 }, (_, i) => ({
|
|||||||
email: 'fullname23@gmail.com',
|
email: 'fullname23@gmail.com',
|
||||||
rating: 4.5,
|
rating: 4.5,
|
||||||
status: i % 2 === 0 ? 'active' : 'inactive',
|
status: i % 2 === 0 ? 'active' : 'inactive',
|
||||||
}));
|
}))
|
||||||
|
|
||||||
export default function Components(): ReactElement {
|
export default function Components(): ReactElement {
|
||||||
const TABS = ['mentor', 'mentee'] as const;
|
const TABS = ['mentor', 'mentee'] as const
|
||||||
const [activeTab, setActiveTab] = useState<'mentor' | 'mentee'>('mentor');
|
const [activeTab, setActiveTab] = useState<'mentor' | 'mentee'>('mentor')
|
||||||
const [showDetail, setShowDetail] = useState(false);
|
const [showDetail, setShowDetail] = useState(false)
|
||||||
const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
|
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
|
||||||
|
|
||||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
|
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
||||||
const [pagination, setPagination] = useState<PaginationState>({
|
const [pagination, setPagination] = useState<PaginationState>({
|
||||||
pageIndex: 0,
|
pageIndex: 0,
|
||||||
pageSize: 9,
|
pageSize: 9,
|
||||||
@@ -49,7 +39,7 @@ export default function Components(): ReactElement {
|
|||||||
const columns: ColumnDef<UserType>[] = [
|
const columns: ColumnDef<UserType>[] = [
|
||||||
{
|
{
|
||||||
id: 'select',
|
id: 'select',
|
||||||
meta: { cellClassName: cn('w-20') },
|
meta: { cellClassName: cn("w-20") },
|
||||||
header: ({ table }) => (
|
header: ({ table }) => (
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
@@ -107,7 +97,7 @@ export default function Components(): ReactElement {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
header: 'Action',
|
header: 'Action',
|
||||||
meta: { cellClassName: cn('w-72') },
|
meta: { cellClassName: cn("w-72") },
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -123,7 +113,7 @@ export default function Components(): ReactElement {
|
|||||||
</Button>
|
</Button>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
];
|
]
|
||||||
|
|
||||||
const table = useReactTable({
|
const table = useReactTable({
|
||||||
data: mockData,
|
data: mockData,
|
||||||
@@ -144,19 +134,14 @@ export default function Components(): ReactElement {
|
|||||||
return (
|
return (
|
||||||
<BackofficeWrapper title="Dimentorin.dev">
|
<BackofficeWrapper title="Dimentorin.dev">
|
||||||
<div className="mb-8 flex justify-between items-center">
|
<div className="mb-8 flex justify-between items-center">
|
||||||
<h1 className="text-p1 font-semibold text-neutral-700 mb-8">
|
<h1 className="text-p1 font-semibold text-neutral-700">User Management</h1>
|
||||||
User Management
|
|
||||||
</h1>
|
|
||||||
<div className="flex gap-2 bg-primary-100 p-1.5 rounded-md">
|
<div className="flex gap-2 bg-primary-100 p-1.5 rounded-md">
|
||||||
<For data={TABS}>
|
<For data={TABS}>
|
||||||
{(tab) => (
|
{(tab) => (
|
||||||
<Button
|
<Button
|
||||||
key={tab}
|
key={tab}
|
||||||
variant="text"
|
variant="text"
|
||||||
className={cn(
|
className={cn("px-3 py-2 capitalize", activeTab === tab && "bg-white")}
|
||||||
'px-3 py-2 capitalize',
|
|
||||||
activeTab === tab && 'bg-white'
|
|
||||||
)}
|
|
||||||
onClick={() => setActiveTab(tab)}
|
onClick={() => setActiveTab(tab)}
|
||||||
>
|
>
|
||||||
{tab}
|
{tab}
|
||||||
@@ -178,16 +163,12 @@ export default function Components(): ReactElement {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Select>
|
<Select>
|
||||||
<option selected disabled>
|
<option selected disabled>Rating</option>
|
||||||
Rating
|
|
||||||
</option>
|
|
||||||
<option value="4.5">4.5</option>
|
<option value="4.5">4.5</option>
|
||||||
<option value="5">5</option>
|
<option value="5">5</option>
|
||||||
</Select>
|
</Select>
|
||||||
<Select>
|
<Select>
|
||||||
<option selected disabled>
|
<option selected disabled>Status</option>
|
||||||
Status
|
|
||||||
</option>
|
|
||||||
<option value="active">Active</option>
|
<option value="active">Active</option>
|
||||||
<option value="inactive">Inactive</option>
|
<option value="inactive">Inactive</option>
|
||||||
</Select>
|
</Select>
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
import { FC, useState, useRef, useEffect } from 'react';
|
|
||||||
import { FilterOutlined } from '@ant-design/icons';
|
|
||||||
import INDONESIAN_CITIES from '../constants/cities';
|
|
||||||
|
|
||||||
interface CityFilterSelectProps {
|
|
||||||
value: string;
|
|
||||||
onChange: (value: string) => void;
|
|
||||||
className?: string;
|
|
||||||
placeholder?: string;
|
|
||||||
allOptionLabel?: string;
|
|
||||||
filterIcon?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const CityFilterSelect: FC<CityFilterSelectProps> = ({
|
|
||||||
value,
|
|
||||||
onChange,
|
|
||||||
className = '',
|
|
||||||
placeholder = 'Search cities...',
|
|
||||||
allOptionLabel = 'All Cities',
|
|
||||||
filterIcon = true,
|
|
||||||
}) => {
|
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
|
||||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
|
||||||
|
|
||||||
// Filter cities based on search query
|
|
||||||
const filteredCities = INDONESIAN_CITIES.filter((city) =>
|
|
||||||
city.toLowerCase().includes(searchQuery.toLowerCase())
|
|
||||||
);
|
|
||||||
|
|
||||||
// Close dropdown when clicking outside
|
|
||||||
useEffect(() => {
|
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
|
||||||
if (
|
|
||||||
dropdownRef.current &&
|
|
||||||
!dropdownRef.current.contains(event.target as Node)
|
|
||||||
) {
|
|
||||||
setIsOpen(false);
|
|
||||||
setSearchQuery('');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
document.addEventListener('mousedown', handleClickOutside);
|
|
||||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleSelectCity = (city: string) => {
|
|
||||||
onChange(city);
|
|
||||||
setSearchQuery('');
|
|
||||||
setIsOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInputClick = () => {
|
|
||||||
setIsOpen(true);
|
|
||||||
setSearchQuery('');
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleClearSelection = () => {
|
|
||||||
onChange('all');
|
|
||||||
setSearchQuery('');
|
|
||||||
setIsOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const displayValue = value === 'all' ? allOptionLabel : value;
|
|
||||||
const showClearButton = value !== 'all' && !isOpen;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={`relative ${className}`} ref={dropdownRef}>
|
|
||||||
<div className="relative">
|
|
||||||
{filterIcon && (
|
|
||||||
<FilterOutlined className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400 text-sm pointer-events-none z-10" />
|
|
||||||
)}
|
|
||||||
<input
|
|
||||||
ref={inputRef}
|
|
||||||
type="text"
|
|
||||||
value={isOpen ? searchQuery : displayValue}
|
|
||||||
onChange={(e) => {
|
|
||||||
setSearchQuery(e.target.value);
|
|
||||||
if (!isOpen) setIsOpen(true);
|
|
||||||
}}
|
|
||||||
onClick={handleInputClick}
|
|
||||||
onFocus={handleInputClick}
|
|
||||||
placeholder={isOpen ? placeholder : displayValue}
|
|
||||||
className={`border border-neutral-200 rounded-lg pr-10 py-2.5 text-sm w-full focus:border-primary-500 focus:outline-none appearance-none bg-white cursor-pointer ${
|
|
||||||
filterIcon ? ' pl-10' : 'pl-3'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
{showClearButton && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
handleClearSelection();
|
|
||||||
}}
|
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 hover:text-neutral-600 text-xs cursor-pointer z-20"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isOpen && (
|
|
||||||
<div className="absolute z-50 w-full mt-1 bg-white border border-neutral-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
|
|
||||||
{/* All Cities Option */}
|
|
||||||
<div
|
|
||||||
onClick={() => handleSelectCity('all')}
|
|
||||||
className={`px-3 py-2 cursor-pointer hover:bg-neutral-50 border-b border-neutral-100 ${
|
|
||||||
value === 'all'
|
|
||||||
? 'bg-primary-50 text-primary-700 font-medium'
|
|
||||||
: 'text-neutral-900'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{allOptionLabel}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Filtered Cities */}
|
|
||||||
{filteredCities.length > 0 ? (
|
|
||||||
<div className="py-1">
|
|
||||||
{filteredCities.slice(0, 100).map((city) => (
|
|
||||||
<div
|
|
||||||
key={city}
|
|
||||||
onClick={() => handleSelectCity(city)}
|
|
||||||
className={`px-3 py-2 cursor-pointer hover:bg-neutral-50 text-sm ${
|
|
||||||
value === city
|
|
||||||
? 'bg-primary-50 text-primary-700 font-medium'
|
|
||||||
: 'text-neutral-700'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{city}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{filteredCities.length > 100 && (
|
|
||||||
<div className="px-3 py-2 text-xs text-neutral-500 border-t border-neutral-100">
|
|
||||||
Showing first 100 results. Continue typing to refine...
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : searchQuery ? (
|
|
||||||
<div className="px-3 py-2 text-neutral-500 text-sm">
|
|
||||||
No cities found matching "{searchQuery}"
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1,518 +0,0 @@
|
|||||||
const INDONESIAN_CITIES: string[] = [
|
|
||||||
'Aceh Selatan',
|
|
||||||
'Aceh Tenggara',
|
|
||||||
'Aceh Timur',
|
|
||||||
'Aceh Tengah',
|
|
||||||
'Aceh Barat',
|
|
||||||
'Aceh Besar',
|
|
||||||
'Pidie',
|
|
||||||
'Aceh Utara',
|
|
||||||
'Simeulue',
|
|
||||||
'Aceh Singkil',
|
|
||||||
'Bireuen',
|
|
||||||
'Aceh Barat Daya',
|
|
||||||
'Gayo Lues',
|
|
||||||
'Aceh Jaya',
|
|
||||||
'Nagan Raya',
|
|
||||||
'Aceh Tamiang',
|
|
||||||
'Bener Meriah',
|
|
||||||
'Pidie Jaya',
|
|
||||||
'Kota Banda Aceh',
|
|
||||||
'Kota Sabang',
|
|
||||||
'Kota Lhokseumawe',
|
|
||||||
'Kota Langsa',
|
|
||||||
'Kota Subulussalam',
|
|
||||||
'Tapanuli Tengah',
|
|
||||||
'Tapanuli Utara',
|
|
||||||
'Tapanuli Selatan',
|
|
||||||
'Nias',
|
|
||||||
'Langkat',
|
|
||||||
'Karo',
|
|
||||||
'Deli Serdang',
|
|
||||||
'Simalungun',
|
|
||||||
'Asahan',
|
|
||||||
'Labuhanbatu',
|
|
||||||
'Dairi',
|
|
||||||
'Toba',
|
|
||||||
'Mandailing Natal',
|
|
||||||
'Nias Selatan',
|
|
||||||
'Pakpak Bharat',
|
|
||||||
'Humbang Hasundutan',
|
|
||||||
'Samosir',
|
|
||||||
'Serdang Bedagai',
|
|
||||||
'Batu Bara',
|
|
||||||
'Padang Lawas Utara',
|
|
||||||
'Padang Lawas',
|
|
||||||
'Labuhanbatu Selatan',
|
|
||||||
'Labuhanbatu Utara',
|
|
||||||
'Nias Utara',
|
|
||||||
'Nias Barat',
|
|
||||||
'Kota Medan',
|
|
||||||
'Kota Pematangsiantar',
|
|
||||||
'Kota Sibolga',
|
|
||||||
'Kota Tanjung Balai',
|
|
||||||
'Kota Binjai',
|
|
||||||
'Kota Tebing Tinggi',
|
|
||||||
'Kota Padangsidimpuan',
|
|
||||||
'Kota Gunungsitoli',
|
|
||||||
'Pesisir Selatan',
|
|
||||||
'Solok',
|
|
||||||
'Sijunjung',
|
|
||||||
'Tanah Datar',
|
|
||||||
'Padang Pariaman',
|
|
||||||
'Agam',
|
|
||||||
'Lima Puluh Kota',
|
|
||||||
'Pasaman',
|
|
||||||
'Kepulauan Mentawai',
|
|
||||||
'Dharmasraya',
|
|
||||||
'Solok Selatan',
|
|
||||||
'Pasaman Barat',
|
|
||||||
'Kota Padang',
|
|
||||||
'Kota Solok',
|
|
||||||
'Kota Sawahlunto',
|
|
||||||
'Kota Padang Panjang',
|
|
||||||
'Kota Bukittinggi',
|
|
||||||
'Kota Payakumbuh',
|
|
||||||
'Kota Pariaman',
|
|
||||||
'Kampar',
|
|
||||||
'Indragiri Hulu',
|
|
||||||
'Bengkalis',
|
|
||||||
'Indragiri Hilir',
|
|
||||||
'Pelalawan',
|
|
||||||
'Rokan Hulu',
|
|
||||||
'Rokan Hilir',
|
|
||||||
'Siak',
|
|
||||||
'Kuantan Singingi',
|
|
||||||
'Kepulauan Meranti',
|
|
||||||
'Kota Pekanbaru',
|
|
||||||
'Kota Dumai',
|
|
||||||
'Kerinci',
|
|
||||||
'Merangin',
|
|
||||||
'Sarolangun',
|
|
||||||
'Batanghari',
|
|
||||||
'Muaro Jambi',
|
|
||||||
'Tanjung Jabung Barat',
|
|
||||||
'Tanjung Jabung Timur',
|
|
||||||
'Bungo',
|
|
||||||
'Tebo',
|
|
||||||
'Kota Jambi',
|
|
||||||
'Kota Sungai Penuh',
|
|
||||||
'Ogan Komering Ulu',
|
|
||||||
'Ogan Komering Ilir',
|
|
||||||
'Muara Enim',
|
|
||||||
'Lahat',
|
|
||||||
'Musi Rawas',
|
|
||||||
'Musi Banyuasin',
|
|
||||||
'Banyuasin',
|
|
||||||
'Ogan Komering Ulu Timur',
|
|
||||||
'Ogan Komering Ulu Selatan',
|
|
||||||
'Ogan Ilir',
|
|
||||||
'Empat Lawang',
|
|
||||||
'Penukal Abab Lematang Ilir',
|
|
||||||
'Musi Rawas Utara',
|
|
||||||
'Kota Palembang',
|
|
||||||
'Kota Pagar Alam',
|
|
||||||
'Kota Lubuk Linggau',
|
|
||||||
'Kota Prabumulih',
|
|
||||||
'Bengkulu Selatan',
|
|
||||||
'Rejang Lebong',
|
|
||||||
'Bengkulu Utara',
|
|
||||||
'Kaur',
|
|
||||||
'Seluma',
|
|
||||||
'Muko Muko',
|
|
||||||
'Lebong',
|
|
||||||
'Kepahiang',
|
|
||||||
'Bengkulu Tengah',
|
|
||||||
'Kota Bengkulu',
|
|
||||||
'Lampung Selatan',
|
|
||||||
'Lampung Tengah',
|
|
||||||
'Lampung Utara',
|
|
||||||
'Lampung Barat',
|
|
||||||
'Tulang Bawang',
|
|
||||||
'Tanggamus',
|
|
||||||
'Lampung Timur',
|
|
||||||
'Way Kanan',
|
|
||||||
'Pesawaran',
|
|
||||||
'Pringsewu',
|
|
||||||
'Mesuji',
|
|
||||||
'Tulang Bawang Barat',
|
|
||||||
'Pesisir Barat',
|
|
||||||
'Kota Bandar Lampung',
|
|
||||||
'Kota Metro',
|
|
||||||
'Bangka',
|
|
||||||
'Belitung',
|
|
||||||
'Bangka Selatan',
|
|
||||||
'Bangka Tengah',
|
|
||||||
'Bangka Barat',
|
|
||||||
'Belitung Timur',
|
|
||||||
'Kota Pangkal Pinang',
|
|
||||||
'Bintan',
|
|
||||||
'Karimun',
|
|
||||||
'Natuna',
|
|
||||||
'Lingga',
|
|
||||||
'Kepulauan Anambas',
|
|
||||||
'Kota Batam',
|
|
||||||
'Kota Tanjung Pinang',
|
|
||||||
'Kepulauan Seribu',
|
|
||||||
'Kota Jakarta Pusat',
|
|
||||||
'Kota Jakarta Utara',
|
|
||||||
'Kota Jakarta Barat',
|
|
||||||
'Kota Jakarta Selatan',
|
|
||||||
'Kota Jakarta Timur',
|
|
||||||
'Bogor',
|
|
||||||
'Sukabumi',
|
|
||||||
'Cianjur',
|
|
||||||
'Bandung',
|
|
||||||
'Garut',
|
|
||||||
'Tasikmalaya',
|
|
||||||
'Ciamis',
|
|
||||||
'Kuningan',
|
|
||||||
'Cirebon',
|
|
||||||
'Majalengka',
|
|
||||||
'Sumedang',
|
|
||||||
'Indramayu',
|
|
||||||
'Subang',
|
|
||||||
'Purwakarta',
|
|
||||||
'Karawang',
|
|
||||||
'Bekasi',
|
|
||||||
'Bandung Barat',
|
|
||||||
'Pangandaran',
|
|
||||||
'Kota Bogor',
|
|
||||||
'Kota Sukabumi',
|
|
||||||
'Kota Bandung',
|
|
||||||
'Kota Cirebon',
|
|
||||||
'Kota Bekasi',
|
|
||||||
'Kota Depok',
|
|
||||||
'Kota Cimahi',
|
|
||||||
'Kota Tasikmalaya',
|
|
||||||
'Kota Banjar',
|
|
||||||
'Cilacap',
|
|
||||||
'Banyumas',
|
|
||||||
'Purbalingga',
|
|
||||||
'Banjarnegara',
|
|
||||||
'Kebumen',
|
|
||||||
'Purworejo',
|
|
||||||
'Wonosobo',
|
|
||||||
'Magelang',
|
|
||||||
'Boyolali',
|
|
||||||
'Klaten',
|
|
||||||
'Sukoharjo',
|
|
||||||
'Wonogiri',
|
|
||||||
'Karanganyar',
|
|
||||||
'Sragen',
|
|
||||||
'Grobogan',
|
|
||||||
'Blora',
|
|
||||||
'Rembang',
|
|
||||||
'Pati',
|
|
||||||
'Kudus',
|
|
||||||
'Jepara',
|
|
||||||
'Demak',
|
|
||||||
'Semarang',
|
|
||||||
'Temanggung',
|
|
||||||
'Kendal',
|
|
||||||
'Batang',
|
|
||||||
'Pekalongan',
|
|
||||||
'Pemalang',
|
|
||||||
'Tegal',
|
|
||||||
'Brebes',
|
|
||||||
'Kota Magelang',
|
|
||||||
'Kota Surakarta',
|
|
||||||
'Kota Salatiga',
|
|
||||||
'Kota Semarang',
|
|
||||||
'Kota Pekalongan',
|
|
||||||
'Kota Tegal',
|
|
||||||
'Kulon Progo',
|
|
||||||
'Bantul',
|
|
||||||
'Gunungkidul',
|
|
||||||
'Sleman',
|
|
||||||
'Kota Yogyakarta',
|
|
||||||
'Pacitan',
|
|
||||||
'Ponorogo',
|
|
||||||
'Trenggalek',
|
|
||||||
'Tulungagung',
|
|
||||||
'Blitar',
|
|
||||||
'Kediri',
|
|
||||||
'Malang',
|
|
||||||
'Lumajang',
|
|
||||||
'Jember',
|
|
||||||
'Banyuwangi',
|
|
||||||
'Bondowoso',
|
|
||||||
'Situbondo',
|
|
||||||
'Probolinggo',
|
|
||||||
'Pasuruan',
|
|
||||||
'Sidoarjo',
|
|
||||||
'Mojokerto',
|
|
||||||
'Jombang',
|
|
||||||
'Nganjuk',
|
|
||||||
'Madiun',
|
|
||||||
'Magetan',
|
|
||||||
'Ngawi',
|
|
||||||
'Bojonegoro',
|
|
||||||
'Tuban',
|
|
||||||
'Lamongan',
|
|
||||||
'Gresik',
|
|
||||||
'Bangkalan',
|
|
||||||
'Sampang',
|
|
||||||
'Pamekasan',
|
|
||||||
'Sumenep',
|
|
||||||
'Kota Kediri',
|
|
||||||
'Kota Blitar',
|
|
||||||
'Kota Malang',
|
|
||||||
'Kota Probolinggo',
|
|
||||||
'Kota Pasuruan',
|
|
||||||
'Kota Mojokerto',
|
|
||||||
'Kota Madiun',
|
|
||||||
'Kota Surabaya',
|
|
||||||
'Kota Batu',
|
|
||||||
'Pandeglang',
|
|
||||||
'Lebak',
|
|
||||||
'Tangerang',
|
|
||||||
'Serang',
|
|
||||||
'Kota Tangerang',
|
|
||||||
'Kota Cilegon',
|
|
||||||
'Kota Serang',
|
|
||||||
'Kota Tangerang Selatan',
|
|
||||||
'Jembrana',
|
|
||||||
'Tabanan',
|
|
||||||
'Badung',
|
|
||||||
'Gianyar',
|
|
||||||
'Klungkung',
|
|
||||||
'Bangli',
|
|
||||||
'Karangasem',
|
|
||||||
'Buleleng',
|
|
||||||
'Kota Denpasar',
|
|
||||||
'Lombok Barat',
|
|
||||||
'Lombok Tengah',
|
|
||||||
'Lombok Timur',
|
|
||||||
'Sumbawa',
|
|
||||||
'Dompu',
|
|
||||||
'Bima',
|
|
||||||
'Sumbawa Barat',
|
|
||||||
'Lombok Utara',
|
|
||||||
'Kota Mataram',
|
|
||||||
'Kota Bima',
|
|
||||||
'Kupang',
|
|
||||||
'Timor Tengah Selatan',
|
|
||||||
'Timor Tengah Utara',
|
|
||||||
'Belu',
|
|
||||||
'Alor',
|
|
||||||
'Flores Timur',
|
|
||||||
'Sikka',
|
|
||||||
'Ende',
|
|
||||||
'Ngada',
|
|
||||||
'Manggarai',
|
|
||||||
'Sumba Timur',
|
|
||||||
'Sumba Barat',
|
|
||||||
'Lembata',
|
|
||||||
'Rote Ndao',
|
|
||||||
'Manggarai Barat',
|
|
||||||
'Nagekeo',
|
|
||||||
'Sumba Tengah',
|
|
||||||
'Sumba Barat Daya',
|
|
||||||
'Manggarai Timur',
|
|
||||||
'Sabu Raijua',
|
|
||||||
'Malaka',
|
|
||||||
'Kota Kupang',
|
|
||||||
'Sambas',
|
|
||||||
'Mempawah',
|
|
||||||
'Sanggau',
|
|
||||||
'Ketapang',
|
|
||||||
'Sintang',
|
|
||||||
'Kapuas Hulu',
|
|
||||||
'Bengkayang',
|
|
||||||
'Landak',
|
|
||||||
'Sekadau',
|
|
||||||
'Melawi',
|
|
||||||
'Kayong Utara',
|
|
||||||
'Kubu Raya',
|
|
||||||
'Kota Pontianak',
|
|
||||||
'Kota Singkawang',
|
|
||||||
'Kotawaringin Barat',
|
|
||||||
'Kotawaringin Timur',
|
|
||||||
'Kapuas',
|
|
||||||
'Barito Selatan',
|
|
||||||
'Barito Utara',
|
|
||||||
'Katingan',
|
|
||||||
'Seruyan',
|
|
||||||
'Sukamara',
|
|
||||||
'Lamandau',
|
|
||||||
'Gunung Mas',
|
|
||||||
'Pulang Pisau',
|
|
||||||
'Murung Raya',
|
|
||||||
'Barito Timur',
|
|
||||||
'Kota Palangkaraya',
|
|
||||||
'Tanah Laut',
|
|
||||||
'Kotabaru',
|
|
||||||
'Banjar',
|
|
||||||
'Barito Kuala',
|
|
||||||
'Tapin',
|
|
||||||
'Hulu Sungai Selatan',
|
|
||||||
'Hulu Sungai Tengah',
|
|
||||||
'Hulu Sungai Utara',
|
|
||||||
'Tabalong',
|
|
||||||
'Tanah Bumbu',
|
|
||||||
'Balangan',
|
|
||||||
'Kota Banjarmasin',
|
|
||||||
'Kota Banjarbaru',
|
|
||||||
'Paser',
|
|
||||||
'Kutai Kartanegara',
|
|
||||||
'Berau',
|
|
||||||
'Kutai Barat',
|
|
||||||
'Kutai Timur',
|
|
||||||
'Penajam Paser Utara',
|
|
||||||
'Mahakam Ulu',
|
|
||||||
'Kota Balikpapan',
|
|
||||||
'Kota Samarinda',
|
|
||||||
'Kota Bontang',
|
|
||||||
'Bulungan',
|
|
||||||
'Malinau',
|
|
||||||
'Nunukan',
|
|
||||||
'Tana Tidung',
|
|
||||||
'Kota Tarakan',
|
|
||||||
'Bolaang Mongondow',
|
|
||||||
'Minahasa',
|
|
||||||
'Kepulauan Sangihe',
|
|
||||||
'Kepulauan Talaud',
|
|
||||||
'Minahasa Selatan',
|
|
||||||
'Minahasa Utara',
|
|
||||||
'Minahasa Tenggara',
|
|
||||||
'Bolaang Mongondow Utara',
|
|
||||||
'Kepulauan Siau Tagulandang Biaro (Sitaro)',
|
|
||||||
'Bolaang Mongondow Timur',
|
|
||||||
'Bolaang Mongondow Selatan',
|
|
||||||
'Kota Manado',
|
|
||||||
'Kota Bitung',
|
|
||||||
'Kota Tomohon',
|
|
||||||
'Kota Kotamobagu',
|
|
||||||
'Banggai',
|
|
||||||
'Poso',
|
|
||||||
'Donggala',
|
|
||||||
'Toli Toli',
|
|
||||||
'Buol',
|
|
||||||
'Morowali',
|
|
||||||
'Banggai Kepulauan',
|
|
||||||
'Parigi Moutong',
|
|
||||||
'Tojo Una Una',
|
|
||||||
'Sigi',
|
|
||||||
'Banggai Laut',
|
|
||||||
'Morowali Utara',
|
|
||||||
'Kota Palu',
|
|
||||||
'Kepulauan Selayar',
|
|
||||||
'Bulukumba',
|
|
||||||
'Bantaeng',
|
|
||||||
'Jeneponto',
|
|
||||||
'Takalar',
|
|
||||||
'Gowa',
|
|
||||||
'Sinjai',
|
|
||||||
'Bone',
|
|
||||||
'Maros',
|
|
||||||
'Pangkajene Kepulauan',
|
|
||||||
'Barru',
|
|
||||||
'Soppeng',
|
|
||||||
'Wajo',
|
|
||||||
'Sidenreng Rappang',
|
|
||||||
'Pinrang',
|
|
||||||
'Enrekang',
|
|
||||||
'Luwu',
|
|
||||||
'Tana Toraja',
|
|
||||||
'Luwu Utara',
|
|
||||||
'Luwu Timur',
|
|
||||||
'Toraja Utara',
|
|
||||||
'Kota Makassar',
|
|
||||||
'Kota Pare Pare',
|
|
||||||
'Kota Palopo',
|
|
||||||
'Kolaka',
|
|
||||||
'Konawe',
|
|
||||||
'Muna',
|
|
||||||
'Buton',
|
|
||||||
'Konawe Selatan',
|
|
||||||
'Bombana',
|
|
||||||
'Wakatobi',
|
|
||||||
'Kolaka Utara',
|
|
||||||
'Konawe Utara',
|
|
||||||
'Buton Utara',
|
|
||||||
'Kolaka Timur',
|
|
||||||
'Konawe Kepulauan',
|
|
||||||
'Muna Barat',
|
|
||||||
'Buton Tengah',
|
|
||||||
'Buton Selatan',
|
|
||||||
'Kota Kendari',
|
|
||||||
'Kota Bau Bau',
|
|
||||||
'Gorontalo',
|
|
||||||
'Boalemo',
|
|
||||||
'Bone Bolango',
|
|
||||||
'Pahuwato',
|
|
||||||
'Gorontalo Utara',
|
|
||||||
'Kota Gorontalo',
|
|
||||||
'Pasangkayu (Mamuju Utara)',
|
|
||||||
'Mamuju',
|
|
||||||
'Mamasa',
|
|
||||||
'Polewali Mandar',
|
|
||||||
'Majene',
|
|
||||||
'Mamuju Tengah',
|
|
||||||
'Maluku Tengah',
|
|
||||||
'Maluku Tenggara',
|
|
||||||
'Kepulauan Tanimbar (Maluku Tenggara Barat)',
|
|
||||||
'Buru',
|
|
||||||
'Seram Bagian Timur',
|
|
||||||
'Seram Bagian Barat',
|
|
||||||
'Kepulauan Aru',
|
|
||||||
'Maluku Barat Daya',
|
|
||||||
'Buru Selatan',
|
|
||||||
'Kota Ambon',
|
|
||||||
'Kota Tual',
|
|
||||||
'Halmahera Barat',
|
|
||||||
'Halmahera Tengah',
|
|
||||||
'Halmahera Utara',
|
|
||||||
'Halmahera Selatan',
|
|
||||||
'Kepulauan Sula',
|
|
||||||
'Halmahera Timur',
|
|
||||||
'Pulau Morotai',
|
|
||||||
'Pulau Taliabu',
|
|
||||||
'Kota Ternate',
|
|
||||||
'Kota Tidore Kepulauan',
|
|
||||||
'Jayapura',
|
|
||||||
'Kepulauan Yapen',
|
|
||||||
'Biak Numfor',
|
|
||||||
'Sarmi',
|
|
||||||
'Keerom',
|
|
||||||
'Waropen',
|
|
||||||
'Supiori',
|
|
||||||
'Mamberamo Raya',
|
|
||||||
'Kota Jayapura',
|
|
||||||
'Manokwari',
|
|
||||||
'Fak Fak',
|
|
||||||
'Teluk Bintuni',
|
|
||||||
'Teluk Wondama',
|
|
||||||
'Kaimana',
|
|
||||||
'Manokwari Selatan',
|
|
||||||
'Pegunungan Arfak',
|
|
||||||
'Merauke',
|
|
||||||
'Boven Digoel',
|
|
||||||
'Mappi',
|
|
||||||
'Asmat',
|
|
||||||
'Nabire',
|
|
||||||
'Puncak Jaya',
|
|
||||||
'Paniai',
|
|
||||||
'Mimika',
|
|
||||||
'Puncak',
|
|
||||||
'Dogiyai',
|
|
||||||
'Intan Jaya',
|
|
||||||
'Deiyai',
|
|
||||||
'Jayawijaya',
|
|
||||||
'Pegunungan Bintang',
|
|
||||||
'Yahukimo',
|
|
||||||
'Tolikara',
|
|
||||||
'Mamberamo Tengah',
|
|
||||||
'Yalimo',
|
|
||||||
'Lanny Jaya',
|
|
||||||
'Nduga',
|
|
||||||
'Sorong',
|
|
||||||
'Sorong Selatan',
|
|
||||||
'Raja Ampat',
|
|
||||||
'Tambrauw',
|
|
||||||
'Maybrat',
|
|
||||||
'Kota Sorong',
|
|
||||||
];
|
|
||||||
|
|
||||||
export default INDONESIAN_CITIES;
|
|
||||||
@@ -130,7 +130,7 @@
|
|||||||
html {
|
html {
|
||||||
font-family: 'Bai Jamjuree', sans-serif;
|
font-family: 'Bai Jamjuree', sans-serif;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
font-size: 14px;
|
font-size: 12px;
|
||||||
line-height: 1.2;
|
line-height: 1.2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ export const middleware = async ({ request }: LoaderFunctionArgs) => {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// if (!session) return redirect('/auth/login');
|
if (!session) return redirect('/auth/login');
|
||||||
|
|
||||||
const matchedRoute = mappingRoutePermissions.find(
|
const matchedRoute = mappingRoutePermissions.find(
|
||||||
(route) => route.path === pathname
|
(route) => route.path === pathname
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { FC, ReactElement, useEffect, useState, useRef } from 'react';
|
import { FC, ReactElement, useEffect, useState, useRef } from 'react';
|
||||||
import { useNavigate } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { useGitHubCallback } from '@imphnen-frontend-service/service';
|
import { useAuthStore, supabase } from '@imphnen-frontend-service/service';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
const CallbackPage: FC = (): ReactElement => {
|
const CallbackPage: FC = (): ReactElement => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { mutateAsync: exchangeGitHubCode } = useGitHubCallback();
|
const { setSession } = useAuthStore();
|
||||||
const [isProcessing, setIsProcessing] = useState(true);
|
const [isProcessing, setIsProcessing] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const hasRunRef = useRef(false);
|
const hasRunRef = useRef(false);
|
||||||
@@ -13,68 +13,134 @@ const CallbackPage: FC = (): ReactElement => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleCallback = async () => {
|
const handleCallback = async () => {
|
||||||
if (hasRunRef.current) {
|
if (hasRunRef.current) {
|
||||||
|
// console.log('[Callback] Already processed, skipping...');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
hasRunRef.current = true;
|
hasRunRef.current = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Check URL hash for Supabase email confirmation callback
|
// console.log('[Callback] Processing OAuth callback...');
|
||||||
const hashParams = new URLSearchParams(globalThis.location.hash.substring(1));
|
// console.log('[Callback] Current URL:', globalThis.location.href);
|
||||||
const urlParams = new URLSearchParams(globalThis.location.search);
|
|
||||||
|
|
||||||
const type = hashParams.get('type') || urlParams.get('type');
|
// Supabase client is configured with detectSessionInUrl: true
|
||||||
const accessToken = hashParams.get('access_token') || urlParams.get('access_token');
|
// 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
|
||||||
|
|
||||||
// Debug: log what we received
|
// console.log('[Callback] Waiting for Supabase to process OAuth callback...');
|
||||||
console.log('[Callback] Params:', { type, accessToken: !!accessToken, hash: globalThis.location.hash, search: globalThis.location.search });
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
|
||||||
// Handle Supabase email callbacks (has access_token in hash or query)
|
// Get the session that Supabase automatically created from the URL hash
|
||||||
// This includes: signup confirmation, email confirmation, password recovery
|
const {
|
||||||
if (accessToken) {
|
data: { session: sessionData },
|
||||||
setIsProcessing(false);
|
error: sessionError,
|
||||||
|
} = await supabase.auth.getSession();
|
||||||
|
|
||||||
// Password recovery - type is 'recovery' or we have access_token from reset email
|
if (sessionError) {
|
||||||
if (type === 'recovery' || type === 'magiclink') {
|
// console.error('[Callback] Session error:', sessionError);
|
||||||
toast.success('Email verified! Please set your new password.');
|
throw new Error(sessionError.message || 'Failed to get session');
|
||||||
navigate('/auth/reset-password?access_token=' + accessToken);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Signup/Email confirmation
|
if (!sessionData || !sessionData.user) {
|
||||||
if (type === 'signup' || type === 'email_confirmation') {
|
throw new Error(
|
||||||
toast.success('Email verified successfully! Please log in to continue.');
|
'No session found after OAuth callback. Please try logging in again.'
|
||||||
navigate('/auth/login');
|
);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we have access_token but unknown type, assume it's password recovery
|
// console.log('[Callback] Supabase session established:', {
|
||||||
// (Supabase sometimes sends without explicit type)
|
// userId: sessionData.user.id,
|
||||||
toast.success('Email verified! Please set your new password.');
|
// email: sessionData.user.email,
|
||||||
navigate('/auth/reset-password?access_token=' + accessToken);
|
// });
|
||||||
return;
|
|
||||||
|
// 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');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the code from URL query params (GitHub OAuth)
|
// Store user-friendly data in Zustand for UI purposes
|
||||||
const code = urlParams.get('code');
|
// 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,
|
||||||
|
};
|
||||||
|
|
||||||
if (!code) {
|
setSession({
|
||||||
throw new Error('No authorization code received');
|
token: {
|
||||||
}
|
access_token: sessionData.access_token,
|
||||||
|
refresh_token: sessionData.refresh_token || '',
|
||||||
// Exchange the code for tokens using backend API (GitHub OAuth)
|
},
|
||||||
const result = await exchangeGitHubCode({ code });
|
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!');
|
toast.success('Login successful!');
|
||||||
setIsProcessing(false);
|
setIsProcessing(false);
|
||||||
|
|
||||||
// Check if user has completed onboarding (has location)
|
// Check if user has completed onboarding (has location)
|
||||||
if (result.user.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');
|
globalThis.location.replace('/dashboard');
|
||||||
} else {
|
} else {
|
||||||
|
// console.log('[Callback] User needs onboarding, redirecting...');
|
||||||
globalThis.location.replace('/onboarding/user');
|
globalThis.location.replace('/onboarding/user');
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[Callback] Error:', err);
|
// console.error('[Callback] Error:', err);
|
||||||
setError((err as Error).message);
|
setError((err as Error).message);
|
||||||
setIsProcessing(false);
|
setIsProcessing(false);
|
||||||
toast.error('An error occurred during login');
|
toast.error('An error occurred during login');
|
||||||
@@ -87,68 +153,21 @@ const CallbackPage: FC = (): ReactElement => {
|
|||||||
|
|
||||||
handleCallback();
|
handleCallback();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, []);
|
}, []); // Run only once on mount
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
// Check if error is related to private email
|
|
||||||
const isPrivateEmailError =
|
|
||||||
error.toLowerCase().includes('failed to create user') ||
|
|
||||||
error.toLowerCase().includes('email') ||
|
|
||||||
error.toLowerCase().includes('user record');
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 px-4">
|
<div className="flex justify-center items-center min-h-screen bg-gray-50 px-4">
|
||||||
<div className="bg-white dark:bg-gray-900 w-full max-w-2xl p-8 rounded-2xl shadow-lg border border-red-200 dark:border-red-800">
|
<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-center mb-6">
|
||||||
<div className="text-red-500 text-5xl mb-4">⚠️</div>
|
<div className="text-red-500 text-5xl mb-4">⚠️</div>
|
||||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
|
<h2 className="text-2xl font-bold text-gray-900 mb-2">
|
||||||
GitHub Login Failed
|
GitHub Login Failed
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-red-600 dark:text-red-400 mb-4 whitespace-pre-line">{error}</p>
|
<p className="text-red-600 mb-4 whitespace-pre-line">{error}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isPrivateEmailError && (
|
<p className="text-gray-600 text-sm mt-6 text-center">
|
||||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-6">
|
|
||||||
<h3 className="font-semibold text-amber-800 dark:text-amber-300 mb-2">
|
|
||||||
Is your GitHub email set to private?
|
|
||||||
</h3>
|
|
||||||
<p className="text-amber-700 dark:text-amber-400 text-sm mb-3">
|
|
||||||
GitHub login requires a public email address. Please follow these steps:
|
|
||||||
</p>
|
|
||||||
<ol className="text-amber-700 dark:text-amber-400 text-sm list-decimal list-inside space-y-1 mb-3">
|
|
||||||
<li>
|
|
||||||
Go to{' '}
|
|
||||||
<a
|
|
||||||
href="https://github.com/settings/emails"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="underline hover:text-amber-900 dark:hover:text-amber-200"
|
|
||||||
>
|
|
||||||
GitHub Email Settings
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li>Uncheck "Keep my email addresses private"</li>
|
|
||||||
<li>
|
|
||||||
Or go to{' '}
|
|
||||||
<a
|
|
||||||
href="https://github.com/settings/profile"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="underline hover:text-amber-900 dark:hover:text-amber-200"
|
|
||||||
>
|
|
||||||
Profile Settings
|
|
||||||
</a>{' '}
|
|
||||||
and set a public email
|
|
||||||
</li>
|
|
||||||
<li>Try signing in with GitHub again</li>
|
|
||||||
</ol>
|
|
||||||
<p className="text-amber-600 dark:text-amber-500 text-xs">
|
|
||||||
Alternatively, you can sign up using email and password instead.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<p className="text-gray-600 dark:text-gray-400 text-sm mt-6 text-center">
|
|
||||||
Redirecting to login page in 3 seconds...
|
Redirecting to login page in 3 seconds...
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useForgotPassword } from '@imphnen-frontend-service/service';
|
import { supabase } from '@imphnen-frontend-service/service';
|
||||||
import { Link, useNavigate } from 'react-router';
|
import { Link, useNavigate } from 'react-router';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
@@ -7,9 +7,9 @@ import ThemeToggle from '../../../components/theme-toggle';
|
|||||||
|
|
||||||
export default function ForgotPasswordPage() {
|
export default function ForgotPasswordPage() {
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [emailSent, setEmailSent] = useState(false);
|
const [emailSent, setEmailSent] = useState(false);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const forgotPasswordMutation = useForgotPassword();
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -20,33 +20,44 @@ export default function ForgotPasswordPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await forgotPasswordMutation.mutateAsync({ email });
|
setIsLoading(true);
|
||||||
|
|
||||||
|
const { error } = await supabase.auth.resetPasswordForEmail(email, {
|
||||||
|
redirectTo: `${window.location.origin}/auth/reset-password`,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
setEmailSent(true);
|
setEmailSent(true);
|
||||||
toast.success('Password reset email sent! Check your inbox.');
|
toast.success('Password reset email sent! Check your inbox.');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// console.error('Failed to send reset email:', err);
|
||||||
toast.error((err as Error).message || 'Failed to send reset email');
|
toast.error((err as Error).message || 'Failed to send reset email');
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (emailSent) {
|
if (emailSent) {
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
<div className="flex justify-center items-center min-h-screen bg-gray-50 p-4">
|
||||||
<div className="bg-white dark:bg-gray-900 w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 text-center">
|
<div className="bg-white w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 text-center">
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<div className="mx-auto w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mb-4">
|
<div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
|
||||||
<span className="text-3xl">✓</span>
|
<span className="text-3xl">✓</span>
|
||||||
</div>
|
</div>
|
||||||
<h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
|
<h2 className="text-3xl font-bold text-gray-900 mb-2">
|
||||||
Check Your Email
|
Check Your Email
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
<p className="text-gray-600">
|
||||||
We've sent a password reset link to <strong>{email}</strong>
|
We've sent a password reset link to <strong>{email}</strong>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
<p className="text-sm text-gray-600">
|
||||||
Click the link in the email to reset your password. The link will
|
Click the link in the email to reset your password. The link will
|
||||||
expire in 1 hour.
|
expire in 1 hour.
|
||||||
</p>
|
</p>
|
||||||
@@ -59,7 +70,7 @@ export default function ForgotPasswordPage() {
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => setEmailSent(false)}
|
onClick={() => setEmailSent(false)}
|
||||||
className="w-full py-3 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
|
className="w-full py-3 text-gray-600 hover:text-gray-900 transition-colors"
|
||||||
>
|
>
|
||||||
Send another email
|
Send another email
|
||||||
</button>
|
</button>
|
||||||
@@ -105,18 +116,18 @@ export default function ForgotPasswordPage() {
|
|||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
placeholder="your@email.com"
|
placeholder="your@email.com"
|
||||||
disabled={forgotPasswordMutation.isPending}
|
disabled={isLoading}
|
||||||
className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
className="bg-white dark:bg-gray-800 w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={forgotPasswordMutation.isPending}
|
disabled={isLoading}
|
||||||
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"
|
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"
|
||||||
>
|
>
|
||||||
{forgotPasswordMutation.isPending ? 'Sending...' : 'Send Reset Link'}
|
{isLoading ? 'Sending...' : 'Send Reset Link'}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
useGitHubAuth,
|
useGitHubAuth,
|
||||||
useLogin,
|
useEmailAuth,
|
||||||
|
supabase,
|
||||||
|
useAuthStore,
|
||||||
} from '@imphnen-frontend-service/service';
|
} from '@imphnen-frontend-service/service';
|
||||||
import { GithubOutlined } from '@ant-design/icons';
|
import { GithubOutlined } from '@ant-design/icons';
|
||||||
import { useNavigate, Link } from 'react-router';
|
import { useNavigate, Link } from 'react-router';
|
||||||
@@ -10,34 +12,17 @@ import { Icon } from '@iconify/react';
|
|||||||
import { ThemeToggle } from '../../../components/theme-toggle';
|
import { ThemeToggle } from '../../../components/theme-toggle';
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
|
// console.log('[LoginPage] Rendering...');
|
||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { setSession } = useAuthStore();
|
||||||
const { signInWithGitHub } = useGitHubAuth();
|
const { signInWithGitHub } = useGitHubAuth();
|
||||||
const loginMutation = useLogin();
|
const { signInWithEmail } = useEmailAuth();
|
||||||
const [isGithubLoading, setIsGithubLoading] = useState(false);
|
const [isGithubLoading, setIsGithubLoading] = useState(false);
|
||||||
|
const [isEmailLoading, setIsEmailLoading] = useState(false);
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
|
||||||
|
|
||||||
// Check for password reset tokens in URL and redirect to reset-password page
|
|
||||||
useEffect(() => {
|
|
||||||
const hashParams = new URLSearchParams(globalThis.location.hash.substring(1));
|
|
||||||
const urlParams = new URLSearchParams(globalThis.location.search);
|
|
||||||
|
|
||||||
const accessToken = hashParams.get('access_token') || urlParams.get('access_token');
|
|
||||||
const type = hashParams.get('type') || urlParams.get('type');
|
|
||||||
|
|
||||||
// If we have an access_token, this is likely a password reset redirect that landed on the wrong page
|
|
||||||
if (accessToken) {
|
|
||||||
console.log('[Login] Detected access_token, redirecting to reset-password page');
|
|
||||||
|
|
||||||
// Check if it's a password recovery
|
|
||||||
if (type === 'recovery' || type === 'magiclink' || !type) {
|
|
||||||
toast.info('Redirecting to password reset...');
|
|
||||||
navigate('/auth/reset-password?access_token=' + accessToken);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [navigate]);
|
|
||||||
|
|
||||||
const handleEmailLogin = async (e: React.FormEvent) => {
|
const handleEmailLogin = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -49,12 +34,52 @@ export default function LoginPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await loginMutation.mutateAsync({ email, password });
|
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!');
|
toast.success('Login successful!');
|
||||||
|
|
||||||
// Redirect based on onboarding status
|
// Redirect based on onboarding status
|
||||||
if (result.user.location) {
|
if (userData?.location) {
|
||||||
navigate('/dashboard');
|
navigate('/dashboard');
|
||||||
} else {
|
} else {
|
||||||
navigate('/onboarding/user');
|
navigate('/onboarding/user');
|
||||||
@@ -62,25 +87,29 @@ export default function LoginPage() {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[Login] Email login failed:', err);
|
console.error('[Login] Email login failed:', err);
|
||||||
setError((err as Error).message || 'Login failed');
|
setError((err as Error).message || 'Login failed');
|
||||||
|
setIsEmailLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleGithubLogin = async () => {
|
const handleGithubLogin = async () => {
|
||||||
try {
|
try {
|
||||||
setIsGithubLoading(true);
|
setIsGithubLoading(true);
|
||||||
|
// console.log('[Login] Initiating GitHub OAuth...');
|
||||||
|
|
||||||
const result = await signInWithGitHub();
|
const result = await signInWithGitHub();
|
||||||
|
// console.log('[Login] OAuth result:', result);
|
||||||
|
|
||||||
// Check if we got a redirect URL
|
// Check if we got a redirect URL
|
||||||
if (result?.url) {
|
if (result?.url) {
|
||||||
|
// console.log('[Login] Redirecting to GitHub OAuth:', result.url);
|
||||||
|
// Manually redirect immediately
|
||||||
globalThis.location.href = result.url;
|
globalThis.location.href = result.url;
|
||||||
} else {
|
} else {
|
||||||
|
// console.error('[Login] No OAuth URL returned');
|
||||||
setIsGithubLoading(false);
|
setIsGithubLoading(false);
|
||||||
setError('Failed to get GitHub OAuth URL');
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('[Login] GitHub login failed:', err);
|
// console.error('[Login] GitHub login failed');
|
||||||
setError((err as Error).message || 'GitHub login failed');
|
|
||||||
setIsGithubLoading(false);
|
setIsGithubLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -128,7 +157,7 @@ export default function LoginPage() {
|
|||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
placeholder="your@email.com"
|
placeholder="your@email.com"
|
||||||
disabled={loginMutation.isPending}
|
disabled={isEmailLoading}
|
||||||
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
@@ -149,33 +178,24 @@ export default function LoginPage() {
|
|||||||
Forgot password?
|
Forgot password?
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<div className="relative">
|
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
type={showPassword ? 'text' : 'password'}
|
type="password"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
disabled={loginMutation.isPending}
|
disabled={isEmailLoading}
|
||||||
className="w-full px-4 py-2.5 pr-12 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
|
|
||||||
>
|
|
||||||
<Icon icon={showPassword ? 'mdi:eye-off' : 'mdi:eye'} className="text-xl" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={loginMutation.isPending}
|
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 dark:focus:ring-offset-gray-900 disabled:bg-gray-400 dark:disabled:bg-gray-600 disabled:cursor-not-allowed transition-colors cursor-pointer"
|
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 dark:focus:ring-offset-gray-900 disabled:bg-gray-400 dark:disabled:bg-gray-600 disabled:cursor-not-allowed transition-colors cursor-pointer"
|
||||||
>
|
>
|
||||||
{loginMutation.isPending ? 'Signing in...' : 'Sign in with Email'}
|
{isEmailLoading ? 'Signing in...' : 'Sign in with Email'}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -199,28 +219,15 @@ export default function LoginPage() {
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<p className="mt-3 text-xs text-center text-gray-500 dark:text-gray-500 font-sans">
|
|
||||||
Make sure your GitHub email is{' '}
|
|
||||||
<a
|
|
||||||
href="https://github.com/settings/emails"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-primary-600 dark:text-primary-400 hover:underline"
|
|
||||||
>
|
|
||||||
set to public
|
|
||||||
</a>{' '}
|
|
||||||
for GitHub sign in to work.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
<p className="text-gray-600 dark:text-gray-400 text-sm">
|
<p className="text-gray-600 dark:text-gray-400 text-sm">
|
||||||
Don't have an account?{' '}
|
Don't have an account?{' '}
|
||||||
<Link
|
<a
|
||||||
to="/auth/signup"
|
href="/auth/signup"
|
||||||
className="text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300 font-semibold"
|
className="text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300 font-semibold"
|
||||||
>
|
>
|
||||||
Sign up
|
Sign up
|
||||||
</Link>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,33 +1,26 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useResetPassword, useAuthStore } from '@imphnen-frontend-service/service';
|
import { supabase } from '@imphnen-frontend-service/service';
|
||||||
import { useNavigate } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { Icon } from '@iconify/react';
|
|
||||||
|
|
||||||
export default function ResetPasswordPage() {
|
export default function ResetPasswordPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { clearSession } = useAuthStore();
|
|
||||||
const resetPasswordMutation = useResetPassword();
|
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [confirmPassword, setConfirmPassword] = useState('');
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
const [accessToken, setAccessToken] = useState<string | null>(null);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
const [isValidToken, setIsValidToken] = useState(false);
|
||||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
// useEffect(() => {
|
||||||
// Get the access_token from URL hash (Supabase sends it as hash fragment)
|
// // Check if we have a valid session (from the reset link)
|
||||||
// or from query params (when redirected from callback page)
|
// supabase.auth.getSession().then(({ data: { session } }) => {
|
||||||
const hashParams = new URLSearchParams(globalThis.location.hash.substring(1));
|
// if (session) {
|
||||||
const queryParams = new URLSearchParams(globalThis.location.search);
|
// setIsValidToken(true);
|
||||||
const token = hashParams.get('access_token') || queryParams.get('access_token');
|
// } else {
|
||||||
|
// toast.error('Invalid or expired reset link');
|
||||||
if (token) {
|
// setTimeout(() => navigate('/auth/forgot-password'), 2000);
|
||||||
setAccessToken(token);
|
// }
|
||||||
} else {
|
// });
|
||||||
toast.error('Invalid or expired reset link');
|
// }, [navigate]);
|
||||||
setTimeout(() => navigate('/auth/forgot-password'), 2000);
|
|
||||||
}
|
|
||||||
}, [navigate]);
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -42,39 +35,42 @@ export default function ResetPasswordPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
toast.error('Invalid reset token');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await resetPasswordMutation.mutateAsync({
|
setIsLoading(true);
|
||||||
access_token: accessToken,
|
|
||||||
new_password: password,
|
const { error } = await supabase.auth.updateUser({
|
||||||
|
password: password,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
toast.success('Password updated successfully!');
|
toast.success('Password updated successfully!');
|
||||||
|
|
||||||
// Clear session and redirect to login
|
// Sign out and redirect to login
|
||||||
clearSession();
|
await supabase.auth.signOut();
|
||||||
navigate('/auth/login');
|
navigate('/auth/login');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// console.error('Failed to reset password:', err);
|
||||||
toast.error((err as Error).message || 'Failed to reset password');
|
toast.error((err as Error).message || 'Failed to reset password');
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!accessToken) {
|
// if (!isValidToken) {
|
||||||
return (
|
// return (
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950">
|
// <div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950">
|
||||||
<div className="text-center">
|
// <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>
|
// <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 dark:text-gray-400">
|
// <p className="text-gray-600 dark:text-gray-400">
|
||||||
Verifying reset link...
|
// Verifying reset link...
|
||||||
</p>
|
// </p>
|
||||||
</div>
|
// </div>
|
||||||
</div>
|
// </div>
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
||||||
@@ -96,26 +92,17 @@ export default function ResetPasswordPage() {
|
|||||||
>
|
>
|
||||||
New Password
|
New Password
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
type={showPassword ? 'text' : 'password'}
|
type="password"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
disabled={resetPasswordMutation.isPending}
|
disabled={isLoading}
|
||||||
className="w-full px-4 py-2.5 pr-12 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
|
||||||
required
|
required
|
||||||
minLength={6}
|
minLength={6}
|
||||||
/>
|
/>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
|
|
||||||
>
|
|
||||||
<Icon icon={showPassword ? 'mdi:eye-off' : 'mdi:eye'} className="text-xl" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
@@ -125,34 +112,25 @@ export default function ResetPasswordPage() {
|
|||||||
>
|
>
|
||||||
Confirm New Password
|
Confirm New Password
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
|
||||||
<input
|
<input
|
||||||
id="confirmPassword"
|
id="confirmPassword"
|
||||||
type={showConfirmPassword ? 'text' : 'password'}
|
type="password"
|
||||||
value={confirmPassword}
|
value={confirmPassword}
|
||||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
disabled={resetPasswordMutation.isPending}
|
disabled={isLoading}
|
||||||
className="w-full px-4 py-2.5 pr-12 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:bg-gray-100 disabled:cursor-not-allowed bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
|
||||||
required
|
required
|
||||||
minLength={6}
|
minLength={6}
|
||||||
/>
|
/>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
|
|
||||||
>
|
|
||||||
<Icon icon={showConfirmPassword ? 'mdi:eye-off' : 'mdi:eye'} className="text-xl" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={resetPasswordMutation.isPending}
|
disabled={isLoading}
|
||||||
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"
|
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"
|
||||||
>
|
>
|
||||||
{resetPasswordMutation.isPending ? 'Updating...' : 'Update Password'}
|
{isLoading ? 'Updating...' : 'Update Password'}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,200 +1,142 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useGitHubAuth, useSignup } from '@imphnen-frontend-service/service';
|
import {
|
||||||
|
useGitHubAuth,
|
||||||
|
useEmailAuth,
|
||||||
|
supabase,
|
||||||
|
useAuthStore,
|
||||||
|
} from '@imphnen-frontend-service/service';
|
||||||
import { GithubOutlined } from '@ant-design/icons';
|
import { GithubOutlined } from '@ant-design/icons';
|
||||||
import { useNavigate, Link } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { ThemeToggle } from '../../../components/theme-toggle';
|
import { ThemeToggle } from '../../../components/theme-toggle';
|
||||||
import { useForm } from 'react-hook-form';
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
const signupSchema = z
|
|
||||||
.object({
|
|
||||||
fullname: z
|
|
||||||
.string()
|
|
||||||
.min(1, 'Full name is required')
|
|
||||||
.min(2, 'Full name must be at least 2 characters'),
|
|
||||||
email: z
|
|
||||||
.string()
|
|
||||||
.min(1, 'Email is required')
|
|
||||||
.email('Please enter a valid email address'),
|
|
||||||
password: z
|
|
||||||
.string()
|
|
||||||
.min(1, 'Password is required')
|
|
||||||
.min(6, 'Password must be at least 6 characters'),
|
|
||||||
confirmPassword: z.string().min(1, 'Please confirm your password'),
|
|
||||||
})
|
|
||||||
.refine((data) => data.password === data.confirmPassword, {
|
|
||||||
message: 'Passwords do not match',
|
|
||||||
path: ['confirmPassword'],
|
|
||||||
});
|
|
||||||
|
|
||||||
type SignupFormData = z.infer<typeof signupSchema>;
|
|
||||||
|
|
||||||
// Registration deadline: 2025-11-30 23:29:00 WIB (UTC+7)
|
|
||||||
const REGISTRATION_DEADLINE = new Date('2025-11-30T16:29:00Z');
|
|
||||||
|
|
||||||
export default function SignupPage() {
|
export default function SignupPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { setSession } = useAuthStore();
|
||||||
// Check if registration is closed
|
|
||||||
const isRegistrationClosed = new Date() >= REGISTRATION_DEADLINE;
|
|
||||||
const { signInWithGitHub } = useGitHubAuth();
|
const { signInWithGitHub } = useGitHubAuth();
|
||||||
const signupMutation = useSignup();
|
const { signUpWithEmail } = useEmailAuth();
|
||||||
const [isGithubLoading, setIsGithubLoading] = useState(false);
|
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 [error, setError] = useState<string | null>(null);
|
||||||
const [registrationSuccess, setRegistrationSuccess] = useState(false);
|
|
||||||
const [registeredEmail, setRegisteredEmail] = useState('');
|
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
|
||||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
|
||||||
|
|
||||||
const {
|
const handleEmailSignup = async (e: React.FormEvent) => {
|
||||||
register,
|
e.preventDefault();
|
||||||
handleSubmit,
|
|
||||||
formState: { errors, isValid },
|
|
||||||
} = useForm<SignupFormData>({
|
|
||||||
resolver: zodResolver(signupSchema),
|
|
||||||
mode: 'onChange',
|
|
||||||
});
|
|
||||||
|
|
||||||
const onSubmit = async (data: SignupFormData) => {
|
|
||||||
setError(null);
|
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 {
|
try {
|
||||||
const result = await signupMutation.mutateAsync({
|
setIsEmailLoading(true);
|
||||||
email: data.email,
|
// console.log('[Signup] Attempting email signup...');
|
||||||
password: data.password,
|
|
||||||
fullname: data.fullname,
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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(result.message);
|
|
||||||
setRegisteredEmail(data.email);
|
toast.success('Account created successfully!');
|
||||||
setRegistrationSuccess(true);
|
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) {
|
} catch (err) {
|
||||||
console.error('[Signup] Email signup failed:', err);
|
// console.error('[Signup] Email signup failed:', err);
|
||||||
setError((err as Error).message || 'Signup failed');
|
setError((err as Error).message || 'Signup failed');
|
||||||
|
setIsEmailLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Show closed registration screen
|
|
||||||
if (isRegistrationClosed) {
|
|
||||||
return (
|
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
|
||||||
<div className="bg-white dark:bg-gray-900 w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 text-center">
|
|
||||||
<div className="mb-6">
|
|
||||||
<div className="mx-auto w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-4">
|
|
||||||
<Icon
|
|
||||||
icon="mdi:clock-alert"
|
|
||||||
className="text-3xl text-red-600 dark:text-red-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
|
|
||||||
Registration Closed
|
|
||||||
</h2>
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
|
||||||
The registration period for this hackathon has ended.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
|
||||||
Thank you for your interest! Registration closed on November 30, 2025 at 23:29 WIB.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<Link to="/auth/login">
|
|
||||||
<button className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 transition-colors cursor-pointer">
|
|
||||||
Go to Login
|
|
||||||
</button>
|
|
||||||
</Link>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => navigate('/')}
|
|
||||||
className="w-full py-3 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors cursor-pointer"
|
|
||||||
>
|
|
||||||
Back to Homepage
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show success screen after registration
|
|
||||||
if (registrationSuccess) {
|
|
||||||
return (
|
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
|
||||||
<div className="bg-white dark:bg-gray-900 w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 text-center">
|
|
||||||
<div className="mb-6">
|
|
||||||
<div className="mx-auto w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mb-4">
|
|
||||||
<Icon
|
|
||||||
icon="mdi:email-check"
|
|
||||||
className="text-3xl text-green-600 dark:text-green-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
|
|
||||||
Check Your Email
|
|
||||||
</h2>
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
|
||||||
We've sent an activation link to{' '}
|
|
||||||
<strong>{registeredEmail}</strong>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
|
||||||
Click the link in the email to activate your account. The link
|
|
||||||
will expire in 24 hours.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
|
|
||||||
<p className="text-sm text-amber-700 dark:text-amber-300">
|
|
||||||
Don't forget to check your spam folder if you don't see the
|
|
||||||
email.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Link to="/auth/login">
|
|
||||||
<button className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 transition-colors cursor-pointer">
|
|
||||||
Go to Login
|
|
||||||
</button>
|
|
||||||
</Link>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => setRegistrationSuccess(false)}
|
|
||||||
className="w-full py-3 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors cursor-pointer"
|
|
||||||
>
|
|
||||||
Register with different email
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleGithubLogin = async () => {
|
const handleGithubLogin = async () => {
|
||||||
try {
|
try {
|
||||||
setIsGithubLoading(true);
|
setIsGithubLoading(true);
|
||||||
|
// console.log('[Signup] Initiating GitHub OAuth...');
|
||||||
|
|
||||||
const result = await signInWithGitHub();
|
const result = await signInWithGitHub();
|
||||||
|
// console.log('[Signup] OAuth result:', result);
|
||||||
|
|
||||||
if (result?.url) {
|
if (result?.url) {
|
||||||
|
// console.log('[Signup] Redirecting to GitHub OAuth:', result.url);
|
||||||
globalThis.location.href = result.url;
|
globalThis.location.href = result.url;
|
||||||
} else {
|
} else {
|
||||||
|
// console.error('[Signup] No OAuth URL returned');
|
||||||
setIsGithubLoading(false);
|
setIsGithubLoading(false);
|
||||||
setError('Failed to get GitHub OAuth URL');
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
console.error('[Signup] GitHub login failed:', err);
|
// console.error('[Signup] GitHub login failed:', error);
|
||||||
setError((err as Error).message || 'GitHub login failed');
|
|
||||||
setIsGithubLoading(false);
|
setIsGithubLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const inputBaseClass =
|
|
||||||
'w-full px-4 py-2.5 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed';
|
|
||||||
const inputErrorClass = 'border-red-500 dark:border-red-500';
|
|
||||||
const inputNormalClass = 'border-gray-300 dark:border-gray-600';
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
||||||
<div className="bg-white dark:bg-gray-900 w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700">
|
<div className="bg-white dark:bg-gray-900 w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700">
|
||||||
@@ -224,7 +166,7 @@ export default function SignupPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
<form onSubmit={handleEmailSignup} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label
|
<label
|
||||||
htmlFor="fullname"
|
htmlFor="fullname"
|
||||||
@@ -235,18 +177,13 @@ export default function SignupPage() {
|
|||||||
<input
|
<input
|
||||||
id="fullname"
|
id="fullname"
|
||||||
type="text"
|
type="text"
|
||||||
{...register('fullname')}
|
value={fullname}
|
||||||
|
onChange={(e) => setFullname(e.target.value)}
|
||||||
placeholder="John Doe"
|
placeholder="John Doe"
|
||||||
disabled={signupMutation.isPending}
|
disabled={isEmailLoading}
|
||||||
className={`${inputBaseClass} ${
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
||||||
errors.fullname ? inputErrorClass : inputNormalClass
|
required
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
{errors.fullname && (
|
|
||||||
<p className="mt-1 text-sm text-red-500 dark:text-red-400">
|
|
||||||
{errors.fullname.message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
@@ -259,18 +196,13 @@ export default function SignupPage() {
|
|||||||
<input
|
<input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
{...register('email')}
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
placeholder="your@email.com"
|
placeholder="your@email.com"
|
||||||
disabled={signupMutation.isPending}
|
disabled={isEmailLoading}
|
||||||
className={`${inputBaseClass} ${
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
||||||
errors.email ? inputErrorClass : inputNormalClass
|
required
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
{errors.email && (
|
|
||||||
<p className="mt-1 text-sm text-red-500 dark:text-red-400">
|
|
||||||
{errors.email.message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
@@ -280,30 +212,16 @@ export default function SignupPage() {
|
|||||||
>
|
>
|
||||||
Password
|
Password
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
type={showPassword ? 'text' : 'password'}
|
type="password"
|
||||||
{...register('password')}
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
disabled={signupMutation.isPending}
|
disabled={isEmailLoading}
|
||||||
className={`${inputBaseClass} pr-12 ${
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
||||||
errors.password ? inputErrorClass : inputNormalClass
|
required
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
|
|
||||||
>
|
|
||||||
<Icon icon={showPassword ? 'mdi:eye-off' : 'mdi:eye'} className="text-xl" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{errors.password && (
|
|
||||||
<p className="mt-1 text-sm text-red-500 dark:text-red-400">
|
|
||||||
{errors.password.message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
@@ -313,40 +231,24 @@ export default function SignupPage() {
|
|||||||
>
|
>
|
||||||
Confirm Password
|
Confirm Password
|
||||||
</label>
|
</label>
|
||||||
<div className="relative">
|
|
||||||
<input
|
<input
|
||||||
id="confirmPassword"
|
id="confirmPassword"
|
||||||
type={showConfirmPassword ? 'text' : 'password'}
|
type="password"
|
||||||
{...register('confirmPassword')}
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
disabled={signupMutation.isPending}
|
disabled={isEmailLoading}
|
||||||
className={`${inputBaseClass} pr-12 ${
|
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 disabled:cursor-not-allowed"
|
||||||
errors.confirmPassword ? inputErrorClass : inputNormalClass
|
required
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
|
|
||||||
>
|
|
||||||
<Icon icon={showConfirmPassword ? 'mdi:eye-off' : 'mdi:eye'} className="text-xl" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{errors.confirmPassword && (
|
|
||||||
<p className="mt-1 text-sm text-red-500 dark:text-red-400">
|
|
||||||
{errors.confirmPassword.message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={!isValid || signupMutation.isPending}
|
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 dark:focus:ring-offset-gray-900 disabled:bg-gray-400 dark:disabled:bg-gray-600 disabled:cursor-not-allowed transition-colors cursor-pointer"
|
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 dark:focus:ring-offset-gray-900 disabled:bg-gray-400 dark:disabled:bg-gray-600 disabled:cursor-not-allowed transition-colors cursor-pointer"
|
||||||
>
|
>
|
||||||
{signupMutation.isPending
|
{isEmailLoading ? 'Creating account...' : 'Create Account'}
|
||||||
? 'Creating account...'
|
|
||||||
: 'Create Account'}
|
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -370,28 +272,15 @@ export default function SignupPage() {
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<p className="mt-3 text-xs text-center text-gray-500 dark:text-gray-500 font-sans">
|
|
||||||
Make sure your GitHub email is{' '}
|
|
||||||
<a
|
|
||||||
href="https://github.com/settings/emails"
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-primary-600 dark:text-primary-400 hover:underline"
|
|
||||||
>
|
|
||||||
set to public
|
|
||||||
</a>{' '}
|
|
||||||
for GitHub sign up to work.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="mt-6 text-center">
|
<div className="mt-6 text-center">
|
||||||
<p className="text-gray-600 dark:text-gray-400 text-sm">
|
<p className="text-gray-600 dark:text-gray-400 text-sm">
|
||||||
Already have an account?{' '}
|
Already have an account?{' '}
|
||||||
<Link
|
<a
|
||||||
to="/auth/login"
|
href="/auth/login"
|
||||||
className="text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300 font-semibold"
|
className="text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300 font-semibold"
|
||||||
>
|
>
|
||||||
Sign in
|
Sign in
|
||||||
</Link>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -11,9 +11,6 @@ import { Button } from '@imphnen-frontend-service/ui/atoms';
|
|||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import ProfilePage from '../profile/page';
|
import ProfilePage from '../profile/page';
|
||||||
|
|
||||||
// Team features deadline: 2025-11-30 23:59:00 WIB (UTC+7)
|
|
||||||
const TEAM_FEATURES_DEADLINE = new Date('2025-11-30T16:59:00Z');
|
|
||||||
|
|
||||||
type Invitation = {
|
type Invitation = {
|
||||||
id: string;
|
id: string;
|
||||||
team: {
|
team: {
|
||||||
@@ -37,9 +34,6 @@ type Invitation = {
|
|||||||
const DashboardPage: FC = (): ReactElement => {
|
const DashboardPage: FC = (): ReactElement => {
|
||||||
const { session } = useAuthStore();
|
const { session } = useAuthStore();
|
||||||
const [showProfileModal, setShowProfileModal] = useState(false);
|
const [showProfileModal, setShowProfileModal] = useState(false);
|
||||||
|
|
||||||
// Check if team features are closed
|
|
||||||
const isTeamFeaturesClosed = new Date() >= TEAM_FEATURES_DEADLINE;
|
|
||||||
// Lock background scroll when profile modal is open
|
// Lock background scroll when profile modal is open
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (showProfileModal) {
|
if (showProfileModal) {
|
||||||
@@ -99,14 +93,6 @@ const DashboardPage: FC = (): ReactElement => {
|
|||||||
<h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
|
<h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
|
||||||
Team Invitations ({invitations.length})
|
Team Invitations ({invitations.length})
|
||||||
</h2>
|
</h2>
|
||||||
{isTeamFeaturesClosed && (
|
|
||||||
<div className="mb-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
|
|
||||||
<p className="text-sm text-amber-700 dark:text-amber-300 flex items-center gap-2">
|
|
||||||
<Icon icon="mdi:clock-alert" className="text-lg shrink-0" />
|
|
||||||
Team features are closed. You can no longer accept invitations.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="space-y-3 font-sans">
|
<div className="space-y-3 font-sans">
|
||||||
{invitations.map((invitation) => (
|
{invitations.map((invitation) => (
|
||||||
<div
|
<div
|
||||||
@@ -122,7 +108,6 @@ const DashboardPage: FC = (): ReactElement => {
|
|||||||
{invitation.inviter?.fullname ?? 'Unknown User'}
|
{invitation.inviter?.fullname ?? 'Unknown User'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{!isTeamFeaturesClosed && (
|
|
||||||
<div className="flex space-x-2">
|
<div className="flex space-x-2">
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -138,7 +123,6 @@ const DashboardPage: FC = (): ReactElement => {
|
|||||||
Decline
|
Decline
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -146,69 +130,57 @@ const DashboardPage: FC = (): ReactElement => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{myTeams.length > 0 ? (
|
{myTeams.length > 0 ? (
|
||||||
(() => {
|
|
||||||
const team = myTeams[0] as any;
|
|
||||||
return (
|
|
||||||
<div className="mb-6 md:mb-8">
|
<div className="mb-6 md:mb-8">
|
||||||
<h2 className="text-xl md:text-2xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
<h2 className="text-xl md:text-2xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
||||||
My Team
|
My Team
|
||||||
</h2>
|
</h2>
|
||||||
|
<div className="grid grid-cols-1 gap-4 md:gap-6 w-full md:max-w-lg">
|
||||||
|
{myTeams.map((team) => (
|
||||||
<Link
|
<Link
|
||||||
|
key={team.id}
|
||||||
to={'/teams/' + team.id}
|
to={'/teams/' + team.id}
|
||||||
className="block bg-white dark:bg-gray-900 rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow border dark:border-gray-700"
|
className="bg-white dark:bg-gray-900 rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow"
|
||||||
>
|
>
|
||||||
|
{team.banner && (
|
||||||
|
<div className="w-full aspect-3/1">
|
||||||
<img
|
<img
|
||||||
src={team.banner || '/images/banner-imphnen.webp'}
|
src={team.banner}
|
||||||
alt={team.name}
|
alt={team.name}
|
||||||
className="w-full aspect-3/1 object-cover"
|
className="w-full h-full object-cover"
|
||||||
/>
|
/>
|
||||||
<div className="p-4 md:p-6">
|
</div>
|
||||||
<div className="flex items-center space-x-4 mb-4">
|
)}
|
||||||
{team.logo ? (
|
<div className="p-4">
|
||||||
|
<div className="flex flex-col md:flex-row items-center space-y-3 space-x-3 -mt-14 md:mt-0 mb-2 md:mb-3 min-w-12 min-h-12 ">
|
||||||
|
{team.logo && (
|
||||||
<img
|
<img
|
||||||
src={team.logo}
|
src={team.logo}
|
||||||
alt={team.name}
|
alt={team.name}
|
||||||
className="w-16 h-16 rounded-full object-cover shrink-0"
|
className="w-20 h-20 rounded-full object-cover shrink-0 border-black dark:border-gray-700"
|
||||||
/>
|
/>
|
||||||
) : (
|
|
||||||
<div className="w-16 h-16 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center shrink-0">
|
|
||||||
<Icon icon="mdi:account-group" className="text-gray-500 dark:text-gray-400 text-2xl" />
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
<div className="flex-1 min-w-0">
|
<div>
|
||||||
<h3 className="text-xl md:text-2xl font-bold text-gray-900 dark:text-white leading-tight line-clamp-1">
|
<h3 className="text-xl md:text-lg font-bold text-gray-900 dark:text-white leading-tight">
|
||||||
{team.name}
|
{team.name}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="text-sm text-gray-600 dark:text-gray-400 flex items-center gap-3 font-sans mt-2">
|
<p className="text-sm text-gray-600 dark:text-gray-400 flex items-center">
|
||||||
{team.has_submission && (
|
<Icon
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 shrink-0">
|
icon="heroicons:map-pin-16-solid"
|
||||||
<Icon icon="mdi:check-circle" className="text-sm" />
|
width="16"
|
||||||
Submitted
|
height="16"
|
||||||
</span>
|
/>
|
||||||
)}
|
<span className="ml-1">{team.city}</span>
|
||||||
{team.city && (
|
</p>
|
||||||
<span className="flex items-center gap-1 truncate">
|
|
||||||
<Icon icon="mdi:map-marker" className="shrink-0" />
|
|
||||||
<span className="truncate">{team.city}</span>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<span className="flex items-center gap-1 shrink-0">
|
|
||||||
<Icon icon="mdi:account-group" />
|
|
||||||
{team.member_count || team.members?.length || 0} member{(team.member_count || team.members?.length || 0) !== 1 ? 's' : ''}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<p className="text-gray-600 dark:text-gray-400 line-clamp-3 text-ellipsis font-sans">
|
||||||
{team.description && (
|
|
||||||
<p className="text-gray-600 dark:text-gray-400 line-clamp-3 font-sans">
|
|
||||||
{team.description}
|
{team.description}
|
||||||
</p>
|
</p>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
|
||||||
})()
|
|
||||||
) : (
|
) : (
|
||||||
<div className="mb-6 md:mb-8 bg-white dark:bg-gray-900 rounded-lg shadow-md p-6 md:p-8">
|
<div className="mb-6 md:mb-8 bg-white dark:bg-gray-900 rounded-lg shadow-md p-6 md:p-8">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
import {
|
import { Outlet, ScrollRestoration, useLocation, useNavigate } from 'react-router-dom';
|
||||||
Outlet,
|
|
||||||
ScrollRestoration,
|
|
||||||
useLocation,
|
|
||||||
useNavigate,
|
|
||||||
} from 'react-router-dom';
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useAuthStore, useUserMe } from '@imphnen-frontend-service/service';
|
import { supabase } from '@imphnen-frontend-service/service';
|
||||||
|
|
||||||
// Define onboarding routes
|
// Define onboarding routes
|
||||||
const ONBOARDING_ROUTES = new Set(['/onboarding/user']);
|
const ONBOARDING_ROUTES = new Set(['/onboarding/user']);
|
||||||
@@ -13,8 +8,6 @@ const ONBOARDING_ROUTES = new Set(['/onboarding/user']);
|
|||||||
export default function RootLayout() {
|
export default function RootLayout() {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { session } = useAuthStore();
|
|
||||||
const { data: userData, isLoading: isUserLoading } = useUserMe();
|
|
||||||
const [isChecking, setIsChecking] = useState(true);
|
const [isChecking, setIsChecking] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -33,15 +26,24 @@ export default function RootLayout() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Public auth pages - allow unauthenticated access
|
// Check Supabase session
|
||||||
if (pathname.startsWith('/auth')) {
|
const { data: { session }, error } = await supabase.auth.getSession();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('[Layout] Session error:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public auth pages (login, signup, forgot-password, reset-password) - allow unauthenticated access
|
||||||
|
const isPublicAuthPage = pathname === '/auth/login' || pathname === '/auth/signup' || pathname === '/auth/forgot-password' || pathname === '/auth/reset-password';
|
||||||
|
|
||||||
|
if (isPublicAuthPage) {
|
||||||
// If already authenticated and not on password reset pages, redirect to dashboard
|
// If already authenticated and not on password reset pages, redirect to dashboard
|
||||||
if (session && pathname !== '/auth/reset-password') {
|
if (session && pathname !== '/auth/reset-password') {
|
||||||
navigate('/dashboard', { replace: true });
|
navigate('/dashboard', { replace: true });
|
||||||
setIsChecking(false);
|
setIsChecking(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Allow unauthenticated access to auth pages
|
// Allow unauthenticated access
|
||||||
setIsChecking(false);
|
setIsChecking(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -59,27 +61,38 @@ export default function RootLayout() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait for user data to load before checking onboarding
|
// Check if user has completed onboarding (skip for onboarding routes)
|
||||||
if (isUserLoading) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user has completed onboarding (skip for onboarding routes)
|
const hasLocation = !!userData?.location;
|
||||||
if (!ONBOARDING_ROUTES.has(pathname)) {
|
|
||||||
const hasLocation = !!userData?.data?.location || !!session?.user?.location;
|
|
||||||
|
|
||||||
if (!hasLocation) {
|
if (!hasLocation) {
|
||||||
navigate('/onboarding/user', { replace: true });
|
navigate('/onboarding/user', { replace: true });
|
||||||
setIsChecking(false);
|
setIsChecking(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Silently handle error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setIsChecking(false);
|
setIsChecking(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
checkAuth();
|
checkAuth();
|
||||||
}, [location.pathname, navigate, session, userData, isUserLoading]);
|
}, [location.pathname, navigate]);
|
||||||
|
|
||||||
// Show loading state while checking auth
|
// Show loading state while checking auth
|
||||||
if (isChecking) {
|
if (isChecking) {
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
import { Link } from 'react-router';
|
|
||||||
|
|
||||||
export default function MaintenancePage() {
|
|
||||||
return (
|
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 px-4">
|
|
||||||
<div className="text-center">
|
|
||||||
<h1 className="text-6xl font-bold text-yellow-600 mb-4">🚧</h1>
|
|
||||||
<h2 className="text-3xl font-semibold mb-2">We'll be back soon!</h2>
|
|
||||||
<p className="text-gray-600">
|
|
||||||
Our site is currently undergoing scheduled maintenance.
|
|
||||||
<br />
|
|
||||||
Thank you for your patience.
|
|
||||||
</p>
|
|
||||||
<Link
|
|
||||||
to="/"
|
|
||||||
className="mt-4 inline-block text-primary-600 hover:underline"
|
|
||||||
>
|
|
||||||
Back to Homepage
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -60,20 +60,6 @@ const UserOnboardingPage: FC = (): ReactElement => {
|
|||||||
const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file) {
|
if (file) {
|
||||||
// Validate file size (max 2MB)
|
|
||||||
if (file.size > 2 * 1024 * 1024) {
|
|
||||||
toast.error('The file is too large. Maximum size is 2MB.');
|
|
||||||
e.target.value = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file type
|
|
||||||
if (!file.type.startsWith('image/')) {
|
|
||||||
toast.error('The file must be an image');
|
|
||||||
e.target.value = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setAvatarFile(file);
|
setAvatarFile(file);
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onloadend = () => {
|
reader.onloadend = () => {
|
||||||
@@ -164,7 +150,7 @@ const UserOnboardingPage: FC = (): ReactElement => {
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<p className="text-xs text-gray-500 dark:text-gray-500 mt-2 text-center">
|
<p className="text-xs text-gray-500 dark:text-gray-500 mt-2 text-center">
|
||||||
Optional, but highly recommended. Max 2MB
|
Optional, but highly recommended
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useNavigate, Link } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
@@ -796,12 +796,12 @@ export default function HomePage() {
|
|||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<Link
|
<a
|
||||||
to="/auth/signup"
|
href="/auth/signup"
|
||||||
className="hover:text-white transition-colors"
|
className="hover:text-white transition-colors"
|
||||||
>
|
>
|
||||||
Daftar
|
Daftar
|
||||||
</Link>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -84,17 +84,15 @@ const ProfilePage: FC<ProfileModalProps> = ({
|
|||||||
const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file) {
|
if (file) {
|
||||||
// Validate file size (max 2MB)
|
// Validate file size (max 5MB)
|
||||||
if (file.size > 2 * 1024 * 1024) {
|
if (file.size > 5 * 1024 * 1024) {
|
||||||
toast.error('The file is too large. Maximum size is 2MB.');
|
toast.error('The file is too large. Maximum 5MB');
|
||||||
e.target.value = '';
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate file type
|
// Validate file type
|
||||||
if (!file.type.startsWith('image/')) {
|
if (!file.type.startsWith('image/')) {
|
||||||
toast.error('The file must be an image');
|
toast.error('The file must be an image');
|
||||||
e.target.value = '';
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,7 +235,7 @@ const ProfilePage: FC<ProfileModalProps> = ({
|
|||||||
<p className="text-sm text-gray-500 dark:text-neutral-400 text-center font-sans">
|
<p className="text-sm text-gray-500 dark:text-neutral-400 text-center font-sans">
|
||||||
Click the camera icon to change your photo
|
Click the camera icon to change your photo
|
||||||
<br />
|
<br />
|
||||||
Format: JPG, PNG. Max 2MB
|
Format: JPG, PNG. Max 5MB
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,6 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
|||||||
|
|
||||||
import { CitySelect } from '../../../../components/city-select';
|
import { CitySelect } from '../../../../components/city-select';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { toast } from 'sonner';
|
|
||||||
|
|
||||||
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
|
|
||||||
|
|
||||||
const EditTeamPage: FC = (): ReactElement => {
|
const EditTeamPage: FC = (): ReactElement => {
|
||||||
const { teamId } = useParams<{ teamId: string }>();
|
const { teamId } = useParams<{ teamId: string }>();
|
||||||
@@ -88,11 +85,6 @@ const EditTeamPage: FC = (): ReactElement => {
|
|||||||
const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file) {
|
if (file) {
|
||||||
if (file.size > MAX_FILE_SIZE) {
|
|
||||||
toast.error('Logo image is too large. Maximum size is 2MB.');
|
|
||||||
e.target.value = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setLogoFile(file);
|
setLogoFile(file);
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onloadend = () => {
|
reader.onloadend = () => {
|
||||||
@@ -105,11 +97,6 @@ const EditTeamPage: FC = (): ReactElement => {
|
|||||||
const handleBannerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleBannerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file) {
|
if (file) {
|
||||||
if (file.size > MAX_FILE_SIZE) {
|
|
||||||
toast.error('Banner image is too large. Maximum size is 2MB.');
|
|
||||||
e.target.value = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setBannerFile(file);
|
setBannerFile(file);
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onloadend = () => {
|
reader.onloadend = () => {
|
||||||
@@ -196,7 +183,7 @@ const EditTeamPage: FC = (): ReactElement => {
|
|||||||
Click to upload banner
|
Click to upload banner
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
|
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
|
||||||
1200x400 recommended. Max 2MB
|
1200x400 recommended
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
@@ -228,7 +215,6 @@ const EditTeamPage: FC = (): ReactElement => {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div>
|
|
||||||
<div className="flex flex-col md:flex-row items-start justify-start gap-1">
|
<div className="flex flex-col md:flex-row items-start justify-start gap-1">
|
||||||
<label htmlFor="logo" className="cursor-pointer">
|
<label htmlFor="logo" className="cursor-pointer">
|
||||||
<span className="px-4 py-2 text-sm bg-primary-600 text-white rounded-lg hover:bg-primary-700 inline-block">
|
<span className="px-4 py-2 text-sm bg-primary-600 text-white rounded-lg hover:bg-primary-700 inline-block">
|
||||||
@@ -256,8 +242,6 @@ const EditTeamPage: FC = (): ReactElement => {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-gray-400 dark:text-gray-500 mt-2">Max 2MB</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,6 @@ const ManageMembersPage: FC = (): ReactElement => {
|
|||||||
: [];
|
: [];
|
||||||
const currentUserId = session?.user?.id;
|
const currentUserId = session?.user?.id;
|
||||||
const isLeader = currentUserId === team?.leader_id;
|
const isLeader = currentUserId === team?.leader_id;
|
||||||
const hasSubmission = team?.has_submission;
|
|
||||||
|
|
||||||
const form = useForm<TInviteMemberForm>({
|
const form = useForm<TInviteMemberForm>({
|
||||||
resolver: zodResolver(inviteMemberSchema),
|
resolver: zodResolver(inviteMemberSchema),
|
||||||
@@ -134,11 +133,7 @@ const ManageMembersPage: FC = (): ReactElement => {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex space-x-3">
|
<div className="flex space-x-3">
|
||||||
<Button
|
<Button onClick={() => setShowInviteModal(true)}>
|
||||||
onClick={() => setShowInviteModal(true)}
|
|
||||||
disabled={hasSubmission}
|
|
||||||
title={hasSubmission ? 'Cannot invite members after project submission' : undefined}
|
|
||||||
>
|
|
||||||
Invite Member
|
Invite Member
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
@@ -153,23 +148,6 @@ const ManageMembersPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
|
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
|
||||||
{/* Submission Lock Warning */}
|
|
||||||
{hasSubmission && (
|
|
||||||
<div className="bg-amber-50 dark:bg-amber-900/20 border-2 border-amber-500 rounded-lg p-4">
|
|
||||||
<div className="flex items-start space-x-3">
|
|
||||||
<span className="text-2xl">🔒</span>
|
|
||||||
<div>
|
|
||||||
<h3 className="font-bold text-amber-900 dark:text-amber-100">
|
|
||||||
Team Locked
|
|
||||||
</h3>
|
|
||||||
<p className="text-amber-800 dark:text-amber-200 text-sm font-sans mt-1">
|
|
||||||
Your team has submitted a project. You cannot add or remove members after submission to maintain competition integrity.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Join Requests */}
|
{/* Join Requests */}
|
||||||
{joinRequests.length > 0 && (
|
{joinRequests.length > 0 && (
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md dark:shadow-gray-950/50 p-6">
|
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md dark:shadow-gray-950/50 p-6">
|
||||||
@@ -218,8 +196,7 @@ const ManageMembersPage: FC = (): ReactElement => {
|
|||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => handleApproveRequest(request.id)}
|
onClick={() => handleApproveRequest(request.id)}
|
||||||
disabled={isResponding || hasSubmission}
|
disabled={isResponding}
|
||||||
title={hasSubmission ? 'Cannot accept members after project submission' : undefined}
|
|
||||||
>
|
>
|
||||||
Approve
|
Approve
|
||||||
</Button>
|
</Button>
|
||||||
@@ -295,7 +272,7 @@ const ManageMembersPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{member.role !== 'leader' && !hasSubmission && (
|
{member.role !== 'leader' && (
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
@@ -312,14 +289,12 @@ const ManageMembersPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Warning */}
|
{/* Warning */}
|
||||||
{!hasSubmission && (
|
|
||||||
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
|
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
|
||||||
<p className="text-sm text-yellow-800 dark:text-yellow-200">
|
<p className="text-sm text-yellow-800 dark:text-yellow-200">
|
||||||
<strong>Note:</strong> Members cannot leave the team without your
|
<strong>Note:</strong> Members cannot leave the team without your
|
||||||
approval. Only you can remove members from the team.
|
approval. Only you can remove members from the team.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Invite Member Modal */}
|
{/* Invite Member Modal */}
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ import {
|
|||||||
useInviteMember,
|
useInviteMember,
|
||||||
useTeamJoinRequests,
|
useTeamJoinRequests,
|
||||||
useRespondToJoinRequest,
|
useRespondToJoinRequest,
|
||||||
useLeaveTeam,
|
|
||||||
useDeleteTeam,
|
|
||||||
ETeamMemberRole,
|
ETeamMemberRole,
|
||||||
useAuthStore,
|
useAuthStore,
|
||||||
} from '@imphnen-frontend-service/service';
|
} from '@imphnen-frontend-service/service';
|
||||||
@@ -17,9 +15,6 @@ import { Icon } from '@iconify/react';
|
|||||||
|
|
||||||
const MAX_TEAM_MEMBERS = 5;
|
const MAX_TEAM_MEMBERS = 5;
|
||||||
|
|
||||||
// Team features deadline: 2025-11-30 23:59:00 WIB (UTC+7)
|
|
||||||
const TEAM_FEATURES_DEADLINE = new Date('2025-11-30T16:59:00Z');
|
|
||||||
|
|
||||||
// Image component with loading state
|
// Image component with loading state
|
||||||
const ImageWithLoader: FC<{
|
const ImageWithLoader: FC<{
|
||||||
src: string;
|
src: string;
|
||||||
@@ -55,14 +50,8 @@ const TeamDashboardPage: FC = (): ReactElement => {
|
|||||||
const { teamId } = useParams<{ teamId: string }>();
|
const { teamId } = useParams<{ teamId: string }>();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { session } = useAuthStore();
|
const { session } = useAuthStore();
|
||||||
|
|
||||||
// Check if team features are closed
|
|
||||||
const isTeamFeaturesClosed = new Date() >= TEAM_FEATURES_DEADLINE;
|
|
||||||
const [showInviteModal, setShowInviteModal] = useState(false);
|
const [showInviteModal, setShowInviteModal] = useState(false);
|
||||||
const [showJoinRequestsModal, setShowJoinRequestsModal] = useState(false);
|
const [showJoinRequestsModal, setShowJoinRequestsModal] = useState(false);
|
||||||
const [showLeaveModal, setShowLeaveModal] = useState(false);
|
|
||||||
const [showDeleteModal, setShowDeleteModal] = useState(false);
|
|
||||||
const [deleteConfirmText, setDeleteConfirmText] = useState('');
|
|
||||||
const [inviteEmail, setInviteEmail] = useState('');
|
const [inviteEmail, setInviteEmail] = useState('');
|
||||||
const [imagesLoaded, setImagesLoaded] = useState(false);
|
const [imagesLoaded, setImagesLoaded] = useState(false);
|
||||||
const [imageLoadCount, setImageLoadCount] = useState(0);
|
const [imageLoadCount, setImageLoadCount] = useState(0);
|
||||||
@@ -96,29 +85,25 @@ const TeamDashboardPage: FC = (): ReactElement => {
|
|||||||
const { data: membersData, isLoading: isLoadingMembers } = useTeamMembers(
|
const { data: membersData, isLoading: isLoadingMembers } = useTeamMembers(
|
||||||
teamId || ''
|
teamId || ''
|
||||||
);
|
);
|
||||||
|
|
||||||
const team = teamData?.data;
|
|
||||||
const members = membersData?.data || [];
|
|
||||||
const currentUserId = session?.user?.id;
|
|
||||||
const isLeader = currentUserId === team?.leader_id;
|
|
||||||
|
|
||||||
// Only fetch join requests if user is the team leader
|
|
||||||
const { data: joinRequestsData } = useTeamJoinRequests(
|
const { data: joinRequestsData } = useTeamJoinRequests(
|
||||||
teamId || '',
|
teamId || '',
|
||||||
!!teamId && isLeader
|
!!teamId
|
||||||
);
|
);
|
||||||
const { mutateAsync: inviteMember, isPending: isInviting } = useInviteMember(
|
const { mutateAsync: inviteMember, isPending: isInviting } = useInviteMember(
|
||||||
teamId || ''
|
teamId || ''
|
||||||
);
|
);
|
||||||
const { mutateAsync: respondToJoinRequest, isPending: isResponding } =
|
const { mutateAsync: respondToJoinRequest, isPending: isResponding } =
|
||||||
useRespondToJoinRequest(teamId || '');
|
useRespondToJoinRequest(teamId || '');
|
||||||
const { mutateAsync: leaveTeam, isPending: isLeaving } = useLeaveTeam();
|
|
||||||
const { mutateAsync: deleteTeam, isPending: isDeleting } = useDeleteTeam();
|
|
||||||
|
|
||||||
|
const team = teamData?.data;
|
||||||
|
const members = membersData?.data || [];
|
||||||
const joinRequests = joinRequestsData?.data || [];
|
const joinRequests = joinRequestsData?.data || [];
|
||||||
const pendingJoinRequests = joinRequests.filter(
|
const pendingJoinRequests = joinRequests.filter(
|
||||||
(req: any) => req.status === 'pending'
|
(req: any) => req.status === 'pending'
|
||||||
);
|
);
|
||||||
|
const currentUserId = session?.user?.id;
|
||||||
|
|
||||||
|
const isLeader = currentUserId === team?.leader_id;
|
||||||
const isMember = members.some(
|
const isMember = members.some(
|
||||||
(member: any) => member.user_id === currentUserId
|
(member: any) => member.user_id === currentUserId
|
||||||
);
|
);
|
||||||
@@ -154,32 +139,6 @@ const TeamDashboardPage: FC = (): ReactElement => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLeaveTeam = async () => {
|
|
||||||
if (!teamId) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await leaveTeam(teamId);
|
|
||||||
toast.success('You have left the team');
|
|
||||||
navigate('/dashboard');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to leave team:', error);
|
|
||||||
toast.error('Failed to leave team');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDeleteTeam = async () => {
|
|
||||||
if (!teamId) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await deleteTeam(teamId);
|
|
||||||
toast.success('Team deleted successfully');
|
|
||||||
navigate('/dashboard');
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error('Failed to delete team:', error);
|
|
||||||
toast.error(error?.message || 'Failed to delete team');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isLoadingTeam || isLoadingMembers) {
|
if (isLoadingTeam || isLoadingMembers) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
|
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
|
||||||
@@ -375,9 +334,6 @@ const TeamDashboardPage: FC = (): ReactElement => {
|
|||||||
Team Management
|
Team Management
|
||||||
</h2>
|
</h2>
|
||||||
<div className="grid gap-3 sm:grid-cols-2">
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
{/* Hide invite/join management after submission or deadline */}
|
|
||||||
{!team.has_submission && !isTeamFeaturesClosed && (
|
|
||||||
<>
|
|
||||||
<Button
|
<Button
|
||||||
className="w-full"
|
className="w-full"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
@@ -401,23 +357,19 @@ const TeamDashboardPage: FC = (): ReactElement => {
|
|||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{!team.has_submission && !isTeamFeaturesClosed && (
|
|
||||||
<Link to={`/teams/${teamId}/edit`}>
|
<Link to={`/teams/${teamId}/edit`}>
|
||||||
<Button className="w-full" variant="secondary">
|
<Button className="w-full" variant="secondary">
|
||||||
<Icon icon="mdi:pencil" className="inline-block mr-2" />
|
<Icon icon="mdi:pencil" className="inline-block mr-2" />
|
||||||
Edit Team Info
|
Edit Team Info
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
|
||||||
<Link to={`/teams/${teamId}/members`}>
|
<Link to={`/teams/${teamId}/members`}>
|
||||||
<Button className="w-full" variant="secondary">
|
<Button className="w-full" variant="secondary">
|
||||||
<Icon
|
<Icon
|
||||||
icon="mdi:account-group"
|
icon="mdi:account-group"
|
||||||
className="inline-block mr-2"
|
className="inline-block mr-2"
|
||||||
/>
|
/>
|
||||||
View Members
|
Manage Members
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
<Link to={`/teams/${teamId}/chat`}>
|
<Link to={`/teams/${teamId}/chat`}>
|
||||||
@@ -426,92 +378,40 @@ const TeamDashboardPage: FC = (): ReactElement => {
|
|||||||
Team Chat
|
Team Chat
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
{team.has_submission ? (
|
|
||||||
<Link to={`/teams/${teamId}/submission`}>
|
|
||||||
<Button className="w-full" variant="secondary">
|
|
||||||
<Icon icon="mdi:file-document" className="inline-block mr-2" />
|
|
||||||
View Submission
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
) : (
|
|
||||||
<Link to={`/teams/${teamId}/submit`}>
|
<Link to={`/teams/${teamId}/submit`}>
|
||||||
<Button className="w-full" disabled={members.length < 2}>
|
<Button className="w-full">
|
||||||
<Icon icon="mdi:rocket" className="inline-block mr-2" />
|
<Icon icon="mdi:rocket" className="inline-block mr-2" />
|
||||||
Submit Project
|
Submit Project
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
{!team.has_submission && !canInvite && members.length >= MAX_TEAM_MEMBERS && (
|
{!canInvite && members.length >= MAX_TEAM_MEMBERS && (
|
||||||
<p className="text-sm text-gray-600 dark:text-gray-400 mt-3 text-center">
|
<p className="text-sm text-gray-600 dark:text-gray-400 mt-3 text-center">
|
||||||
Maximum team size reached ({MAX_TEAM_MEMBERS} members)
|
Maximum team size reached ({MAX_TEAM_MEMBERS} members)
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{/* Danger Zone - Only show when leader is alone, no submission, and features not closed */}
|
|
||||||
{members.length === 1 && !team.has_submission && !isTeamFeaturesClosed && (
|
|
||||||
<div className="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
|
|
||||||
<h3 className="text-sm font-medium text-red-600 dark:text-red-400 mb-3">
|
|
||||||
Danger Zone
|
|
||||||
</h3>
|
|
||||||
<Button
|
|
||||||
className="w-full bg-red-600 hover:bg-red-700 text-white"
|
|
||||||
onClick={() => setShowDeleteModal(true)}
|
|
||||||
>
|
|
||||||
<Icon icon="mdi:delete" className="inline-block mr-2" />
|
|
||||||
Delete Team
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Quick Actions for Members (non-leaders) */}
|
{/* Quick Actions for Members (non-leaders) */}
|
||||||
{!isLeader && isMember && (
|
{!isLeader && isMember && (
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md p-4 md:p-6">
|
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4 md:p-6">
|
||||||
<h2 className="text-lg md:text-xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
<h2 className="text-lg md:text-xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
||||||
Quick Actions
|
Quick Actions
|
||||||
</h2>
|
</h2>
|
||||||
<div className="grid gap-3 sm:grid-cols-2">
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
<Link to={`/teams/${teamId}/chat`}>
|
<Link to={`/teams/${teamId}/chat`}>
|
||||||
<Button className="w-full" variant="secondary">
|
<Button className="w-full" variant="secondary">
|
||||||
<Icon icon="mdi:chat" className="inline-block mr-2" />
|
💬 Team Chat
|
||||||
Team Chat
|
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
{team.has_submission && (
|
{team.has_submission && (
|
||||||
<Link to={`/teams/${teamId}/submission`}>
|
<Link to={`/teams/${teamId}/submission`}>
|
||||||
<Button className="w-full" variant="secondary">
|
<Button className="w-full" variant="secondary">
|
||||||
<Icon icon="mdi:file-document" className="inline-block mr-2" />
|
📄 View Submission
|
||||||
View Submission
|
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
{!team.has_submission && !isTeamFeaturesClosed && (
|
|
||||||
<Button
|
|
||||||
className="w-full bg-red-600 hover:bg-red-700 text-white"
|
|
||||||
onClick={() => setShowLeaveModal(true)}
|
|
||||||
>
|
|
||||||
<Icon icon="mdi:exit-run" className="inline-block mr-2" />
|
|
||||||
Leave Team
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Warning for single member teams */}
|
|
||||||
{members.length === 1 && !team.has_submission && isMember && (
|
|
||||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 md:p-6">
|
|
||||||
<div className="flex items-center space-x-3">
|
|
||||||
<span className="text-3xl">⚠️</span>
|
|
||||||
<div>
|
|
||||||
<h3 className="font-bold text-amber-900 dark:text-amber-400">
|
|
||||||
Team Needs More Members
|
|
||||||
</h3>
|
|
||||||
<p className="text-amber-700 dark:text-amber-300 text-sm">
|
|
||||||
Your team needs at least 2 members to submit a project. Invite someone or wait for join requests!
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -796,110 +696,6 @@ const TeamDashboardPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Leave Team Confirmation Modal */}
|
|
||||||
{showLeaveModal && (
|
|
||||||
<div className="fixed inset-0 bg-black/30 dark:bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-md w-full p-6">
|
|
||||||
<div className="text-center mb-6">
|
|
||||||
<div className="mx-auto w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-4">
|
|
||||||
<Icon
|
|
||||||
icon="mdi:exit-run"
|
|
||||||
className="text-3xl text-red-600 dark:text-red-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
|
|
||||||
Leave Team?
|
|
||||||
</h2>
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
|
||||||
Are you sure you want to leave <strong>{team?.name}</strong>?
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-6">
|
|
||||||
<p className="text-sm text-amber-800 dark:text-amber-300 font-sans">
|
|
||||||
<strong>Warning:</strong> If you leave, you will need to request to join again or be re-invited by the team leader.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex space-x-3">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="secondary"
|
|
||||||
className="flex-1"
|
|
||||||
onClick={() => setShowLeaveModal(false)}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleLeaveTeam}
|
|
||||||
className="flex-1 bg-red-600 hover:bg-red-700"
|
|
||||||
disabled={isLeaving}
|
|
||||||
>
|
|
||||||
{isLeaving ? 'Leaving...' : 'Leave Team'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Delete Team Confirmation Modal */}
|
|
||||||
{showDeleteModal && (
|
|
||||||
<div className="fixed inset-0 bg-black/30 dark:bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-md w-full p-6">
|
|
||||||
<div className="text-center mb-6">
|
|
||||||
<div className="mx-auto w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-4">
|
|
||||||
<Icon
|
|
||||||
icon="mdi:delete-alert"
|
|
||||||
className="text-3xl text-red-600 dark:text-red-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
|
|
||||||
Delete Team?
|
|
||||||
</h2>
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
|
||||||
This action is <strong className="text-red-600 dark:text-red-400">permanent</strong> and cannot be undone.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6">
|
|
||||||
<p className="text-sm text-red-800 dark:text-red-300 font-sans">
|
|
||||||
<strong>Warning:</strong> All team data, chat messages, and submissions will be permanently deleted.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="mb-6">
|
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
|
||||||
Type <span className="font-bold text-red-600 dark:text-red-400">{team?.name}</span> to confirm:
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={deleteConfirmText}
|
|
||||||
onChange={(e) => setDeleteConfirmText(e.target.value)}
|
|
||||||
placeholder="Type team name here"
|
|
||||||
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500"
|
|
||||||
autoComplete="off"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex space-x-3">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="secondary"
|
|
||||||
className="flex-1"
|
|
||||||
onClick={() => {
|
|
||||||
setShowDeleteModal(false);
|
|
||||||
setDeleteConfirmText('');
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={handleDeleteTeam}
|
|
||||||
className="flex-1 bg-red-600 hover:bg-red-700"
|
|
||||||
disabled={isDeleting || deleteConfirmText !== team?.name}
|
|
||||||
>
|
|
||||||
{isDeleting ? 'Deleting...' : 'Delete Team'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -60,7 +60,6 @@ const SubmissionViewPage: FC = (): ReactElement => {
|
|||||||
|
|
||||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
{/* Status Banner */}
|
{/* Status Banner */}
|
||||||
{submission.status === 'submitted' ? (
|
|
||||||
<div className="bg-green-50 dark:bg-green-900/20 border border-green-500 rounded-lg p-6 mb-6">
|
<div className="bg-green-50 dark:bg-green-900/20 border border-green-500 rounded-lg p-6 mb-6">
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-3">
|
||||||
<span className="text-4xl">✅</span>
|
<span className="text-4xl">✅</span>
|
||||||
@@ -75,31 +74,6 @@ const SubmissionViewPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : submission.status === 'pending_verification' ? (
|
|
||||||
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-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-yellow-900 dark:text-yellow-100 text-lg">Submission Pending Verification</h3>
|
|
||||||
<p className="text-yellow-700 dark:text-yellow-300 text-sm">
|
|
||||||
Your submission is being processed
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="bg-orange-50 dark:bg-orange-900/20 border border-orange-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-orange-900 dark:text-orange-100 text-lg">Draft Submission</h3>
|
|
||||||
<p className="text-orange-700 dark:text-orange-300 text-sm">
|
|
||||||
This submission is still in draft and has not been finalized
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="bg-white dark:bg-neutral-900 rounded-lg shadow-md dark:shadow-neutral-950/50 overflow-hidden">
|
<div className="bg-white dark:bg-neutral-900 rounded-lg shadow-md dark:shadow-neutral-950/50 overflow-hidden">
|
||||||
{/* Project Header */}
|
{/* Project Header */}
|
||||||
@@ -150,6 +124,21 @@ const SubmissionViewPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Presentation URL */}
|
||||||
|
{submission.presentation_url && (
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-bold text-gray-900 dark:text-white mb-3">Presentation</h3>
|
||||||
|
<a
|
||||||
|
href={submission.presentation_url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="flex items-center space-x-2 text-blue-600 dark:text-primary-400 hover:text-blue-800 dark:hover:text-primary-300"
|
||||||
|
>
|
||||||
|
<span>📊</span>
|
||||||
|
<span className="break-all">{submission.presentation_url}</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Screenshots */}
|
{/* Screenshots */}
|
||||||
@@ -184,18 +173,8 @@ const SubmissionViewPage: FC = (): ReactElement => {
|
|||||||
<div className="grid gap-2 text-sm">
|
<div className="grid gap-2 text-sm">
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-gray-600 dark:text-neutral-400">Status:</span>
|
<span className="text-gray-600 dark:text-neutral-400">Status:</span>
|
||||||
<span className={`font-medium ${
|
<span className="font-medium text-green-600 dark:text-green-400">
|
||||||
submission.status === 'submitted'
|
{submission.status === 'submitted' ? '✓ Submitted' : 'Draft'}
|
||||||
? 'text-green-600 dark:text-green-400'
|
|
||||||
: submission.status === 'pending_verification'
|
|
||||||
? 'text-yellow-600 dark:text-yellow-400'
|
|
||||||
: 'text-orange-600 dark:text-orange-400'
|
|
||||||
}`}>
|
|
||||||
{submission.status === 'submitted'
|
|
||||||
? '✓ Submitted'
|
|
||||||
: submission.status === 'pending_verification'
|
|
||||||
? '⏳ Pending Verification'
|
|
||||||
: '📝 Draft'}
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
|
|||||||
@@ -13,17 +13,12 @@ import {
|
|||||||
useAuthStore,
|
useAuthStore,
|
||||||
} from '@imphnen-frontend-service/service';
|
} from '@imphnen-frontend-service/service';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { toast } from 'sonner';
|
|
||||||
|
|
||||||
const MIN_TEAM_MEMBERS = 2; // Minimum members required to submit (including leader)
|
|
||||||
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
|
|
||||||
|
|
||||||
const SubmitProjectPage: FC = (): ReactElement => {
|
const SubmitProjectPage: FC = (): ReactElement => {
|
||||||
const { teamId } = useParams<{ teamId: string }>();
|
const { teamId } = useParams<{ teamId: string }>();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { session } = useAuthStore();
|
const { session } = useAuthStore();
|
||||||
const [showConfirmModal, setShowConfirmModal] = useState(false);
|
const [showConfirmModal, setShowConfirmModal] = useState(false);
|
||||||
const [confirmText, setConfirmText] = useState('');
|
|
||||||
const [screenshots, setScreenshots] = useState<string[]>([]);
|
const [screenshots, setScreenshots] = useState<string[]>([]);
|
||||||
|
|
||||||
const { data: teamData } = useTeamById(teamId || '');
|
const { data: teamData } = useTeamById(teamId || '');
|
||||||
@@ -36,8 +31,6 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
const currentUserId = session?.user?.id;
|
const currentUserId = session?.user?.id;
|
||||||
const isLeader = currentUserId === team?.leader_id;
|
const isLeader = currentUserId === team?.leader_id;
|
||||||
const hasSubmission = !!submissionData?.data;
|
const hasSubmission = !!submissionData?.data;
|
||||||
const memberCount = team?.members?.length || 0;
|
|
||||||
const hasEnoughMembers = memberCount >= MIN_TEAM_MEMBERS;
|
|
||||||
|
|
||||||
const form = useForm<TProjectSubmissionForm>({
|
const form = useForm<TProjectSubmissionForm>({
|
||||||
resolver: zodResolver(projectSubmissionSchema),
|
resolver: zodResolver(projectSubmissionSchema),
|
||||||
@@ -91,14 +84,6 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
const files = e.target.files;
|
const files = e.target.files;
|
||||||
if (!files) return;
|
if (!files) return;
|
||||||
|
|
||||||
// Validate file sizes
|
|
||||||
const oversizedFiles = Array.from(files).filter(file => file.size > MAX_FILE_SIZE);
|
|
||||||
if (oversizedFiles.length > 0) {
|
|
||||||
toast.error(`${oversizedFiles.length} file(s) are too large. Maximum size is 2MB per file.`);
|
|
||||||
e.target.value = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const uploadPromises = Array.from(files).map((file) => uploadFile(file));
|
const uploadPromises = Array.from(files).map((file) => uploadFile(file));
|
||||||
const results = await Promise.all(uploadPromises);
|
const results = await Promise.all(uploadPromises);
|
||||||
@@ -106,7 +91,6 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
setScreenshots([...screenshots, ...urls]);
|
setScreenshots([...screenshots, ...urls]);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to upload screenshots:', error);
|
console.error('Failed to upload screenshots:', error);
|
||||||
toast.error('Failed to upload screenshots. Please try again.');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -138,25 +122,6 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
{/* Minimum Members Warning */}
|
|
||||||
{!hasEnoughMembers && (
|
|
||||||
<div className="bg-amber-50 dark:bg-amber-900/20 border-2 border-amber-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-amber-900 dark:text-amber-100 text-lg">
|
|
||||||
Team Members Required
|
|
||||||
</h3>
|
|
||||||
<p className="text-amber-800 dark:text-amber-200 mt-2 text-sm font-sans">
|
|
||||||
Your team needs at least <strong>{MIN_TEAM_MEMBERS} members</strong> to submit a project.
|
|
||||||
Currently you have <strong>{memberCount} member{memberCount !== 1 ? 's' : ''}</strong>.
|
|
||||||
Please invite more members to your team before submitting.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Warning Banner */}
|
{/* Warning Banner */}
|
||||||
<div className="bg-red-50 dark:bg-red-900/20 border-2 border-red-500 rounded-lg p-6 mb-6">
|
<div className="bg-red-50 dark:bg-red-900/20 border-2 border-red-500 rounded-lg p-6 mb-6">
|
||||||
<div className="flex items-start space-x-3">
|
<div className="flex items-start space-x-3">
|
||||||
@@ -243,6 +208,16 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
size="lg"
|
size="lg"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* 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"
|
||||||
|
size="lg"
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Screenshots */}
|
{/* Screenshots */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-label1 font-medium text-neutral-800 dark:text-gray-300">
|
<label className="block text-label1 font-medium text-neutral-800 dark:text-gray-300">
|
||||||
@@ -272,7 +247,7 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
Click to upload screenshots
|
Click to upload screenshots
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1 font-sans">
|
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1 font-sans">
|
||||||
PNG, JPG. Max 2MB each
|
PNG, JPG up to 5MB each
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
@@ -299,16 +274,11 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
disabled={!form.formState.isValid || isUploading || !hasEnoughMembers}
|
disabled={!form.formState.isValid || isUploading}
|
||||||
>
|
>
|
||||||
Review & Submit
|
Review & Submit
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{!hasEnoughMembers && (
|
|
||||||
<p className="text-center text-sm text-amber-600 dark:text-amber-400 mt-2">
|
|
||||||
You need at least {MIN_TEAM_MEMBERS} team members to submit
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -328,7 +298,7 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6">
|
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6">
|
||||||
<p className="text-sm text-gray-700 dark:text-gray-300 mb-3">
|
<p className="text-sm text-gray-700 dark:text-gray-300 mb-3">
|
||||||
By submitting, you confirm that:
|
By clicking "Submit Project", you confirm that:
|
||||||
</p>
|
</p>
|
||||||
<ul className="text-sm text-gray-600 dark:text-gray-400 space-y-2">
|
<ul className="text-sm text-gray-600 dark:text-gray-400 space-y-2">
|
||||||
<li>✓ All information is correct and complete</li>
|
<li>✓ All information is correct and complete</li>
|
||||||
@@ -337,35 +307,19 @@ const SubmitProjectPage: FC = (): ReactElement => {
|
|||||||
<li>✓ Your team agrees with this submission</li>
|
<li>✓ Your team agrees with this submission</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<div className="mb-6">
|
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
|
||||||
Type <span className="font-bold text-red-600 dark:text-red-400">SUBMIT</span> to confirm:
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={confirmText}
|
|
||||||
onChange={(e) => setConfirmText(e.target.value)}
|
|
||||||
placeholder="Type SUBMIT here"
|
|
||||||
className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-500"
|
|
||||||
autoComplete="off"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex space-x-3">
|
<div className="flex space-x-3">
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
onClick={() => {
|
onClick={() => setShowConfirmModal(false)}
|
||||||
setShowConfirmModal(false);
|
|
||||||
setConfirmText('');
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
Go Back
|
Go Back
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={onSubmit}
|
onClick={onSubmit}
|
||||||
className="flex-1 bg-red-600 hover:bg-red-700"
|
className="flex-1 bg-red-600 hover:bg-red-700"
|
||||||
disabled={isSubmitting || confirmText !== 'SUBMIT'}
|
disabled={isSubmitting}
|
||||||
>
|
>
|
||||||
{isSubmitting ? 'Submitting...' : 'Submit Project'}
|
{isSubmitting ? 'Submitting...' : 'Submit Project'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { FC, ReactElement, useState, useEffect, useCallback } from 'react';
|
import { FC, ReactElement, useState, useEffect } from 'react';
|
||||||
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
import { Button } from '@imphnen-frontend-service/ui/atoms';
|
||||||
import { Link, useNavigate, useSearchParams } from 'react-router';
|
import { Link, useNavigate } from 'react-router';
|
||||||
import {
|
import {
|
||||||
useTeams,
|
useTeams,
|
||||||
useJoinTeam,
|
useJoinTeam,
|
||||||
@@ -14,193 +14,26 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
|||||||
import { CitySelect } from '../../../components/city-select';
|
import { CitySelect } from '../../../components/city-select';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
|
|
||||||
const DEFAULT_PER_PAGE = 12;
|
|
||||||
const PER_PAGE_OPTIONS = [6, 12, 24, 48];
|
|
||||||
|
|
||||||
// Team features deadline: 2025-11-30 23:59:00 WIB (UTC+7)
|
|
||||||
const TEAM_FEATURES_DEADLINE = new Date('2025-11-30T16:59:00Z');
|
|
||||||
|
|
||||||
// Member filter options
|
|
||||||
const MEMBER_FILTER_OPTIONS = [
|
|
||||||
{ label: 'All Teams', value: '', minMembers: undefined, maxMembers: undefined },
|
|
||||||
{ label: 'Looking for Members (1-4)', value: 'looking', minMembers: 1, maxMembers: 4 },
|
|
||||||
{ label: '1 Member', value: '1', minMembers: 1, maxMembers: 1 },
|
|
||||||
{ label: '2 Members', value: '2', minMembers: 2, maxMembers: 2 },
|
|
||||||
{ label: '3 Members', value: '3', minMembers: 3, maxMembers: 3 },
|
|
||||||
{ label: '4 Members', value: '4', minMembers: 4, maxMembers: 4 },
|
|
||||||
{ label: '5 Members (Full)', value: '5', minMembers: 5, maxMembers: 5 },
|
|
||||||
];
|
|
||||||
|
|
||||||
// Submission status filter options
|
|
||||||
const SUBMISSION_FILTER_OPTIONS = [
|
|
||||||
{ label: 'All Teams', value: '' },
|
|
||||||
{ label: 'Submitted', value: 'true' },
|
|
||||||
{ label: 'Not Submitted', value: 'false' },
|
|
||||||
];
|
|
||||||
|
|
||||||
// Skeleton card component for loading state
|
|
||||||
const TeamCardSkeleton: FC = () => (
|
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md overflow-hidden flex flex-col border dark:border-gray-800 animate-pulse">
|
|
||||||
<div className="w-full aspect-3/1 bg-gray-200 dark:bg-gray-700" />
|
|
||||||
<div className="p-6 flex flex-col flex-1">
|
|
||||||
<div className="flex items-center space-x-3 mb-3">
|
|
||||||
<div className="w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700" />
|
|
||||||
<div className="flex-1">
|
|
||||||
<div className="h-5 w-32 bg-gray-200 dark:bg-gray-700 rounded mb-2" />
|
|
||||||
<div className="h-4 w-48 bg-gray-200 dark:bg-gray-700 rounded" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 mb-4 flex-1">
|
|
||||||
<div className="h-4 w-full bg-gray-200 dark:bg-gray-700 rounded" />
|
|
||||||
<div className="h-4 w-5/6 bg-gray-200 dark:bg-gray-700 rounded" />
|
|
||||||
<div className="h-4 w-4/6 bg-gray-200 dark:bg-gray-700 rounded" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-3 mt-auto">
|
|
||||||
<div className="h-10 w-full bg-gray-200 dark:bg-gray-700 rounded" />
|
|
||||||
<div className="h-10 w-full bg-gray-200 dark:bg-gray-700 rounded" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
const BrowseTeamsPage: FC = (): ReactElement => {
|
const BrowseTeamsPage: FC = (): ReactElement => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
|
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||||
// Check if team features are closed
|
const [selectedCity, setSelectedCity] = useState('');
|
||||||
const isTeamFeaturesClosed = new Date() >= TEAM_FEATURES_DEADLINE;
|
|
||||||
|
|
||||||
// Initialize state from URL params
|
|
||||||
const initialPage = parseInt(searchParams.get('page') || '1', 10);
|
|
||||||
const initialPerPage = parseInt(
|
|
||||||
searchParams.get('per_page') || String(DEFAULT_PER_PAGE),
|
|
||||||
10
|
|
||||||
);
|
|
||||||
const initialSearch = searchParams.get('search') || '';
|
|
||||||
const initialCity = searchParams.get('city') || '';
|
|
||||||
const initialMembers = searchParams.get('members') || '';
|
|
||||||
const initialSubmission = searchParams.get('submission') || '';
|
|
||||||
|
|
||||||
const [searchTerm, setSearchTerm] = useState(initialSearch);
|
|
||||||
const [debouncedSearch, setDebouncedSearch] = useState(initialSearch);
|
|
||||||
const [selectedCity, setSelectedCity] = useState(initialCity);
|
|
||||||
const [selectedMembers, setSelectedMembers] = useState(initialMembers);
|
|
||||||
const [selectedSubmission, setSelectedSubmission] = useState(initialSubmission);
|
|
||||||
const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
|
const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
|
||||||
const [showJoinModal, setShowJoinModal] = useState(false);
|
const [showJoinModal, setShowJoinModal] = useState(false);
|
||||||
const [currentPage, setCurrentPage] = useState(
|
|
||||||
PER_PAGE_OPTIONS.includes(initialPerPage) ? initialPage : 1
|
|
||||||
);
|
|
||||||
const [perPage, setPerPage] = useState(
|
|
||||||
PER_PAGE_OPTIONS.includes(initialPerPage) ? initialPerPage : DEFAULT_PER_PAGE
|
|
||||||
);
|
|
||||||
|
|
||||||
// Update URL when pagination state changes
|
// Debounce search term
|
||||||
const updateUrlParams = useCallback(
|
|
||||||
(params: {
|
|
||||||
page?: number;
|
|
||||||
per_page?: number;
|
|
||||||
search?: string;
|
|
||||||
city?: string;
|
|
||||||
members?: string;
|
|
||||||
submission?: string;
|
|
||||||
}) => {
|
|
||||||
const newParams = new URLSearchParams(searchParams);
|
|
||||||
|
|
||||||
if (params.page !== undefined) {
|
|
||||||
if (params.page === 1) {
|
|
||||||
newParams.delete('page');
|
|
||||||
} else {
|
|
||||||
newParams.set('page', String(params.page));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.per_page !== undefined) {
|
|
||||||
if (params.per_page === DEFAULT_PER_PAGE) {
|
|
||||||
newParams.delete('per_page');
|
|
||||||
} else {
|
|
||||||
newParams.set('per_page', String(params.per_page));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.search !== undefined) {
|
|
||||||
if (params.search === '') {
|
|
||||||
newParams.delete('search');
|
|
||||||
} else {
|
|
||||||
newParams.set('search', params.search);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.city !== undefined) {
|
|
||||||
if (params.city === '') {
|
|
||||||
newParams.delete('city');
|
|
||||||
} else {
|
|
||||||
newParams.set('city', params.city);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.members !== undefined) {
|
|
||||||
if (params.members === '') {
|
|
||||||
newParams.delete('members');
|
|
||||||
} else {
|
|
||||||
newParams.set('members', params.members);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (params.submission !== undefined) {
|
|
||||||
if (params.submission === '') {
|
|
||||||
newParams.delete('submission');
|
|
||||||
} else {
|
|
||||||
newParams.set('submission', params.submission);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setSearchParams(newParams, { replace: true });
|
|
||||||
},
|
|
||||||
[searchParams, setSearchParams]
|
|
||||||
);
|
|
||||||
|
|
||||||
// Debounce search term and reset page
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
setDebouncedSearch(searchTerm);
|
setDebouncedSearch(searchTerm);
|
||||||
if (searchTerm !== debouncedSearch) {
|
|
||||||
setCurrentPage(1);
|
|
||||||
updateUrlParams({ search: searchTerm, page: 1 });
|
|
||||||
}
|
|
||||||
}, 300);
|
}, 300);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, [searchTerm]);
|
}, [searchTerm]);
|
||||||
|
|
||||||
// Update URL when city filter changes
|
const { data: teamsData, isLoading } = useTeams({
|
||||||
useEffect(() => {
|
|
||||||
if (selectedCity !== initialCity) {
|
|
||||||
setCurrentPage(1);
|
|
||||||
updateUrlParams({ city: selectedCity, page: 1 });
|
|
||||||
}
|
|
||||||
}, [selectedCity]);
|
|
||||||
|
|
||||||
// Get member filter values
|
|
||||||
const memberFilter = MEMBER_FILTER_OPTIONS.find(
|
|
||||||
(opt) => opt.value === selectedMembers
|
|
||||||
);
|
|
||||||
|
|
||||||
// Convert submission filter value to boolean
|
|
||||||
const hasSubmissionFilter = selectedSubmission === 'true' ? true : selectedSubmission === 'false' ? false : undefined;
|
|
||||||
|
|
||||||
const {
|
|
||||||
data: teamsData,
|
|
||||||
isLoading,
|
|
||||||
isFetching,
|
|
||||||
} = useTeams({
|
|
||||||
page: currentPage,
|
|
||||||
limit: perPage,
|
|
||||||
search: debouncedSearch,
|
search: debouncedSearch,
|
||||||
city: selectedCity || undefined,
|
city: selectedCity || undefined,
|
||||||
visibility: ETeamVisibility.PUBLIC,
|
visibility: ETeamVisibility.PUBLIC,
|
||||||
minMembers: memberFilter?.minMembers,
|
|
||||||
maxMembers: memberFilter?.maxMembers,
|
|
||||||
hasSubmission: hasSubmissionFilter,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: myTeamsData } = useMyTeams();
|
const { data: myTeamsData } = useMyTeams();
|
||||||
@@ -211,9 +44,7 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
mode: 'all',
|
mode: 'all',
|
||||||
});
|
});
|
||||||
|
|
||||||
const teams = teamsData?.teams || [];
|
const teams = teamsData?.data || [];
|
||||||
const totalPages = teamsData?.totalPages || 1;
|
|
||||||
const total = teamsData?.total || 0;
|
|
||||||
const myTeams = myTeamsData?.data || [];
|
const myTeams = myTeamsData?.data || [];
|
||||||
|
|
||||||
// Helper function to check if user is a member of a team
|
// Helper function to check if user is a member of a team
|
||||||
@@ -239,43 +70,6 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Generate page numbers to display
|
|
||||||
const getPageNumbers = () => {
|
|
||||||
const pages: (number | string)[] = [];
|
|
||||||
const maxVisible = 5;
|
|
||||||
|
|
||||||
if (totalPages <= maxVisible + 2) {
|
|
||||||
// Show all pages if total is small
|
|
||||||
for (let i = 1; i <= totalPages; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Always show first page
|
|
||||||
pages.push(1);
|
|
||||||
|
|
||||||
if (currentPage > 3) {
|
|
||||||
pages.push('...');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show pages around current
|
|
||||||
const start = Math.max(2, currentPage - 1);
|
|
||||||
const end = Math.min(totalPages - 1, currentPage + 1);
|
|
||||||
|
|
||||||
for (let i = start; i <= end; i++) {
|
|
||||||
pages.push(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (currentPage < totalPages - 2) {
|
|
||||||
pages.push('...');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Always show last page
|
|
||||||
pages.push(totalPages);
|
|
||||||
}
|
|
||||||
|
|
||||||
return pages;
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
|
<div className="min-h-screen bg-gray-50 dark:bg-gray-950">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -300,7 +94,7 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
{/* Filters */}
|
{/* Filters */}
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
|
||||||
<div className="bg-white dark:bg-gray-900 p-6 rounded-lg shadow-sm mb-6 border dark:border-gray-800">
|
<div className="bg-white dark:bg-gray-900 p-6 rounded-lg shadow-sm mb-6 border dark:border-gray-800">
|
||||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||||
Search Teams
|
Search Teams
|
||||||
@@ -323,63 +117,13 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
placeholder="All Cities (search to filter...)"
|
placeholder="All Cities (search to filter...)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
|
||||||
Filter by Members
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={selectedMembers}
|
|
||||||
onChange={(e) => {
|
|
||||||
setSelectedMembers(e.target.value);
|
|
||||||
setCurrentPage(1);
|
|
||||||
updateUrlParams({ members: e.target.value, page: 1 });
|
|
||||||
}}
|
|
||||||
className="w-full h-[42px] px-3 border border-gray-300 dark:border-gray-700 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
|
|
||||||
>
|
|
||||||
{MEMBER_FILTER_OPTIONS.map((option) => (
|
|
||||||
<option key={option.value} value={option.value}>
|
|
||||||
{option.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
|
||||||
Submission Status
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={selectedSubmission}
|
|
||||||
onChange={(e) => {
|
|
||||||
setSelectedSubmission(e.target.value);
|
|
||||||
setCurrentPage(1);
|
|
||||||
updateUrlParams({ submission: e.target.value, page: 1 });
|
|
||||||
}}
|
|
||||||
className="w-full h-[42px] px-3 border border-gray-300 dark:border-gray-700 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
|
|
||||||
>
|
|
||||||
{SUBMISSION_FILTER_OPTIONS.map((option) => (
|
|
||||||
<option key={option.value} value={option.value}>
|
|
||||||
{option.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Teams Count */}
|
|
||||||
{!isLoading && total > 0 && (
|
|
||||||
<div className="mb-4 text-sm text-gray-600 dark:text-gray-400">
|
|
||||||
Showing {(currentPage - 1) * perPage + 1}-
|
|
||||||
{Math.min(currentPage * perPage, total)} of {total} teams
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Teams List */}
|
{/* Teams List */}
|
||||||
{isLoading || isFetching ? (
|
{isLoading ? (
|
||||||
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
|
<div className="text-center py-12">
|
||||||
{Array.from({ length: perPage }).map((_, index) => (
|
<p className="text-gray-600 dark:text-gray-400">Loading teams...</p>
|
||||||
<TeamCardSkeleton key={index} />
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
) : teams.length === 0 ? (
|
) : teams.length === 0 ? (
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-sm p-12 text-center">
|
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-sm p-12 text-center">
|
||||||
@@ -391,9 +135,8 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<>
|
|
||||||
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
|
<div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
|
||||||
{teams.map((team: any) => (
|
{teams.map((team) => (
|
||||||
<div
|
<div
|
||||||
key={team.id}
|
key={team.id}
|
||||||
className="bg-white dark:bg-gray-900 rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow flex flex-col border dark:border-gray-800"
|
className="bg-white dark:bg-gray-900 rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow flex flex-col border dark:border-gray-800"
|
||||||
@@ -419,39 +162,25 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<h3 className="text-lg font-bold text-gray-900 dark:text-white line-clamp-1 leading-tight">
|
<h3 className="text-lg font-bold text-gray-900 dark:text-white line-clamp-2 leading-tight">
|
||||||
{team.name}
|
{team.name}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="text-sm font-sans text-gray-600 dark:text-gray-400 flex items-center gap-2 mt-1">
|
<div className="text-sm font-sans text-gray-600 dark:text-gray-400 flex gap-2">
|
||||||
{team.has_submission && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 shrink-0">
|
|
||||||
<Icon icon="mdi:check-circle" className="text-sm" />
|
|
||||||
Submitted
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<p className="truncate flex-1 min-w-0 flex items-center gap-x-1">
|
<p className="truncate flex-1 min-w-0 flex items-center gap-x-1">
|
||||||
<Icon icon="mdi:map-marker" />{' '}
|
<Icon icon="mdi:map-marker" />{' '}
|
||||||
<span>{team.city}</span>
|
<span>{team.city}</span>
|
||||||
</p>
|
</p>
|
||||||
<p className="whitespace-nowrap shrink-0 flex items-center gap-x-1">
|
<p className="whitespace-nowrap shrink-0 flex items-center gap-x-1">
|
||||||
<Icon icon="mdi:account-group" />{' '}
|
<Icon icon="mdi:account-group" />{' '}
|
||||||
{team.member_count || 0} members
|
{team.members?.length || 0} members
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-gray-600 dark:text-gray-300 text-sm mb-4 line-clamp-3 font-sans flex-1">
|
<p className="text-gray-600 dark:text-gray-300 text-sm mb-4 line-clamp-3 font-sans">
|
||||||
{team.description}
|
{team.description}
|
||||||
</p>
|
</p>
|
||||||
<div className="space-y-3 mt-auto">
|
<div className="space-y-3 mt-auto">
|
||||||
{(team.member_count || 0) === 1 && !team.has_submission && (
|
|
||||||
<div className="p-2 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
|
|
||||||
<p className="text-xs text-amber-700 dark:text-amber-400 flex items-center gap-1">
|
|
||||||
<Icon icon="mdi:alert" className="text-sm shrink-0" />
|
|
||||||
<span>This team needs at least 2 members to submit</span>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{isMyTeam(team.id) ? (
|
{isMyTeam(team.id) ? (
|
||||||
<Button
|
<Button
|
||||||
className="w-full"
|
className="w-full"
|
||||||
@@ -463,9 +192,7 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{myTeams.length === 0 &&
|
{myTeams.length === 0 &&
|
||||||
(team.member_count || 0) < 5 &&
|
(team.members?.length || 0) < 5 && (
|
||||||
!team.has_submission &&
|
|
||||||
!isTeamFeaturesClosed && (
|
|
||||||
<Button
|
<Button
|
||||||
className="w-full"
|
className="w-full"
|
||||||
onClick={() => handleJoinRequest(team.id)}
|
onClick={() => handleJoinRequest(team.id)}
|
||||||
@@ -487,99 +214,6 @@ const BrowseTeamsPage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Pagination */}
|
|
||||||
{(totalPages > 1 || total > 6) && (
|
|
||||||
<div className="mt-8 flex flex-col sm:flex-row items-center justify-center gap-4">
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
onClick={() => {
|
|
||||||
const newPage = Math.max(1, currentPage - 1);
|
|
||||||
setCurrentPage(newPage);
|
|
||||||
updateUrlParams({ page: newPage });
|
|
||||||
}}
|
|
||||||
disabled={currentPage === 1 || isFetching}
|
|
||||||
className="px-3"
|
|
||||||
>
|
|
||||||
<Icon icon="mdi:chevron-left" className="text-xl" />
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-1">
|
|
||||||
{getPageNumbers().map((page, index) =>
|
|
||||||
typeof page === 'string' ? (
|
|
||||||
<span
|
|
||||||
key={`ellipsis-${index}`}
|
|
||||||
className="px-2 text-gray-400 dark:text-gray-500"
|
|
||||||
>
|
|
||||||
...
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
key={page}
|
|
||||||
onClick={() => {
|
|
||||||
setCurrentPage(page);
|
|
||||||
updateUrlParams({ page });
|
|
||||||
}}
|
|
||||||
disabled={isFetching}
|
|
||||||
className={`min-w-10 h-10 px-3 rounded-md text-sm font-medium transition-colors ${
|
|
||||||
currentPage === page
|
|
||||||
? 'bg-blue-600 text-white'
|
|
||||||
: 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 border border-gray-300 dark:border-gray-600'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{page}
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
onClick={() => {
|
|
||||||
const newPage = Math.min(totalPages, currentPage + 1);
|
|
||||||
setCurrentPage(newPage);
|
|
||||||
updateUrlParams({ page: newPage });
|
|
||||||
}}
|
|
||||||
disabled={currentPage === totalPages || isFetching}
|
|
||||||
className="px-3"
|
|
||||||
>
|
|
||||||
<Icon icon="mdi:chevron-right" className="text-xl" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<span className="text-sm text-gray-500 dark:text-gray-400">
|
|
||||||
Page {currentPage} of {totalPages}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm text-gray-500 dark:text-gray-400">Show:</span>
|
|
||||||
<select
|
|
||||||
value={perPage}
|
|
||||||
onChange={(e) => {
|
|
||||||
const newPerPage = Number(e.target.value);
|
|
||||||
setPerPage(newPerPage);
|
|
||||||
setCurrentPage(1);
|
|
||||||
updateUrlParams({ per_page: newPerPage, page: 1 });
|
|
||||||
}}
|
|
||||||
className="h-10 px-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
|
||||||
>
|
|
||||||
{PER_PAGE_OPTIONS.map((option) => (
|
|
||||||
<option key={option} value={option}>
|
|
||||||
{option}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -5,22 +5,11 @@ import { useNavigate } from 'react-router';
|
|||||||
import { useForm, Controller } from 'react-hook-form';
|
import { useForm, Controller } from 'react-hook-form';
|
||||||
import { teamCreateSchema, TTeamCreateForm, useCreateTeam, ETeamVisibility, useUploadFile } from '@imphnen-frontend-service/service';
|
import { teamCreateSchema, TTeamCreateForm, useCreateTeam, ETeamVisibility, useUploadFile } from '@imphnen-frontend-service/service';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { toast } from 'sonner';
|
|
||||||
import { Icon } from '@iconify/react';
|
|
||||||
|
|
||||||
import { CitySelect } from '../../../components/city-select';
|
import { CitySelect } from '../../../components/city-select';
|
||||||
|
|
||||||
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
|
|
||||||
|
|
||||||
// Team features deadline: 2025-11-30 23:59:00 WIB (UTC+7)
|
|
||||||
const TEAM_FEATURES_DEADLINE = new Date('2025-11-30T16:59:00Z');
|
|
||||||
|
|
||||||
const CreateTeamPage: FC = (): ReactElement => {
|
const CreateTeamPage: FC = (): ReactElement => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
// Check if team features are closed
|
|
||||||
const isTeamFeaturesClosed = new Date() >= TEAM_FEATURES_DEADLINE;
|
|
||||||
|
|
||||||
const [logoFile, setLogoFile] = useState<File | null>(null);
|
const [logoFile, setLogoFile] = useState<File | null>(null);
|
||||||
const [logoPreview, setLogoPreview] = useState<string>('');
|
const [logoPreview, setLogoPreview] = useState<string>('');
|
||||||
const [bannerFile, setBannerFile] = useState<File | null>(null);
|
const [bannerFile, setBannerFile] = useState<File | null>(null);
|
||||||
@@ -42,11 +31,6 @@ const CreateTeamPage: FC = (): ReactElement => {
|
|||||||
const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file) {
|
if (file) {
|
||||||
if (file.size > MAX_FILE_SIZE) {
|
|
||||||
toast.error('Logo image is too large. Maximum size is 2MB.');
|
|
||||||
e.target.value = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setLogoFile(file);
|
setLogoFile(file);
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onloadend = () => {
|
reader.onloadend = () => {
|
||||||
@@ -59,11 +43,6 @@ const CreateTeamPage: FC = (): ReactElement => {
|
|||||||
const handleBannerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleBannerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (file) {
|
if (file) {
|
||||||
if (file.size > MAX_FILE_SIZE) {
|
|
||||||
toast.error('Banner image is too large. Maximum size is 2MB.');
|
|
||||||
e.target.value = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setBannerFile(file);
|
setBannerFile(file);
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onloadend = () => {
|
reader.onloadend = () => {
|
||||||
@@ -94,67 +73,12 @@ const CreateTeamPage: FC = (): ReactElement => {
|
|||||||
banner: bannerUrl,
|
banner: bannerUrl,
|
||||||
});
|
});
|
||||||
|
|
||||||
toast.success('Team created successfully!');
|
|
||||||
navigate(`/teams/${result.data.id}`);
|
navigate(`/teams/${result.data.id}`);
|
||||||
} catch (error: any) {
|
} catch (error) {
|
||||||
console.error('Failed to create team:', error);
|
console.error('Failed to create team:', error);
|
||||||
|
|
||||||
// Handle specific error messages
|
|
||||||
const message = error?.message || '';
|
|
||||||
if (message.includes('413') || message.includes('length limit') || message.includes('too large')) {
|
|
||||||
toast.error('Image file is too large. Please use smaller images (max 2MB each).');
|
|
||||||
} else if (message.includes('already a member')) {
|
|
||||||
toast.error(message);
|
|
||||||
} else {
|
|
||||||
toast.error(message || 'Failed to create team. Please try again.');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Show closed screen if team features are closed
|
|
||||||
if (isTeamFeaturesClosed) {
|
|
||||||
return (
|
|
||||||
<div className="flex justify-center items-center min-h-screen bg-gray-50 dark:bg-gray-950 p-4">
|
|
||||||
<div className="bg-white dark:bg-gray-900 w-full max-w-md p-8 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 text-center">
|
|
||||||
<div className="mb-6">
|
|
||||||
<div className="mx-auto w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-4">
|
|
||||||
<Icon
|
|
||||||
icon="mdi:clock-alert"
|
|
||||||
className="text-3xl text-red-600 dark:text-red-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
|
|
||||||
Team Features Closed
|
|
||||||
</h2>
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
|
||||||
Team creation is no longer available.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
|
||||||
The deadline for team features was November 30, 2025 at 23:59 WIB.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => navigate('/dashboard')}
|
|
||||||
className="w-full py-3 bg-primary-600 text-white rounded-lg font-semibold hover:bg-primary-700 transition-colors cursor-pointer"
|
|
||||||
>
|
|
||||||
Back to Dashboard
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => navigate('/teams/browse')}
|
|
||||||
className="w-full py-3 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors cursor-pointer"
|
|
||||||
>
|
|
||||||
Browse Teams
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-neutral-950">
|
<div className="min-h-screen bg-gray-50 dark:bg-neutral-950">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -195,7 +119,7 @@ const CreateTeamPage: FC = (): ReactElement => {
|
|||||||
<label className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 dark:border-neutral-600 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-neutral-800">
|
<label className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 dark:border-neutral-600 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-neutral-800">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<p className="text-gray-500 dark:text-neutral-400">Click to upload banner</p>
|
<p className="text-gray-500 dark:text-neutral-400">Click to upload banner</p>
|
||||||
<p className="text-xs text-gray-400 dark:text-neutral-500 mt-1">1200x400 recommended. Max 2MB</p>
|
<p className="text-xs text-gray-400 dark:text-neutral-500 mt-1">1200x400 recommended</p>
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
@@ -224,7 +148,6 @@ const CreateTeamPage: FC = (): ReactElement => {
|
|||||||
<span className="text-gray-400 dark:text-neutral-500 text-3xl">👥</span>
|
<span className="text-gray-400 dark:text-neutral-500 text-3xl">👥</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div>
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="logo" className="cursor-pointer">
|
<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">
|
<span className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 inline-block">
|
||||||
@@ -251,8 +174,6 @@ const CreateTeamPage: FC = (): ReactElement => {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-gray-400 dark:text-neutral-500 mt-2">Max 2MB</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -124,62 +124,60 @@ const UserProfilePage: FC = (): ReactElement => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Team Section */}
|
{/* Teams Section */}
|
||||||
{userTeams.length > 0 ? (
|
{userTeams.length > 0 ? (
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md dark:shadow-gray-950/50 p-4 md:p-6">
|
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md dark:shadow-gray-950/50 p-4 md:p-6">
|
||||||
<h2 className="text-lg md:text-xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
<h2 className="text-lg md:text-xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
||||||
Team
|
Teams ({userTeams.length})
|
||||||
</h2>
|
</h2>
|
||||||
<div className="space-y-4">
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
{userTeams.map((team: any) => (
|
{userTeams.map((team: any) => (
|
||||||
<Link
|
<Link
|
||||||
key={team.id}
|
key={team.id}
|
||||||
to={'/teams/' + team.id}
|
to={'/teams/' + team.id}
|
||||||
className="block bg-white dark:bg-gray-800 rounded-lg shadow-md dark:shadow-gray-950/50 overflow-hidden hover:shadow-lg transition-shadow border dark:border-gray-700"
|
className="bg-white dark:bg-gray-800 rounded-lg shadow-md dark:shadow-gray-950/50 overflow-hidden hover:shadow-lg transition-shadow"
|
||||||
>
|
>
|
||||||
|
<div className="w-full aspect-3/1">
|
||||||
<img
|
<img
|
||||||
src={team.banner || '/images/banner-imphnen.webp'}
|
src={team.banner}
|
||||||
alt={team.name}
|
alt={team.name}
|
||||||
className="w-full aspect-3/1 object-cover"
|
className="w-full h-full object-cover"
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
<div className="p-4">
|
<div className="p-4">
|
||||||
<div className="flex items-center space-x-3 mb-3">
|
<div className="flex items-center space-x-3 mb-2">
|
||||||
{team.logo ? (
|
{team.logo && (
|
||||||
<img
|
<img
|
||||||
src={team.logo}
|
src={team.logo}
|
||||||
alt={team.name}
|
alt={team.name}
|
||||||
className="w-12 h-12 rounded-full object-cover"
|
className="w-12 h-12 rounded-full object-cover"
|
||||||
/>
|
/>
|
||||||
) : (
|
|
||||||
<div className="w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
|
|
||||||
<Icon icon="mdi:account-group" className="text-gray-500 dark:text-gray-400 text-xl" />
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<h3 className="font-bold text-gray-900 dark:text-white line-clamp-1 text-lg">
|
<h3 className="font-bold text-gray-900 dark:text-white line-clamp-2 mb-1">
|
||||||
{team.name}
|
{team.name}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="text-sm text-gray-600 dark:text-gray-400 flex items-center gap-3 font-sans mt-1">
|
<div className="text-sm text-gray-600 dark:text-gray-400 flex gap-2 font-sans">
|
||||||
{team.has_submission && (
|
<p className="truncate flex-1 min-w-0">
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 shrink-0">
|
<Icon
|
||||||
<Icon icon="mdi:check-circle" className="text-sm" />
|
icon="mdi:map-marker"
|
||||||
Submitted
|
className="inline-block w-4 h-4 mr-1"
|
||||||
</span>
|
/>
|
||||||
)}
|
{team.city}
|
||||||
{team.city && (
|
</p>
|
||||||
<span className="flex items-center gap-1 truncate">
|
<p className="whitespace-nowrap shrink-0">
|
||||||
<Icon icon="mdi:map-marker" className="shrink-0" />
|
<Icon
|
||||||
<span className="truncate">{team.city}</span>
|
icon="mdi:account-group"
|
||||||
</span>
|
className="inline-block w-4 h-4 mr-1"
|
||||||
)}
|
/>
|
||||||
|
{team.members?.length || 0} members
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{team.description && (
|
<p className="text-gray-600 dark:text-gray-400 text-base line-clamp-2 font-sans">
|
||||||
<p className="text-gray-600 dark:text-gray-400 text-sm line-clamp-2 font-sans">
|
|
||||||
{team.description}
|
{team.description}
|
||||||
</p>
|
</p>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
@@ -188,12 +186,10 @@ const UserProfilePage: FC = (): ReactElement => {
|
|||||||
) : (
|
) : (
|
||||||
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md dark:shadow-gray-950/50 p-4 md:p-6">
|
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-md dark:shadow-gray-950/50 p-4 md:p-6">
|
||||||
<h2 className="text-lg md:text-xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
<h2 className="text-lg md:text-xl font-bold text-gray-900 dark:text-white mb-3 md:mb-4">
|
||||||
Team
|
Teams
|
||||||
</h2>
|
</h2>
|
||||||
<div className="text-center py-8">
|
<div className="text-center py-8">
|
||||||
<div className="text-4xl mb-3">
|
<div className="text-4xl mb-3">👥</div>
|
||||||
<Icon icon="mdi:account-group-outline" className="inline-block text-gray-400" />
|
|
||||||
</div>
|
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
<p className="text-gray-600 dark:text-gray-400">
|
||||||
Not in any team yet
|
Not in any team yet
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Link, useLocation } from 'react-router';
|
|||||||
import {
|
import {
|
||||||
useMyTeams,
|
useMyTeams,
|
||||||
useAuthStore,
|
useAuthStore,
|
||||||
|
supabase,
|
||||||
} from '@imphnen-frontend-service/service';
|
} from '@imphnen-frontend-service/service';
|
||||||
import { useNavigate } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
@@ -39,11 +40,19 @@ export const Sidebar: FC<SidebarProps> = ({ isOpen = true, onClose }) => {
|
|||||||
}
|
}
|
||||||
}, [location.pathname]);
|
}, [location.pathname]);
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = async () => {
|
||||||
|
try {
|
||||||
|
await supabase.auth.signOut();
|
||||||
clearSession();
|
clearSession();
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
toast.success('Logged out successfully');
|
toast.success('Logged out successfully');
|
||||||
navigate('/auth/login');
|
navigate('/auth/login');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Logout error:', error);
|
||||||
|
clearSession();
|
||||||
|
localStorage.clear();
|
||||||
|
navigate('/auth/login');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const navItems: NavItem[] = [
|
const navItems: NavItem[] = [
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { SessionUser } from '@imphnen-frontend-service/utils';
|
import { SessionUser } from '@imphnen-frontend-service/utils';
|
||||||
import { hackathonApi, SessionToken } from '@imphnen-frontend-service/service';
|
import { supabase } from '@imphnen-frontend-service/service';
|
||||||
import { LoaderFunctionArgs, redirect } from 'react-router';
|
import { LoaderFunctionArgs, redirect } from 'react-router';
|
||||||
|
|
||||||
const mappingPublicRoutes = [
|
const mappingPublicRoutes = [
|
||||||
@@ -37,10 +37,14 @@ export const middleware = async ({ request }: LoaderFunctionArgs) => {
|
|||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
const pathname = url.pathname;
|
const pathname = url.pathname;
|
||||||
|
|
||||||
// Get token from cookies and user from local storage
|
// Get session from Supabase (authoritative source)
|
||||||
const tokenData = SessionToken.get();
|
const { data: { session: supabaseSession }, error: sessionError } = await supabase.auth.getSession();
|
||||||
const user = SessionUser.get();
|
|
||||||
const isAuthenticated = !!tokenData?.token?.access_token;
|
// 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
|
// Allow to access the hackathon pages without authentication
|
||||||
if (mappingPublicPrefixRoutes.some((prefix) => pathname.startsWith(prefix))) {
|
if (mappingPublicPrefixRoutes.some((prefix) => pathname.startsWith(prefix))) {
|
||||||
@@ -59,24 +63,20 @@ export const middleware = async ({ request }: LoaderFunctionArgs) => {
|
|||||||
|
|
||||||
// Auth routes (all /auth/* paths) - redirect to dashboard if already authenticated
|
// Auth routes (all /auth/* paths) - redirect to dashboard if already authenticated
|
||||||
if (pathname.startsWith('/auth')) {
|
if (pathname.startsWith('/auth')) {
|
||||||
if (isAuthenticated) return redirect('/dashboard');
|
if (supabaseSession) return redirect('/dashboard');
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Require authentication for all other routes
|
// Require authentication for all other routes - ONLY check Supabase session
|
||||||
if (!isAuthenticated) {
|
if (!supabaseSession) {
|
||||||
return redirect('/auth/login');
|
return redirect('/auth/login');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user has completed onboarding
|
// Check if user has completed onboarding by querying database (not localStorage!)
|
||||||
// Skip onboarding check for onboarding routes themselves
|
// Skip onboarding check for onboarding routes themselves
|
||||||
if (!mappingOnboardingRoutes.includes(pathname)) {
|
if (!mappingOnboardingRoutes.includes(pathname)) {
|
||||||
try {
|
try {
|
||||||
const userId = user?.id;
|
const userId = supabaseSession.user.id;
|
||||||
if (!userId) {
|
|
||||||
return redirect('/auth/login');
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
// Check cache first
|
// Check cache first
|
||||||
@@ -86,20 +86,20 @@ export const middleware = async ({ request }: LoaderFunctionArgs) => {
|
|||||||
if (cached && (now - cached.timestamp) < CACHE_DURATION) {
|
if (cached && (now - cached.timestamp) < CACHE_DURATION) {
|
||||||
hasLocation = cached.hasLocation;
|
hasLocation = cached.hasLocation;
|
||||||
} else {
|
} else {
|
||||||
// First check user data (faster)
|
const { data: userData, error: userError } = await supabase
|
||||||
if (user?.location) {
|
.from('users')
|
||||||
hasLocation = true;
|
.select('location')
|
||||||
} else {
|
.eq('id', userId)
|
||||||
// Fetch from backend API
|
.single();
|
||||||
try {
|
|
||||||
const response = await hackathonApi.get('/users/me');
|
if (userError) {
|
||||||
hasLocation = !!response.data?.data?.location;
|
console.error('[Middleware] Failed to fetch user data:', userError);
|
||||||
} catch {
|
// If we can't fetch user data, allow access (don't break the app)
|
||||||
// If API fails, check user data as fallback
|
return null;
|
||||||
hasLocation = !!user?.location;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
hasLocation = !!userData?.location;
|
||||||
|
|
||||||
// Update cache
|
// Update cache
|
||||||
onboardingCache.set(userId, { hasLocation, timestamp: now });
|
onboardingCache.set(userId, { hasLocation, timestamp: now });
|
||||||
}
|
}
|
||||||
@@ -114,9 +114,10 @@ export const middleware = async ({ request }: LoaderFunctionArgs) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check route permissions using user data
|
// Check route permissions using fresh user data from Zustand (for UI metadata)
|
||||||
|
const session = SessionUser.get();
|
||||||
const userPermissions =
|
const userPermissions =
|
||||||
user?.role?.permissions?.map?.((perm) => perm?.name) ?? [];
|
session?.role?.permissions?.map?.((perm) => perm?.name) ?? [];
|
||||||
|
|
||||||
const matchedRoute = mappingRoutePermissions.find(
|
const matchedRoute = mappingRoutePermissions.find(
|
||||||
(route) => route.path === pathname
|
(route) => route.path === pathname
|
||||||
|
|||||||
@@ -1,754 +0,0 @@
|
|||||||
# Hackathon Backoffice API Contract
|
|
||||||
|
|
||||||
## GET /api/v1/admin/dashboard
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Single endpoint delivering aggregated metrics for the IMPHNEN x Kolosal.ai Hackathon dashboard.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
- 401 if unauthenticated, 403 if authenticated but lacking required scope.
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /api/v1/admin/dashboard
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"total_participants": 1261,
|
|
||||||
"total_teams": 206,
|
|
||||||
"total_submissions": 0 // Total project submitted
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Field Types
|
|
||||||
|
|
||||||
| Path | Type | Notes |
|
|
||||||
| ------------------------- | ------- | --------------------- |
|
|
||||||
| `data.total_participants` | integer | >= 0 |
|
|
||||||
| `data.total_teams` | integer | >= 0 |
|
|
||||||
| `data.total_submissions` | integer | <= `data.total_teams` |
|
|
||||||
|
|
||||||
### Errors
|
|
||||||
|
|
||||||
| Status | Code | Message | Notes |
|
|
||||||
| ------ | ---------------- | ----------------------------- | --------------------- |
|
|
||||||
| 401 | `unauthorized` | `authentication required` | Missing/invalid token |
|
|
||||||
| 403 | `forbidden` | `insufficient permissions` | Lacks required scope |
|
|
||||||
| 429 | `rate_limited` | `too many dashboard requests` | Rate limiting |
|
|
||||||
| 500 | `internal_error` | `unexpected server error` | Unhandled exception |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET /api/v1/admin/users
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Retrieve paginated list of hackathon participants with filtering, searching, and sorting capabilities for backoffice user management.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
- 401 if unauthenticated, 403 if authenticated but lacking required scope.
|
|
||||||
|
|
||||||
### Query Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Default | Description |
|
|
||||||
| ------------ | ------- | -------- | ------------ | ------------------------------------------------------------- |
|
|
||||||
| `page` | integer | No | 1 | Page number (1-based) |
|
|
||||||
| `limit` | integer | No | 10 | Items per page (1-100) |
|
|
||||||
| `search` | string | No | - | Search by name or location (case-insensitive) |
|
|
||||||
| `status` | string | No | `all` | Filter by status: `all`, `active`, `inactive` |
|
|
||||||
| `location` | string | No | `all` | Filter by location or `all` |
|
|
||||||
| `skills` | string | No | - | Comma-separated skill filters |
|
|
||||||
| `sort_by` | string | No | `created_at` | Sort field: `fullname`, `location`, `is_active`, `created_at` |
|
|
||||||
| `sort_order` | string | No | `desc` | Sort order: `asc`, `desc` |
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /api/v1/admin/users
|
|
||||||
GET /api/v1/admin/users?page=2&limit=10
|
|
||||||
GET /api/v1/admin/users?search=john&status=active
|
|
||||||
GET /api/v1/admin/users?location=Jakarta&skills=Frontend Developer,UI/UX Designer
|
|
||||||
GET /api/v1/admin/users?sort_by=fullname&sort_order=asc
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"users": [
|
|
||||||
{
|
|
||||||
"id": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"avatar": "https://example.com/avatars/user1.jpg", // Optional
|
|
||||||
"fullname": "Budi Santoso",
|
|
||||||
"bio": "Passionate developer with 5+ years experience", // Optional
|
|
||||||
"location": "Jakarta",
|
|
||||||
"is_active": true,
|
|
||||||
"skills": ["Frontend Developer", "UI/UX Designer"], // Optional
|
|
||||||
"created_at": "2024-11-15T08:30:00Z",
|
|
||||||
"updated_at": "2024-11-30T14:22:00Z"
|
|
||||||
}
|
|
||||||
// ... more users
|
|
||||||
],
|
|
||||||
"pagination": {
|
|
||||||
"current_page": 1,
|
|
||||||
"total_pages": 15,
|
|
||||||
"total_items": 287,
|
|
||||||
"items_per_page": 20,
|
|
||||||
"has_next": true,
|
|
||||||
"has_prev": false
|
|
||||||
},
|
|
||||||
"filters": {
|
|
||||||
"available_locations": ["Jakarta", "Bandung", "Surabaya", "Medan", "Yogyakarta"],
|
|
||||||
"available_skills": ["Frontend Developer", "Backend Developer", "Full Stack Developer", "DevOps Engineer", "UI/UX Designer", "Product Manager", "Data Scientist", "Mobile Developer"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Field Types
|
|
||||||
|
|
||||||
| Path | Type | Notes |
|
|
||||||
| ------------------------- | ------- | ------------------------------ |
|
|
||||||
| `data.users[].id` | string | UUID format |
|
|
||||||
| `data.users[].avatar` | string | URL, nullable |
|
|
||||||
| `data.users[].fullname` | string | Required |
|
|
||||||
| `data.users[].bio` | string | Optional, max 500 chars |
|
|
||||||
| `data.users[].location` | string | Required, from predefined list |
|
|
||||||
| `data.users[].is_active` | boolean | Account status |
|
|
||||||
| `data.users[].skills` | array | Array of skill strings |
|
|
||||||
| `data.users[].created_at` | string | ISO 8601 timestamp |
|
|
||||||
| `data.users[].updated_at` | string | ISO 8601 timestamp |
|
|
||||||
| `data.pagination.*` | integer | Pagination metadata |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET /api/v1/admin/users/{user_id}
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Retrieve detailed information for a specific user by ID.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Path Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ------ | -------- | ----------- |
|
|
||||||
| `user_id` | string | Yes | User UUID |
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /api/v1/admin/users/550e8400-e29b-41d4-a716-446655440000
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"id": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"avatar": "https://example.com/avatars/user1.jpg",
|
|
||||||
"fullname": "Budi Santoso",
|
|
||||||
"bio": "Passionate developer with 5+ years experience",
|
|
||||||
"location": "Jakarta",
|
|
||||||
"is_active": true,
|
|
||||||
"skills": ["Frontend Developer", "UI/UX Designer"],
|
|
||||||
"created_at": "2024-11-15T08:30:00Z",
|
|
||||||
"updated_at": "2024-11-30T14:22:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## POST /api/v1/admin/users
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Create a new user account in the hackathon system.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Request Body Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"fullname": "Jane Doe", // Required, 1-100 chars
|
|
||||||
"bio": "Experienced developer", // Optional, max 500 chars
|
|
||||||
"location": "Jakarta", // Required, from predefined list
|
|
||||||
"is_active": true, // Required, boolean
|
|
||||||
"skills": ["Backend Developer"], // Optional, array of valid skills
|
|
||||||
"avatar": "https://example.com/images/..." // Optional, URL
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /api/v1/admin/users
|
|
||||||
Content-Type: application/json
|
|
||||||
|
|
||||||
{
|
|
||||||
"fullname": "Jane Doe",
|
|
||||||
"bio": "Experienced developer passionate about AI and machine learning",
|
|
||||||
"location": "Jakarta",
|
|
||||||
"is_active": true,
|
|
||||||
"skills": ["Backend Developer", "Data Scientist"],
|
|
||||||
"avatar": "https://example.com/images/..."
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"id": "550e8400-e29b-41d4-a716-446655440001",
|
|
||||||
"avatar": "https://example.com/avatars/generated_url.jpg",
|
|
||||||
"fullname": "Jane Doe",
|
|
||||||
"bio": "Experienced developer passionate about AI and machine learning",
|
|
||||||
"location": "Jakarta",
|
|
||||||
"is_active": true,
|
|
||||||
"skills": ["Backend Developer", "Data Scientist"],
|
|
||||||
"created_at": "2024-12-01T10:30:00Z",
|
|
||||||
"updated_at": "2024-12-01T10:30:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## PUT /api/v1/admin/users/{user_id}
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Update an existing user's profile information.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Path Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ------ | -------- | ----------- |
|
|
||||||
| `user_id` | string | Yes | User UUID |
|
|
||||||
|
|
||||||
### Request Body Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"fullname": "Jane Smith", // Optional, 1-100 chars
|
|
||||||
"bio": "Senior developer", // Optional, max 500 chars, null to clear
|
|
||||||
"location": "Bandung", // Optional, from predefined list
|
|
||||||
"is_active": false, // Optional, boolean
|
|
||||||
"skills": ["Full Stack Developer"], // Optional, array of valid skills
|
|
||||||
"avatar": "https://example.com/images/..." // Optional, URL, null to remove
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
PUT /api/v1/admin/users/550e8400-e29b-41d4-a716-446655440000
|
|
||||||
Content-Type: application/json
|
|
||||||
|
|
||||||
{
|
|
||||||
"fullname": "Jane Smith",
|
|
||||||
"location": "Bandung",
|
|
||||||
"is_active": false,
|
|
||||||
"skills": ["Full Stack Developer", "Product Manager"]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"id": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"avatar": "https://example.com/avatars/user1.jpg",
|
|
||||||
"fullname": "Jane Smith",
|
|
||||||
"bio": "Experienced developer passionate about AI and machine learning",
|
|
||||||
"location": "Bandung",
|
|
||||||
"is_active": false,
|
|
||||||
"skills": ["Full Stack Developer", "Product Manager"],
|
|
||||||
"created_at": "2024-11-15T08:30:00Z",
|
|
||||||
"updated_at": "2024-12-01T10:45:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## DELETE /api/v1/admin/users/{user_id}
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
(Soft) Delete a user account from the hackathon system.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Path Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ------ | -------- | ----------- |
|
|
||||||
| `user_id` | string | Yes | User UUID |
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
DELETE /api/v1/admin/users/550e8400-e29b-41d4-a716-446655440000
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"message": "User successfully deleted",
|
|
||||||
"deleted_user_id": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"deleted_at": "2024-12-01T10:50:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Common Error Responses
|
|
||||||
|
|
||||||
### User Management Endpoints
|
|
||||||
|
|
||||||
| Status | Code | Message | Notes |
|
|
||||||
| ------ | --------------------- | -------------------------------- | ---------------------------- |
|
|
||||||
| 400 | `validation_error` | `Invalid request data` | Field validation failures |
|
|
||||||
| 401 | `unauthorized` | `Authentication required` | Missing/invalid token |
|
|
||||||
| 403 | `forbidden` | `Insufficient permissions` | Lacks required scope |
|
|
||||||
| 404 | `user_not_found` | `User not found` | Invalid user ID |
|
|
||||||
| 409 | `user_already_exists` | `User with email already exists` | Duplicate user creation |
|
|
||||||
| 413 | `payload_too_large` | `Avatar file too large` | Avatar exceeds size limit |
|
|
||||||
| 422 | `invalid_skill` | `Invalid skill specified` | Skill not in allowed list |
|
|
||||||
| 422 | `invalid_location` | `Invalid location specified` | Location not in allowed list |
|
|
||||||
| 429 | `rate_limited` | `Too many requests` | Rate limiting |
|
|
||||||
| 500 | `internal_error` | `Unexpected server error` | Unhandled exception |
|
|
||||||
|
|
||||||
### Validation Error Details
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"error": {
|
|
||||||
"code": "validation_error",
|
|
||||||
"message": "Invalid request data",
|
|
||||||
"details": [
|
|
||||||
{
|
|
||||||
"field": "fullname",
|
|
||||||
"code": "required",
|
|
||||||
"message": "Full name is required"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"field": "location",
|
|
||||||
"code": "invalid_choice",
|
|
||||||
"message": "Location must be one of: Jakarta, Bandung, Surabaya, Medan, Yogyakarta"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Rate Limiting
|
|
||||||
|
|
||||||
- **Dashboard**: 30 requests / minute / admin user
|
|
||||||
- **User Management**: 100 requests / minute / admin user
|
|
||||||
- **File Upload**: 10 avatar uploads / minute / admin user
|
|
||||||
- Return 429 with `Retry-After` header
|
|
||||||
|
|
||||||
## Avatar Handling
|
|
||||||
|
|
||||||
- **Supported formats**: JPEG, PNG, WebP
|
|
||||||
- **Max file size**: 5MB
|
|
||||||
- **Recommended dimensions**: 400x400px
|
|
||||||
- **Storage**: Uploaded avatars are processed and stored with generated URLs
|
|
||||||
- **URL response**: Always return publicly accessible HTTPS URLs
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET /api/v1/admin/teams
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Retrieve paginated list of hackathon teams with filtering, searching, and sorting capabilities for backoffice team management.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
- 401 if unauthenticated, 403 if authenticated but lacking required scope.
|
|
||||||
|
|
||||||
### Query Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Default | Description |
|
|
||||||
| -------------- | ------- | -------- | ------------ | ---------------------------------------------------------------------------------------- |
|
|
||||||
| `page` | integer | No | 1 | Page number (1-based) |
|
|
||||||
| `limit` | integer | No | 10 | Items per page (1-100) |
|
|
||||||
| `search` | string | No | - | Search by team name, city, or leader name (case-insensitive) |
|
|
||||||
| `visibility` | string | No | `all` | Filter by visibility: `all`, `public`, `private` |
|
|
||||||
| `city` | string | No | `all` | Filter by city or `all` |
|
|
||||||
| `submission` | string | No | `all` | Filter by submission status: `all`, `submitted`, `not_submitted` |
|
|
||||||
| `member_count` | string | No | `all` | Filter by member count: `all`, `1`, `2`, `3`, `4`, `5` |
|
|
||||||
| `sort_by` | string | No | `created_at` | Sort field: `name`, `city`, `visibility`, `member_count`, `has_submission`, `created_at` |
|
|
||||||
| `sort_order` | string | No | `desc` | Sort order: `asc`, `desc` |
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /api/v1/admin/teams
|
|
||||||
GET /api/v1/admin/teams?page=2&limit=10
|
|
||||||
GET /api/v1/admin/teams?search=innovators&visibility=public
|
|
||||||
GET /api/v1/admin/teams?city=Jakarta&submission=submitted&member_count=3
|
|
||||||
GET /api/v1/admin/teams?sort_by=name&sort_order=asc
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"teams": [
|
|
||||||
{
|
|
||||||
"id": "team-001",
|
|
||||||
"name": "Team Innovators",
|
|
||||||
"description": "Building innovative solutions for modern problems", // Optional
|
|
||||||
"city": "Jakarta",
|
|
||||||
"banner": "https://example.com/banners/team1.jpg", // Optional
|
|
||||||
"logo": "https://example.com/logos/team1.jpg", // Optional
|
|
||||||
"visibility": "public", // "public" | "private"
|
|
||||||
"member_count": 3,
|
|
||||||
"has_submission": true,
|
|
||||||
"created_at": "2024-11-15T08:30:00Z",
|
|
||||||
"updated_at": "2024-11-30T14:22:00Z",
|
|
||||||
"leader_id": "leader-team-001",
|
|
||||||
"members": [
|
|
||||||
{
|
|
||||||
"id": "member-team-001-0",
|
|
||||||
"joined_at": "2024-11-15T08:30:00Z",
|
|
||||||
"role": "leader", // "leader" | "member"
|
|
||||||
"status": "accepted", // "pending" | "accepted" | "rejected"
|
|
||||||
"team_id": "team-001",
|
|
||||||
"user_id": "leader-team-001",
|
|
||||||
"user": {
|
|
||||||
"id": "leader-team-001",
|
|
||||||
"avatar": "https://ui-avatars.com/api/?name=John+Doe", // Optional
|
|
||||||
"bio": "Passionate developer with 5+ years experience", // Optional
|
|
||||||
"created_at": "2024-10-01T08:30:00Z",
|
|
||||||
"email": "john.doe@example.com",
|
|
||||||
"fullname": "John Doe",
|
|
||||||
"is_active": true,
|
|
||||||
"location": "Jakarta",
|
|
||||||
"phone_number": "+6281234567890", // Optional
|
|
||||||
"skills": ["Frontend Developer", "UI/UX Designer"],
|
|
||||||
"updated_at": "2024-11-30T14:22:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// ... more members
|
|
||||||
]
|
|
||||||
}
|
|
||||||
// ... more teams
|
|
||||||
],
|
|
||||||
"pagination": {
|
|
||||||
"current_page": 1,
|
|
||||||
"total_pages": 15,
|
|
||||||
"total_items": 147,
|
|
||||||
"items_per_page": 10,
|
|
||||||
"has_next": true,
|
|
||||||
"has_prev": false
|
|
||||||
},
|
|
||||||
"filters": {
|
|
||||||
"available_cities": ["Jakarta", "Bandung", "Surabaya", "Medan", "Yogyakarta"],
|
|
||||||
"available_skills": ["Frontend Developer", "Backend Developer", "Full Stack Developer", "DevOps Engineer", "UI/UX Designer", "Product Manager", "Data Scientist", "Mobile Developer"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET /api/v1/admin/teams/{team_id}
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Retrieve detailed information for a specific team by ID.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Path Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ------ | -------- | ----------- |
|
|
||||||
| `team_id` | string | Yes | Team ID |
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
```
|
|
||||||
GET /api/v1/admin/teams/team-001
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"id": "team-001",
|
|
||||||
"name": "Team Innovators",
|
|
||||||
"description": "Building innovative solutions for modern problems",
|
|
||||||
"city": "Jakarta",
|
|
||||||
"banner": "https://example.com/banners/team1.jpg",
|
|
||||||
"logo": "https://example.com/logos/team1.jpg",
|
|
||||||
"visibility": "public",
|
|
||||||
"member_count": 3,
|
|
||||||
"has_submission": true,
|
|
||||||
"created_at": "2024-11-15T08:30:00Z",
|
|
||||||
"updated_at": "2024-11-30T14:22:00Z",
|
|
||||||
"leader_id": "leader-team-001",
|
|
||||||
"members": [
|
|
||||||
{
|
|
||||||
"id": "member-team-001-0",
|
|
||||||
"joined_at": "2024-11-15T08:30:00Z",
|
|
||||||
"role": "leader",
|
|
||||||
"status": "accepted",
|
|
||||||
"team_id": "team-001",
|
|
||||||
"user_id": "leader-team-001",
|
|
||||||
"user": {
|
|
||||||
"id": "leader-team-001",
|
|
||||||
"avatar": "https://ui-avatars.com/api/?name=John+Doe",
|
|
||||||
"bio": "Passionate developer with 5+ years experience",
|
|
||||||
"created_at": "2024-10-01T08:30:00Z",
|
|
||||||
"email": "john.doe@example.com",
|
|
||||||
"fullname": "John Doe",
|
|
||||||
"is_active": true,
|
|
||||||
"location": "Jakarta",
|
|
||||||
"phone_number": "+6281234567890",
|
|
||||||
"skills": ["Frontend Developer", "UI/UX Designer"],
|
|
||||||
"updated_at": "2024-11-30T14:22:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// ... all team members
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## POST /api/v1/admin/teams
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Create a new team in the hackathon system.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Request Body Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"name": "Team New Innovators", // Required, 1-100 chars
|
|
||||||
"description": "Building next-gen solutions", // Optional, max 500 chars
|
|
||||||
"city": "Jakarta", // Required, from predefined list
|
|
||||||
"visibility": "public", // Required, "public" | "private"
|
|
||||||
"leader_id": "user-123", // Required, existing user ID
|
|
||||||
"banner": "https://example.com/banners/new.jpg", // Optional, URL
|
|
||||||
"logo": "https://example.com/logos/new.jpg" // Optional, URL
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"id": "team-new-001",
|
|
||||||
"name": "Team New Innovators",
|
|
||||||
"description": "Building next-gen solutions",
|
|
||||||
"city": "Jakarta",
|
|
||||||
"banner": "https://example.com/banners/new.jpg",
|
|
||||||
"logo": "https://example.com/logos/new.jpg",
|
|
||||||
"visibility": "public",
|
|
||||||
"member_count": 1,
|
|
||||||
"has_submission": false,
|
|
||||||
"created_at": "2024-12-02T10:30:00Z",
|
|
||||||
"updated_at": "2024-12-02T10:30:00Z",
|
|
||||||
"leader_id": "user-123",
|
|
||||||
"members": [
|
|
||||||
{
|
|
||||||
"id": "member-new-001-0",
|
|
||||||
"joined_at": "2024-12-02T10:30:00Z",
|
|
||||||
"role": "leader",
|
|
||||||
"status": "accepted",
|
|
||||||
"team_id": "team-new-001",
|
|
||||||
"user_id": "user-123",
|
|
||||||
"user": {
|
|
||||||
"id": "user-123",
|
|
||||||
"fullname": "John Doe",
|
|
||||||
"email": "john.doe@example.com",
|
|
||||||
"location": "Jakarta",
|
|
||||||
"is_active": true,
|
|
||||||
"skills": ["Frontend Developer"],
|
|
||||||
"created_at": "2024-10-01T08:30:00Z",
|
|
||||||
"updated_at": "2024-12-02T10:30:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## PUT /api/v1/admin/teams/{team_id}
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Update an existing team's information.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Path Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ------ | -------- | ----------- |
|
|
||||||
| `team_id` | string | Yes | Team ID |
|
|
||||||
|
|
||||||
### Request Body Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"name": "Team Updated Name", // Optional, 1-100 chars
|
|
||||||
"description": "Updated description", // Optional, max 500 chars, null to clear
|
|
||||||
"city": "Bandung", // Optional, from predefined list
|
|
||||||
"visibility": "private", // Optional, "public" | "private"
|
|
||||||
"banner": "https://example.com/banners/updated.jpg", // Optional, URL, null to remove
|
|
||||||
"logo": "https://example.com/logos/updated.jpg" // Optional, URL, null to remove
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
Same as GET /api/v1/admin/teams/{team_id} with updated values.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## DELETE /api/v1/admin/teams/{team_id}
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Delete a team from the hackathon system.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Path Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ------ | -------- | ----------- |
|
|
||||||
| `team_id` | string | Yes | Team ID |
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"message": "Team successfully deleted",
|
|
||||||
"deleted_team_id": "team-001",
|
|
||||||
"deleted_at": "2024-12-02T10:50:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET /api/v1/admin/teams/{team_id}/submission
|
|
||||||
|
|
||||||
### Purpose
|
|
||||||
|
|
||||||
Retrieve submission details for a specific team.
|
|
||||||
|
|
||||||
### Authentication & Authorization
|
|
||||||
|
|
||||||
- Requires admin (backoffice) scope: e.g. `role=admin`
|
|
||||||
|
|
||||||
### Path Parameters
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ------ | -------- | ----------- |
|
|
||||||
| `team_id` | string | Yes | Team ID |
|
|
||||||
|
|
||||||
### Response Schema
|
|
||||||
|
|
||||||
```jsonc
|
|
||||||
{
|
|
||||||
"data": {
|
|
||||||
"team_id": "team-001",
|
|
||||||
"team_name": "Team Innovators",
|
|
||||||
"project_name": "EcoTrack - Smart Waste Management",
|
|
||||||
"project_description": "An AI-powered waste management solution that helps cities optimize collection routes and reduce environmental impact.",
|
|
||||||
"repository_url": "https://github.com/team-innovators/ecotrack",
|
|
||||||
"demo_url": "https://ecotrack-demo.vercel.app",
|
|
||||||
"presentation_url": "https://docs.google.com/presentation/d/team-innovators-pitch/edit",
|
|
||||||
"submitted_at": "2024-12-01T15:30:00Z",
|
|
||||||
"updated_at": "2024-12-01T16:45:00Z"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Common Error Responses
|
|
||||||
|
|
||||||
### Team Management Endpoints
|
|
||||||
|
|
||||||
| Status | Code | Message | Notes |
|
|
||||||
| ------ | ---------------------- | ------------------------------- | -------------------------- |
|
|
||||||
| 400 | `validation_error` | `Invalid request data` | Field validation failures |
|
|
||||||
| 401 | `unauthorized` | `Authentication required` | Missing/invalid token |
|
|
||||||
| 403 | `forbidden` | `Insufficient permissions` | Lacks required scope |
|
|
||||||
| 404 | `team_not_found` | `Team not found` | Invalid team ID |
|
|
||||||
| 404 | `submission_not_found` | `Team submission not found` | Team has no submission |
|
|
||||||
| 409 | `team_already_exists` | `Team with name already exists` | Duplicate team name |
|
|
||||||
| 413 | `payload_too_large` | `Banner/logo file too large` | Image exceeds size limit |
|
|
||||||
| 422 | `invalid_city` | `Invalid city specified` | City not in allowed list |
|
|
||||||
| 422 | `invalid_leader` | `Invalid leader user ID` | Leader user does not exist |
|
|
||||||
| 429 | `rate_limited` | `Too many requests` | Rate limiting |
|
|
||||||
| 500 | `internal_error` | `Unexpected server error` | Unhandled exception |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Revision History**
|
|
||||||
|
|
||||||
- v1.0.0 (2025-11-30): Initial contract drafted.
|
|
||||||
- v2.0.0 (2025-12-01): Added user management endpoints with filtering, pagination, CRUD operations, and avatar handling.
|
|
||||||
- v3.0.0 (2025-12-02): Added team management endpoints based on backoffice implementation with team members, submissions, and comprehensive filtering.
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
import axios from 'axios';
|
|
||||||
import { useAuthStore } from '../hooks/auth';
|
|
||||||
|
|
||||||
// Hackathon Backend API Base URL
|
|
||||||
const HACKATHON_API_URL = 'https://api.hackathon.imphnen.dev/api/v1';
|
|
||||||
|
|
||||||
// Create axios instance for hackathon backend
|
|
||||||
export const hackathonApi = axios.create({
|
|
||||||
baseURL: HACKATHON_API_URL,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add auth token interceptor
|
|
||||||
hackathonApi.interceptors.request.use(
|
|
||||||
(config) => {
|
|
||||||
const { session } = useAuthStore.getState();
|
|
||||||
if (session?.token?.access_token) {
|
|
||||||
config.headers.Authorization = `Bearer ${session.token.access_token}`;
|
|
||||||
}
|
|
||||||
return config;
|
|
||||||
},
|
|
||||||
(error) => {
|
|
||||||
return Promise.reject(new Error(error.message || 'Request failed'));
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Error handling interceptor
|
|
||||||
hackathonApi.interceptors.response.use(
|
|
||||||
(response) => response,
|
|
||||||
(error) => {
|
|
||||||
// Handle 401 - clear session and redirect to login
|
|
||||||
// But skip redirect if already on auth pages (to avoid reload on login failure)
|
|
||||||
if (error.response?.status === 401) {
|
|
||||||
const isAuthPage = globalThis.window !== undefined && globalThis.location.pathname.startsWith('/auth');
|
|
||||||
|
|
||||||
// Only clear session and redirect if not on auth page
|
|
||||||
if (!isAuthPage) {
|
|
||||||
useAuthStore.getState().clearSession();
|
|
||||||
if (globalThis.window !== undefined) {
|
|
||||||
globalThis.location.href = '/auth/login';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If backend sends a message, use it
|
|
||||||
const backendMsg = error?.response?.data?.message;
|
|
||||||
if (backendMsg && typeof backendMsg === 'string') {
|
|
||||||
return Promise.reject(new Error(backendMsg));
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.reject(new Error(error.message || 'Request failed'));
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// API Response wrapper type
|
|
||||||
export interface HackathonApiResponse<T> {
|
|
||||||
data: T;
|
|
||||||
message?: string;
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,6 @@ export * from './gacha';
|
|||||||
export * from './users';
|
export * from './users';
|
||||||
export * from './mentors';
|
export * from './mentors';
|
||||||
export * from './upload';
|
export * from './upload';
|
||||||
export * from './hackathon';
|
|
||||||
|
|
||||||
// Common API response wrapper interface
|
// Common API response wrapper interface
|
||||||
export interface ApiResponse<T> {
|
export interface ApiResponse<T> {
|
||||||
|
|||||||
@@ -1,251 +1,57 @@
|
|||||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
import { supabase } from '../../supabase';
|
||||||
import { hackathonApi, HackathonApiResponse } from '../../api/hackathon';
|
import { useMutation } from '@tanstack/react-query';
|
||||||
import { useAuthStore } from './use-auth-store';
|
import * as authApi from '../../api/auth';
|
||||||
|
|
||||||
export * from './use-auth-store';
|
export * from './use-auth-store';
|
||||||
|
|
||||||
// Types matching backend response
|
// React Query hooks for auth API
|
||||||
interface TokenInfo {
|
export const usePostLogin = () => {
|
||||||
access_token: string;
|
|
||||||
refresh_token: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface User {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
fullname: string;
|
|
||||||
phone_number?: string;
|
|
||||||
avatar?: string;
|
|
||||||
birthdate?: string;
|
|
||||||
gender?: string;
|
|
||||||
is_active: boolean;
|
|
||||||
location?: string;
|
|
||||||
bio?: string;
|
|
||||||
skills?: string[];
|
|
||||||
role_id?: string;
|
|
||||||
created_at: string;
|
|
||||||
updated_at?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AuthResponse {
|
|
||||||
token: TokenInfo;
|
|
||||||
user: User;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SessionResponse {
|
|
||||||
user: User;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MessageResponse {
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login request type
|
|
||||||
interface LoginRequest {
|
|
||||||
email: string;
|
|
||||||
password: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Signup request type
|
|
||||||
interface SignupRequest {
|
|
||||||
email: string;
|
|
||||||
password: string;
|
|
||||||
fullname: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// GitHub auth request type
|
|
||||||
interface GitHubAuthRequest {
|
|
||||||
code: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Forgot password request type
|
|
||||||
interface ForgotPasswordRequest {
|
|
||||||
email: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset password request type
|
|
||||||
interface ResetPasswordRequest {
|
|
||||||
access_token: string;
|
|
||||||
new_password: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend API-based auth hooks
|
|
||||||
|
|
||||||
// Email/Password Login
|
|
||||||
export const useLogin = () => {
|
|
||||||
const { setSession } = useAuthStore();
|
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (data: LoginRequest) => {
|
mutationFn: authApi.postLogin,
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<AuthResponse>>(
|
|
||||||
'/auth/login',
|
|
||||||
data
|
|
||||||
);
|
|
||||||
return response.data.data;
|
|
||||||
},
|
|
||||||
onSuccess: (data) => {
|
|
||||||
setSession({
|
|
||||||
token: data.token,
|
|
||||||
user: {
|
|
||||||
id: data.user.id,
|
|
||||||
email: data.user.email,
|
|
||||||
fullname: data.user.fullname,
|
|
||||||
phone_number: data.user.phone_number || '',
|
|
||||||
avatar: data.user.avatar || '',
|
|
||||||
birthdate: data.user.birthdate || '',
|
|
||||||
gender: data.user.gender || '',
|
|
||||||
is_active: data.user.is_active,
|
|
||||||
location: data.user.location,
|
|
||||||
bio: data.user.bio,
|
|
||||||
skills: data.user.skills,
|
|
||||||
role: {
|
|
||||||
id: '',
|
|
||||||
name: 'user',
|
|
||||||
permissions: [],
|
|
||||||
created_at: '',
|
|
||||||
updated_at: '',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Email/Password Signup - returns message only (user needs to activate via email)
|
export const usePostRegister = () => {
|
||||||
export const useSignup = () => {
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (data: SignupRequest) => {
|
mutationFn: authApi.postRegister,
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<MessageResponse>>(
|
|
||||||
'/auth/signup',
|
|
||||||
data
|
|
||||||
);
|
|
||||||
return response.data.data;
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// GitHub OAuth - exchange code for token
|
export const usePostVerifyEmail = () => {
|
||||||
export const useGitHubCallback = () => {
|
|
||||||
const { setSession } = useAuthStore();
|
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (data: GitHubAuthRequest) => {
|
mutationFn: authApi.postVerifyEmail,
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<AuthResponse>>(
|
|
||||||
'/auth/github',
|
|
||||||
data
|
|
||||||
);
|
|
||||||
return response.data.data;
|
|
||||||
},
|
|
||||||
onSuccess: (data) => {
|
|
||||||
setSession({
|
|
||||||
token: data.token,
|
|
||||||
user: {
|
|
||||||
id: data.user.id,
|
|
||||||
email: data.user.email,
|
|
||||||
fullname: data.user.fullname,
|
|
||||||
phone_number: data.user.phone_number || '',
|
|
||||||
avatar: data.user.avatar || '',
|
|
||||||
birthdate: data.user.birthdate || '',
|
|
||||||
gender: data.user.gender || '',
|
|
||||||
is_active: data.user.is_active,
|
|
||||||
location: data.user.location,
|
|
||||||
bio: data.user.bio,
|
|
||||||
skills: data.user.skills,
|
|
||||||
role: {
|
|
||||||
id: '',
|
|
||||||
name: 'user',
|
|
||||||
permissions: [],
|
|
||||||
created_at: '',
|
|
||||||
updated_at: '',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get current session (protected)
|
export const usePostSendOtp = () => {
|
||||||
export const useSession = () => {
|
|
||||||
const { session } = useAuthStore();
|
|
||||||
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ['auth-session'],
|
|
||||||
queryFn: async () => {
|
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<SessionResponse>>(
|
|
||||||
'/auth/session'
|
|
||||||
);
|
|
||||||
return response.data.data;
|
|
||||||
},
|
|
||||||
enabled: !!session?.token,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Forgot password
|
|
||||||
export const useForgotPassword = () => {
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (data: ForgotPasswordRequest) => {
|
mutationFn: authApi.postSendOtp,
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<MessageResponse>>(
|
|
||||||
'/auth/forgot-password',
|
|
||||||
data
|
|
||||||
);
|
|
||||||
return response.data.data;
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Reset password
|
export const useGoogleCallback = () => {
|
||||||
export const useResetPassword = () => {
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (data: ResetPasswordRequest) => {
|
mutationFn: ({ code, state }: { code: string; state: string }) =>
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<MessageResponse>>(
|
authApi.postGoogleCallback(code, state),
|
||||||
'/auth/reset-password',
|
|
||||||
data
|
|
||||||
);
|
|
||||||
return response.data.data;
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Sign out (clears local session)
|
// Supabase GitHub OAuth hook
|
||||||
export const useSignOut = () => {
|
|
||||||
const { clearSession } = useAuthStore();
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async () => {
|
|
||||||
// No backend call needed - just clear local session
|
|
||||||
clearSession();
|
|
||||||
return { success: true };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// GitHub OAuth URL helper
|
|
||||||
// The frontend needs to redirect to GitHub with the client_id
|
|
||||||
// After GitHub redirects back with a code, use useGitHubCallback
|
|
||||||
export const getGitHubOAuthUrl = (clientId: string, redirectUri: string) => {
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
client_id: clientId,
|
|
||||||
redirect_uri: redirectUri,
|
|
||||||
scope: 'read:user user:email',
|
|
||||||
});
|
|
||||||
return `https://github.com/login/oauth/authorize?${params.toString()}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Backward compatibility hooks - these wrap the new backend API
|
|
||||||
|
|
||||||
// GitHub OAuth hook (backward compatible)
|
|
||||||
export const useGitHubAuth = () => {
|
export const useGitHubAuth = () => {
|
||||||
const signInWithGitHub = async () => {
|
const signInWithGitHub = async () => {
|
||||||
// Get GitHub client ID from environment
|
const { data, error } = await supabase.auth.signInWithOAuth({
|
||||||
const clientId = import.meta.env.VITE_GITHUB_CLIENT_ID || '';
|
provider: 'github',
|
||||||
if (!clientId) {
|
options: {
|
||||||
throw new Error('GitHub Client ID not configured. Set VITE_GITHUB_CLIENT_ID environment variable.');
|
redirectTo: `${globalThis.location.origin}/auth/callback`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const redirectUri = `${globalThis.location.origin}/auth/callback`;
|
// Return the OAuth URL for debugging
|
||||||
const url = getGitHubOAuthUrl(clientId, redirectUri);
|
return data;
|
||||||
|
|
||||||
return { url };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -253,33 +59,45 @@ export const useGitHubAuth = () => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
// Email/Password auth hook (backward compatible)
|
// Supabase Email/Password authentication hook
|
||||||
export const useEmailAuth = () => {
|
export const useEmailAuth = () => {
|
||||||
const loginMutation = useLogin();
|
|
||||||
const signupMutation = useSignup();
|
|
||||||
const { clearSession } = useAuthStore();
|
|
||||||
|
|
||||||
const signInWithEmail = async (email: string, password: string) => {
|
const signInWithEmail = async (email: string, password: string) => {
|
||||||
const result = await loginMutation.mutateAsync({ email, password });
|
const { data, error } = await supabase.auth.signInWithPassword({
|
||||||
return {
|
email,
|
||||||
user: result.user,
|
password,
|
||||||
session: {
|
});
|
||||||
access_token: result.token.access_token,
|
|
||||||
refresh_token: result.token.refresh_token,
|
if (error) {
|
||||||
},
|
throw error;
|
||||||
};
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const signUpWithEmail = async (email: string, password: string, fullname: string) => {
|
const signUpWithEmail = async (email: string, password: string, fullname: string) => {
|
||||||
const result = await signupMutation.mutateAsync({ email, password, fullname });
|
const { data, error } = await supabase.auth.signUp({
|
||||||
// Signup only returns a message (user needs to verify email first)
|
email,
|
||||||
return {
|
password,
|
||||||
message: result.message,
|
options: {
|
||||||
};
|
data: {
|
||||||
|
full_name: fullname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const signOut = async () => {
|
const signOut = async () => {
|
||||||
clearSession();
|
const { error } = await supabase.auth.signOut();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -288,58 +106,3 @@ export const useEmailAuth = () => {
|
|||||||
signOut,
|
signOut,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
// Legacy hooks for old API compatibility (deprecated)
|
|
||||||
|
|
||||||
/** @deprecated Use useLogin instead */
|
|
||||||
export const usePostLogin = () => {
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async (data: LoginRequest) => {
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<AuthResponse>>(
|
|
||||||
'/auth/login',
|
|
||||||
data
|
|
||||||
);
|
|
||||||
return { data: response.data.data };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/** @deprecated Use useSignup instead */
|
|
||||||
export const usePostRegister = () => {
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async (data: SignupRequest) => {
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<AuthResponse>>(
|
|
||||||
'/auth/signup',
|
|
||||||
data
|
|
||||||
);
|
|
||||||
return { data: response.data.data };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/** @deprecated Not needed with new backend */
|
|
||||||
export const usePostVerifyEmail = () => {
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async () => {
|
|
||||||
throw new Error('Email verification not required with new backend');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/** @deprecated Not needed with new backend */
|
|
||||||
export const usePostSendOtp = () => {
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async () => {
|
|
||||||
throw new Error('OTP not required with new backend');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/** @deprecated Use useGitHubCallback instead */
|
|
||||||
export const useGoogleCallback = () => {
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async () => {
|
|
||||||
throw new Error('Google OAuth not supported. Use GitHub OAuth instead.');
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { hackathonApi, HackathonApiResponse } from '../../api/hackathon';
|
import { supabase } from '../../supabase';
|
||||||
import { useAuthStore } from '../auth';
|
import { useAuthStore } from '../auth';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
export type Message = {
|
export type Message = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -23,22 +24,101 @@ export const messageKeys = {
|
|||||||
team: (teamId: string) => [...messageKeys.all, 'team', teamId] as const,
|
team: (teamId: string) => [...messageKeys.all, 'team', teamId] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fetch messages for a team with polling
|
// Fetch messages for a team
|
||||||
export const useTeamMessages = (teamId: string) => {
|
export const useTeamMessages = (teamId: string) => {
|
||||||
return useQuery({
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
const query = useQuery({
|
||||||
queryKey: messageKeys.team(teamId),
|
queryKey: messageKeys.team(teamId),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<Message[]>>(
|
const { data: messages, error } = await supabase
|
||||||
`/chat/teams/${teamId}`
|
.from('team_messages')
|
||||||
);
|
.select(`
|
||||||
return response.data.data || [];
|
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,
|
enabled: !!teamId,
|
||||||
// Poll every 3 seconds for new messages
|
|
||||||
refetchInterval: 3000,
|
|
||||||
// Keep refetching even when window loses focus
|
|
||||||
refetchIntervalInBackground: true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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
|
// Send a message
|
||||||
@@ -52,15 +132,26 @@ export const useSendMessage = (teamId: string) => {
|
|||||||
throw new Error('You must be logged in to send messages');
|
throw new Error('You must be logged in to send messages');
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<Message>>(
|
const { data, error } = await supabase
|
||||||
`/chat/teams/${teamId}`,
|
.from('team_messages')
|
||||||
{ message }
|
.insert({
|
||||||
);
|
team_id: teamId,
|
||||||
|
user_id: session.user.id,
|
||||||
|
message,
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
return response.data.data;
|
if (error) {
|
||||||
|
console.error('Failed to send message:', error);
|
||||||
|
throw new Error(error.message || 'Failed to send message');
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
// Invalidate to trigger immediate refetch
|
// Realtime will handle adding the message to the list
|
||||||
|
// But we can invalidate to ensure consistency
|
||||||
queryClient.invalidateQueries({ queryKey: messageKeys.team(teamId) });
|
queryClient.invalidateQueries({ queryKey: messageKeys.team(teamId) });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -72,9 +163,18 @@ export const useDeleteMessage = (teamId: string) => {
|
|||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (messageId: string) => {
|
mutationFn: async (messageId: string) => {
|
||||||
await hackathonApi.delete(`/chat/messages/${messageId}`);
|
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: () => {
|
onSuccess: () => {
|
||||||
|
// Realtime will handle removing the message from the list
|
||||||
queryClient.invalidateQueries({ queryKey: messageKeys.team(teamId) });
|
queryClient.invalidateQueries({ queryKey: messageKeys.team(teamId) });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from '@tanstack/react-query';
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { hackathonApi, HackathonApiResponse } from '../../api/hackathon';
|
import * as teamsApi from '../../api/teams';
|
||||||
|
import { supabase, getAuthenticatedClient } from '../../supabase';
|
||||||
import { useAuthStore } from '../auth';
|
import { useAuthStore } from '../auth';
|
||||||
import type {
|
import type {
|
||||||
TCreateTeamRequest,
|
TCreateTeamRequest,
|
||||||
@@ -23,101 +24,6 @@ export const teamKeys = {
|
|||||||
myInvitations: () => [...teamKeys.all, 'my-invitations'] as const,
|
myInvitations: () => [...teamKeys.all, 'my-invitations'] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
// API response types
|
|
||||||
interface TeamMember {
|
|
||||||
id: string;
|
|
||||||
team_id: string;
|
|
||||||
user_id: string;
|
|
||||||
role: string;
|
|
||||||
status: string;
|
|
||||||
joined_at: string;
|
|
||||||
user?: {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
fullname: string;
|
|
||||||
avatar: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Team {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
logo?: string;
|
|
||||||
banner?: string;
|
|
||||||
description?: string;
|
|
||||||
city?: string;
|
|
||||||
visibility: string;
|
|
||||||
leader_id: string;
|
|
||||||
created_at: string;
|
|
||||||
leader?: {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
fullname: string;
|
|
||||||
avatar: string;
|
|
||||||
};
|
|
||||||
members?: TeamMember[];
|
|
||||||
member_count?: number;
|
|
||||||
has_submission?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface JoinRequest {
|
|
||||||
id: string;
|
|
||||||
team_id: string;
|
|
||||||
user_id: string;
|
|
||||||
message?: string;
|
|
||||||
status: string;
|
|
||||||
created_at: string;
|
|
||||||
user?: {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
fullname: string;
|
|
||||||
avatar: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Invitation {
|
|
||||||
id: string;
|
|
||||||
team_id: string;
|
|
||||||
inviter_id: string;
|
|
||||||
invitee_email: string;
|
|
||||||
invitee_id?: string;
|
|
||||||
status: string;
|
|
||||||
created_at: string;
|
|
||||||
team?: Team;
|
|
||||||
inviter?: {
|
|
||||||
id: string;
|
|
||||||
fullname: string;
|
|
||||||
email: string;
|
|
||||||
avatar: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Submission {
|
|
||||||
id: string;
|
|
||||||
team_id: string;
|
|
||||||
project_name: string;
|
|
||||||
description?: string;
|
|
||||||
repository_url?: string;
|
|
||||||
demo_url?: string;
|
|
||||||
video_url?: string;
|
|
||||||
presentation_url?: string;
|
|
||||||
status: string;
|
|
||||||
submitted_at?: string;
|
|
||||||
created_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// List response type with pagination
|
|
||||||
interface ListResponseWithMeta<T> {
|
|
||||||
message: string;
|
|
||||||
data: T[];
|
|
||||||
meta: {
|
|
||||||
page: number;
|
|
||||||
per_page: number;
|
|
||||||
total_page: number;
|
|
||||||
total_data: number;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Team CRUD Hooks
|
// Team CRUD Hooks
|
||||||
export const useTeams = (params?: {
|
export const useTeams = (params?: {
|
||||||
page?: number;
|
page?: number;
|
||||||
@@ -125,78 +31,100 @@ export const useTeams = (params?: {
|
|||||||
city?: string;
|
city?: string;
|
||||||
visibility?: string;
|
visibility?: string;
|
||||||
search?: string;
|
search?: string;
|
||||||
minMembers?: number;
|
|
||||||
maxMembers?: number;
|
|
||||||
hasSubmission?: boolean;
|
|
||||||
}) => {
|
}) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: teamKeys.list(params),
|
queryKey: teamKeys.list(params),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const queryParams = new URLSearchParams();
|
try {
|
||||||
if (params?.page) queryParams.append('page', String(params.page));
|
// Supabase client now has auth context from setSession()
|
||||||
if (params?.limit) queryParams.append('per_page', String(params.limit));
|
let query = supabase.from('teams').select(`
|
||||||
if (params?.search) queryParams.append('search', params.search);
|
*,
|
||||||
if (params?.city) queryParams.append('city', params.city);
|
members:team_members(id)
|
||||||
if (params?.visibility) queryParams.append('visibility', params.visibility);
|
`);
|
||||||
if (params?.minMembers) queryParams.append('min_members', String(params.minMembers));
|
|
||||||
if (params?.maxMembers) queryParams.append('max_members', String(params.maxMembers));
|
|
||||||
if (params?.hasSubmission !== undefined) queryParams.append('has_submission', String(params.hasSubmission));
|
|
||||||
|
|
||||||
const response = await hackathonApi.get<ListResponseWithMeta<Team>>(
|
// Filter by visibility
|
||||||
`/teams/browse${queryParams.toString() ? `?${queryParams.toString()}` : ''}`
|
if (params?.visibility) {
|
||||||
);
|
query = query.eq('visibility', params.visibility);
|
||||||
|
}
|
||||||
|
|
||||||
const { data, meta } = response.data;
|
// Filter by city
|
||||||
return {
|
if (params?.city) {
|
||||||
teams: data || [],
|
query = query.eq('city', params.city);
|
||||||
total: meta?.total_data || 0,
|
}
|
||||||
page: meta?.page || 1,
|
|
||||||
perPage: meta?.per_page || 12,
|
// Search by name
|
||||||
totalPages: meta?.total_page || 1,
|
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: [] };
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Infinite scroll teams hook
|
|
||||||
const TEAMS_PAGE_SIZE = 12;
|
|
||||||
|
|
||||||
export const useInfiniteTeams = (params?: {
|
|
||||||
city?: string;
|
|
||||||
visibility?: string;
|
|
||||||
search?: string;
|
|
||||||
}) => {
|
|
||||||
return useInfiniteQuery({
|
|
||||||
queryKey: [...teamKeys.lists(), 'infinite', params],
|
|
||||||
queryFn: async ({ pageParam = 1 }) => {
|
|
||||||
const queryParams = new URLSearchParams();
|
|
||||||
queryParams.append('page', String(pageParam));
|
|
||||||
queryParams.append('limit', String(TEAMS_PAGE_SIZE));
|
|
||||||
if (params?.search) queryParams.append('search', params.search);
|
|
||||||
if (params?.city) queryParams.append('city', params.city);
|
|
||||||
if (params?.visibility) queryParams.append('visibility', params.visibility);
|
|
||||||
|
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<Team[]>>(
|
|
||||||
`/teams/browse?${queryParams.toString()}`
|
|
||||||
);
|
|
||||||
|
|
||||||
const teams = response.data.data || [];
|
|
||||||
return {
|
|
||||||
data: teams,
|
|
||||||
nextPage: teams.length === TEAMS_PAGE_SIZE ? pageParam + 1 : undefined,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
initialPageParam: 1,
|
|
||||||
getNextPageParam: (lastPage) => lastPage.nextPage,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useTeamById = (teamId: string, enabled = true) => {
|
export const useTeamById = (teamId: string, enabled = true) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: teamKeys.detail(teamId),
|
queryKey: teamKeys.detail(teamId),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<Team>>(`/teams/${teamId}`);
|
// Supabase client now has auth context from setSession()
|
||||||
return { data: response.data.data };
|
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,
|
enabled: enabled && !!teamId,
|
||||||
});
|
});
|
||||||
@@ -212,16 +140,50 @@ export const useCreateTeam = () => {
|
|||||||
throw new Error('You must be logged in to create a team');
|
throw new Error('You must be logged in to create a team');
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<Team>>('/teams', {
|
// Supabase client now has auth context from setSession()
|
||||||
|
const { data: team, error: teamError } = await supabase
|
||||||
|
.from('teams')
|
||||||
|
.insert({
|
||||||
name: data.name,
|
name: data.name,
|
||||||
logo: data.logo,
|
logo: data.logo,
|
||||||
banner: data.banner,
|
banner: data.banner,
|
||||||
description: data.description,
|
description: data.description,
|
||||||
city: data.city,
|
city: data.city,
|
||||||
visibility: data.visibility,
|
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',
|
||||||
});
|
});
|
||||||
|
|
||||||
return { data: response.data.data };
|
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: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
||||||
@@ -240,16 +202,27 @@ export const useUpdateTeam = (teamId: string) => {
|
|||||||
throw new Error('You must be logged in to update a team');
|
throw new Error('You must be logged in to update a team');
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await hackathonApi.put<HackathonApiResponse<Team>>(`/teams/${teamId}`, {
|
// Supabase client now has auth context from setSession()
|
||||||
|
const { data: team, error } = await supabase
|
||||||
|
.from('teams')
|
||||||
|
.update({
|
||||||
name: data.name,
|
name: data.name,
|
||||||
logo: data.logo,
|
logo: data.logo,
|
||||||
banner: data.banner,
|
banner: data.banner,
|
||||||
description: data.description,
|
description: data.description,
|
||||||
city: data.city,
|
city: data.city,
|
||||||
visibility: data.visibility,
|
visibility: data.visibility,
|
||||||
});
|
})
|
||||||
|
.eq('id', teamId)
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
return { data: response.data.data };
|
if (error) {
|
||||||
|
console.error('Failed to update team:', error);
|
||||||
|
throw new Error(error.message || 'Failed to update team');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { data: team };
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
||||||
@@ -258,13 +231,32 @@ export const useUpdateTeam = (teamId: string) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Team Members Hooks - using team detail endpoint which includes members
|
// Team Members Hooks
|
||||||
export const useTeamMembers = (teamId: string, enabled = true) => {
|
export const useTeamMembers = (teamId: string, enabled = true) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: teamKeys.members(teamId),
|
queryKey: teamKeys.members(teamId),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<Team>>(`/teams/${teamId}`);
|
// Supabase client now has auth context from setSession()
|
||||||
return { data: response.data.data?.members || [] };
|
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,
|
enabled: enabled && !!teamId,
|
||||||
});
|
});
|
||||||
@@ -280,12 +272,24 @@ export const useInviteMember = (teamId: string) => {
|
|||||||
throw new Error('You must be logged in to invite a member');
|
throw new Error('You must be logged in to invite a member');
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<Invitation>>(
|
// Insert invitation into team_invitations table
|
||||||
`/teams/${teamId}/invite`,
|
const { data: invitation, error } = await supabase
|
||||||
{ invitee_email: data.email }
|
.from('team_invitations')
|
||||||
);
|
.insert({
|
||||||
|
team_id: teamId,
|
||||||
|
inviter_id: session.user.id,
|
||||||
|
invitee_email: data.email,
|
||||||
|
status: 'pending',
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
return { data: response.data.data };
|
if (error) {
|
||||||
|
console.error('Failed to create invitation:', error);
|
||||||
|
throw new Error(error.message || 'Failed to send invitation');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { data: invitation };
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
||||||
@@ -297,11 +301,8 @@ export const useManageMember = (teamId: string) => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async ({ userId, data }: { userId: string; data: { role?: string; status?: string } }) => {
|
mutationFn: ({ userId, data }: { userId: string; data: any }) =>
|
||||||
// This endpoint may not exist in the backend yet
|
teamsApi.manageMember(teamId, userId, data),
|
||||||
// For now, we'll throw an error indicating it's not implemented
|
|
||||||
throw new Error('Manage member functionality not yet implemented in backend');
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
queryClient.invalidateQueries({ queryKey: teamKeys.members(teamId) });
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
queryClient.invalidateQueries({ queryKey: teamKeys.detail(teamId) });
|
||||||
@@ -319,7 +320,38 @@ export const useRemoveMember = (teamId: string) => {
|
|||||||
throw new Error('You must be logged in to remove a member');
|
throw new Error('You must be logged in to remove a member');
|
||||||
}
|
}
|
||||||
|
|
||||||
await hackathonApi.delete(`/teams/${teamId}/members/${userId}`);
|
// Verify the current user is the team leader
|
||||||
|
const { data: team, error: teamError } = await supabase
|
||||||
|
.from('teams')
|
||||||
|
.select('leader_id')
|
||||||
|
.eq('id', teamId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (teamError || !team) {
|
||||||
|
throw new Error('Team not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (team.leader_id !== session.user.id) {
|
||||||
|
throw new Error('Only the team leader can remove members');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cannot remove the leader
|
||||||
|
if (userId === team.leader_id) {
|
||||||
|
throw new Error('Cannot remove the team leader');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the team member record
|
||||||
|
const { error: deleteError } = await supabase
|
||||||
|
.from('team_members')
|
||||||
|
.delete()
|
||||||
|
.eq('team_id', teamId)
|
||||||
|
.eq('user_id', userId);
|
||||||
|
|
||||||
|
if (deleteError) {
|
||||||
|
console.error('Failed to remove member:', deleteError);
|
||||||
|
throw new Error(deleteError.message || 'Failed to remove member');
|
||||||
|
}
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
@@ -340,12 +372,24 @@ export const useJoinTeam = () => {
|
|||||||
throw new Error('You must be logged in to join a team');
|
throw new Error('You must be logged in to join a team');
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<JoinRequest>>(
|
// Insert join request into team_join_requests table
|
||||||
`/join-requests/teams/${teamId}`,
|
const { data: joinRequest, error } = await supabase
|
||||||
{ message: data.message }
|
.from('team_join_requests')
|
||||||
);
|
.insert({
|
||||||
|
team_id: teamId,
|
||||||
|
user_id: session.user.id,
|
||||||
|
message: data.message,
|
||||||
|
status: 'pending',
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
return { data: response.data.data };
|
if (error) {
|
||||||
|
console.error('Failed to create join request:', error);
|
||||||
|
throw new Error(error.message || 'Failed to send join request');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { data: joinRequest };
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
||||||
@@ -357,10 +401,28 @@ export const useTeamJoinRequests = (teamId: string, enabled = true) => {
|
|||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: teamKeys.joinRequests(teamId),
|
queryKey: teamKeys.joinRequests(teamId),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<JoinRequest[]>>(
|
// Fetch join requests with user information
|
||||||
`/join-requests/teams/${teamId}/pending`
|
const { data: requests, error } = await supabase
|
||||||
);
|
.from('team_join_requests')
|
||||||
return { data: response.data.data || [] };
|
.select(`
|
||||||
|
id,
|
||||||
|
team_id,
|
||||||
|
user_id,
|
||||||
|
message,
|
||||||
|
status,
|
||||||
|
created_at,
|
||||||
|
user:users(id, email, fullname, avatar)
|
||||||
|
`)
|
||||||
|
.eq('team_id', teamId)
|
||||||
|
.eq('status', 'pending')
|
||||||
|
.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,
|
enabled: enabled && !!teamId,
|
||||||
});
|
});
|
||||||
@@ -376,14 +438,76 @@ export const useRespondToJoinRequest = (teamId: string) => {
|
|||||||
throw new Error('You must be logged in to respond to join requests');
|
throw new Error('You must be logged in to respond to join requests');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Backend uses 'accept' instead of 'approve'
|
// First, get the join request details
|
||||||
const backendAction = action === 'approve' ? 'accept' : 'reject';
|
const { data: joinRequest, error: fetchError } = await supabase
|
||||||
|
.from('team_join_requests')
|
||||||
|
.select('id, team_id, user_id, status')
|
||||||
|
.eq('id', requestId)
|
||||||
|
.single();
|
||||||
|
|
||||||
await hackathonApi.post(`/join-requests/${requestId}/respond`, {
|
if (fetchError || !joinRequest) {
|
||||||
action: backendAction,
|
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',
|
||||||
});
|
});
|
||||||
|
|
||||||
return { success: true, action };
|
if (memberError) {
|
||||||
|
// If member creation fails, rollback join request update
|
||||||
|
await supabase
|
||||||
|
.from('team_join_requests')
|
||||||
|
.update({ status: 'pending' })
|
||||||
|
.eq('id', requestId);
|
||||||
|
|
||||||
|
// Parse Supabase error for user-friendly message
|
||||||
|
let errorMsg = memberError.message;
|
||||||
|
if (errorMsg.includes('Team already has 5 members') || errorMsg.includes('Team cannot have more than 5 members')) {
|
||||||
|
errorMsg = 'Team is full! Maximum 5 members allowed.';
|
||||||
|
} else if (errorMsg.includes('already in a team') || errorMsg.includes('User is already in a team')) {
|
||||||
|
errorMsg = 'This user is already in another team.';
|
||||||
|
} else if (errorMsg.includes('Bulk insert')) {
|
||||||
|
errorMsg = 'Invalid operation detected.';
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(errorMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
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: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.joinRequests(teamId) });
|
queryClient.invalidateQueries({ queryKey: teamKeys.joinRequests(teamId) });
|
||||||
@@ -400,10 +524,49 @@ export const useMyInvitations = () => {
|
|||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: teamKeys.myInvitations(),
|
queryKey: teamKeys.myInvitations(),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<Invitation[]>>('/invitations/my');
|
if (!session?.user?.email) {
|
||||||
return { data: response.data.data || [] };
|
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?.id,
|
enabled: !!session?.user?.email,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -417,9 +580,75 @@ export const useRespondToInvitation = () => {
|
|||||||
throw new Error('User not authenticated');
|
throw new Error('User not authenticated');
|
||||||
}
|
}
|
||||||
|
|
||||||
await hackathonApi.post(`/invitations/${invitationId}/respond`, { action });
|
// 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();
|
||||||
|
|
||||||
return { success: true, action };
|
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: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.myInvitations() });
|
queryClient.invalidateQueries({ queryKey: teamKeys.myInvitations() });
|
||||||
@@ -436,10 +665,38 @@ export const useMyTeams = () => {
|
|||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: teamKeys.myTeams(),
|
queryKey: teamKeys.myTeams(),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<any[]>>('/teams/my');
|
if (!session?.user?.id) {
|
||||||
const rawData = response.data.data || [];
|
return { data: [] };
|
||||||
// Unwrap nested team data if present (API returns [{team: {...}}] or [{id, name, ...}])
|
}
|
||||||
const teams = rawData.map((item: any) => item.team || item);
|
|
||||||
|
// 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 };
|
return { data: teams };
|
||||||
},
|
},
|
||||||
enabled: !!session?.user?.id,
|
enabled: !!session?.user?.id,
|
||||||
@@ -452,60 +709,7 @@ export const useSubmitProject = (teamId: string) => {
|
|||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (data: TSubmitProjectRequest) => {
|
mutationFn: async (data: TSubmitProjectRequest) => {
|
||||||
let submissionId: string;
|
return await teamsApi.submitProject(teamId, data);
|
||||||
|
|
||||||
// First, check if submission exists
|
|
||||||
try {
|
|
||||||
const existingResponse = await hackathonApi.get<HackathonApiResponse<Submission | null>>(
|
|
||||||
`/submissions/teams/${teamId}`
|
|
||||||
);
|
|
||||||
|
|
||||||
if (existingResponse.data.data?.id) {
|
|
||||||
// Update existing submission
|
|
||||||
const response = await hackathonApi.put<HackathonApiResponse<Submission>>(
|
|
||||||
`/submissions/${existingResponse.data.data.id}`,
|
|
||||||
{
|
|
||||||
project_name: data.project_name,
|
|
||||||
description: data.description,
|
|
||||||
repository_url: data.repository_url,
|
|
||||||
demo_url: data.demo_url,
|
|
||||||
video_url: data.video_url,
|
|
||||||
presentation_url: data.presentation_url,
|
|
||||||
screenshots: data.screenshots,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
submissionId = response.data.data.id;
|
|
||||||
} else {
|
|
||||||
throw new Error('No existing submission');
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// No existing submission, create new one
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<Submission>>(
|
|
||||||
`/submissions/teams/${teamId}`,
|
|
||||||
{
|
|
||||||
project_name: data.project_name,
|
|
||||||
description: data.description,
|
|
||||||
repository_url: data.repository_url,
|
|
||||||
demo_url: data.demo_url,
|
|
||||||
video_url: data.video_url,
|
|
||||||
presentation_url: data.presentation_url,
|
|
||||||
screenshots: data.screenshots,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
submissionId = response.data.data.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 2: Submit the project (draft -> pending_verification)
|
|
||||||
await hackathonApi.post<HackathonApiResponse<Submission>>(
|
|
||||||
`/submissions/${submissionId}/submit`
|
|
||||||
);
|
|
||||||
|
|
||||||
// Step 3: Confirm the submission (pending_verification -> submitted)
|
|
||||||
const finalResponse = await hackathonApi.post<HackathonApiResponse<Submission>>(
|
|
||||||
`/submissions/${submissionId}/confirm`
|
|
||||||
);
|
|
||||||
|
|
||||||
return { data: finalResponse.data.data };
|
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.submission(teamId) });
|
queryClient.invalidateQueries({ queryKey: teamKeys.submission(teamId) });
|
||||||
@@ -518,10 +722,8 @@ export const useTeamSubmission = (teamId: string, enabled = true) => {
|
|||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: teamKeys.submission(teamId),
|
queryKey: teamKeys.submission(teamId),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<Submission | null>>(
|
const submission = await teamsApi.getTeamSubmission(teamId);
|
||||||
`/submissions/teams/${teamId}`
|
return { data: submission };
|
||||||
);
|
|
||||||
return { data: response.data.data };
|
|
||||||
},
|
},
|
||||||
enabled: enabled && !!teamId,
|
enabled: enabled && !!teamId,
|
||||||
});
|
});
|
||||||
@@ -530,17 +732,10 @@ export const useTeamSubmission = (teamId: string, enabled = true) => {
|
|||||||
// Leave Team Hook
|
// Leave Team Hook
|
||||||
export const useLeaveTeam = () => {
|
export const useLeaveTeam = () => {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { session } = useAuthStore();
|
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (teamId: string) => {
|
mutationFn: async (teamId: string) => {
|
||||||
if (!session?.user?.id) {
|
return await teamsApi.leaveTeam(teamId);
|
||||||
throw new Error('You must be logged in to leave a team');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use the dedicated leave team endpoint
|
|
||||||
await hackathonApi.post(`/teams/${teamId}/leave`);
|
|
||||||
return { success: true };
|
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.myTeams() });
|
queryClient.invalidateQueries({ queryKey: teamKeys.myTeams() });
|
||||||
@@ -549,36 +744,43 @@ export const useLeaveTeam = () => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Delete Team Hook (Leader only)
|
// Get Teams by User ID
|
||||||
export const useDeleteTeam = () => {
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const { session } = useAuthStore();
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async (teamId: string) => {
|
|
||||||
if (!session?.user?.id) {
|
|
||||||
throw new Error('You must be logged in to delete a team');
|
|
||||||
}
|
|
||||||
|
|
||||||
await hackathonApi.delete(`/teams/${teamId}`);
|
|
||||||
return { success: true };
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.myTeams() });
|
|
||||||
queryClient.invalidateQueries({ queryKey: teamKeys.lists() });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get Teams by User ID - uses /users/{user_id}/teams
|
|
||||||
export const useTeamsByUserId = (userId: string) => {
|
export const useTeamsByUserId = (userId: string) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['teams-by-user', userId],
|
queryKey: ['teams-by-user', userId],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<any[]>>(`/users/${userId}/teams`);
|
if (!userId) {
|
||||||
const rawData = response.data.data || [];
|
return { data: [] };
|
||||||
// Unwrap nested team data if present (API returns [{team: {...}}] or [{id, name, ...}])
|
}
|
||||||
const teams = rawData.map((item: any) => item.team || item);
|
|
||||||
|
// 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', userId)
|
||||||
|
.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 };
|
return { data: teams };
|
||||||
},
|
},
|
||||||
enabled: !!userId,
|
enabled: !!userId,
|
||||||
|
|||||||
@@ -1,27 +1,8 @@
|
|||||||
import { useMutation } from '@tanstack/react-query';
|
import { useMutation } from '@tanstack/react-query';
|
||||||
import { hackathonApi, HackathonApiResponse } from '../../api/hackathon';
|
import { supabase, getAuthenticatedClient } from '../../supabase';
|
||||||
import { useAuthStore } from '../auth';
|
import { useAuthStore } from '../auth';
|
||||||
|
|
||||||
// Upload response type from backend
|
// Supabase Storage-based upload hooks
|
||||||
interface UploadResponse {
|
|
||||||
url: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper function to convert File to base64
|
|
||||||
const fileToBase64 = (file: File): Promise<string> => {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.readAsDataURL(file);
|
|
||||||
reader.onload = () => {
|
|
||||||
// Remove the data:image/xxx;base64, prefix
|
|
||||||
const base64 = (reader.result as string).split(',')[1];
|
|
||||||
resolve(base64);
|
|
||||||
};
|
|
||||||
reader.onerror = (error) => reject(error);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Backend API-based upload hooks
|
|
||||||
|
|
||||||
export const useUploadFile = () => {
|
export const useUploadFile = () => {
|
||||||
const { session } = useAuthStore();
|
const { session } = useAuthStore();
|
||||||
@@ -33,18 +14,30 @@ export const useUploadFile = () => {
|
|||||||
throw new Error('You must be logged in to upload files');
|
throw new Error('You must be logged in to upload files');
|
||||||
}
|
}
|
||||||
|
|
||||||
const base64Data = await fileToBase64(file);
|
// Generate a unique file name
|
||||||
|
const fileExt = file.name.split('.').pop();
|
||||||
|
const fileName = `${session.user.id}-${Date.now()}.${fileExt}`;
|
||||||
|
const filePath = `teams/${fileName}`;
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<UploadResponse>>(
|
// Supabase client now has auth context from setSession()
|
||||||
'/upload/team',
|
const { error } = await supabase.storage
|
||||||
{
|
.from('hackathon-uploads')
|
||||||
filename: file.name,
|
.upload(filePath, file, {
|
||||||
content_type: file.type,
|
cacheControl: '3600',
|
||||||
data: base64Data,
|
upsert: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Failed to upload file:', error);
|
||||||
|
throw new Error(error.message || 'Failed to upload file');
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
|
||||||
return { data: { url: response.data.data.url } };
|
// Get public URL
|
||||||
|
const { data: publicUrlData } = supabase.storage
|
||||||
|
.from('hackathon-uploads')
|
||||||
|
.getPublicUrl(filePath);
|
||||||
|
|
||||||
|
return { data: { url: publicUrlData.publicUrl } };
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -59,131 +52,34 @@ export const useUploadAvatar = () => {
|
|||||||
throw new Error('You must be logged in to upload avatar');
|
throw new Error('You must be logged in to upload avatar');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate file type
|
// Generate a unique file name
|
||||||
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
|
const fileExt = file.name.split('.').pop();
|
||||||
if (!allowedTypes.includes(file.type)) {
|
const fileName = `${session.user.id}-${Date.now()}.${fileExt}`;
|
||||||
throw new Error('Invalid file type. Allowed types: JPEG, PNG, WebP, GIF');
|
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');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate file size (max 5MB)
|
// Get public URL
|
||||||
const maxSize = 5 * 1024 * 1024;
|
const { data: publicUrlData } = supabase.storage
|
||||||
if (file.size > maxSize) {
|
.from('hackathon-uploads')
|
||||||
throw new Error('File too large. Maximum size: 5MB');
|
.getPublicUrl(filePath);
|
||||||
}
|
|
||||||
|
|
||||||
const base64Data = await fileToBase64(file);
|
return { data: { url: publicUrlData.publicUrl } };
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<UploadResponse>>(
|
|
||||||
'/upload/avatar',
|
|
||||||
{
|
|
||||||
filename: file.name,
|
|
||||||
content_type: file.type,
|
|
||||||
data: base64Data,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return { data: { url: response.data.data.url } };
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useUploadTeamFile = () => {
|
|
||||||
const { session } = useAuthStore();
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationKey: ['upload-team-file'],
|
|
||||||
mutationFn: async (file: File) => {
|
|
||||||
if (!session?.user?.id) {
|
|
||||||
throw new Error('You must be logged in to upload files');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file type
|
|
||||||
const allowedTypes = [
|
|
||||||
'image/jpeg',
|
|
||||||
'image/jpg',
|
|
||||||
'image/png',
|
|
||||||
'image/webp',
|
|
||||||
'image/gif',
|
|
||||||
'application/pdf',
|
|
||||||
];
|
|
||||||
if (!allowedTypes.includes(file.type)) {
|
|
||||||
throw new Error('Invalid file type. Allowed types: JPEG, PNG, WebP, GIF, PDF');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file size (max 20MB)
|
|
||||||
const maxSize = 20 * 1024 * 1024;
|
|
||||||
if (file.size > maxSize) {
|
|
||||||
throw new Error('File too large. Maximum size: 20MB');
|
|
||||||
}
|
|
||||||
|
|
||||||
const base64Data = await fileToBase64(file);
|
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<UploadResponse>>(
|
|
||||||
'/upload/team',
|
|
||||||
{
|
|
||||||
filename: file.name,
|
|
||||||
content_type: file.type,
|
|
||||||
data: base64Data,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return { data: { url: response.data.data.url } };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useUploadSubmission = () => {
|
|
||||||
const { session } = useAuthStore();
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationKey: ['upload-submission'],
|
|
||||||
mutationFn: async (file: File) => {
|
|
||||||
if (!session?.user?.id) {
|
|
||||||
throw new Error('You must be logged in to upload submissions');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file type
|
|
||||||
const allowedTypes = [
|
|
||||||
'image/jpeg',
|
|
||||||
'image/jpg',
|
|
||||||
'image/png',
|
|
||||||
'image/webp',
|
|
||||||
'image/gif',
|
|
||||||
'application/pdf',
|
|
||||||
'application/zip',
|
|
||||||
'application/x-zip-compressed',
|
|
||||||
'video/mp4',
|
|
||||||
'video/webm',
|
|
||||||
];
|
|
||||||
if (!allowedTypes.includes(file.type)) {
|
|
||||||
throw new Error(
|
|
||||||
'Invalid file type. Allowed types: Images, PDF, ZIP, MP4, WebM'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file size (max 50MB)
|
|
||||||
const maxSize = 50 * 1024 * 1024;
|
|
||||||
if (file.size > maxSize) {
|
|
||||||
throw new Error('File too large. Maximum size: 50MB');
|
|
||||||
}
|
|
||||||
|
|
||||||
const base64Data = await fileToBase64(file);
|
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<UploadResponse>>(
|
|
||||||
'/upload/submission',
|
|
||||||
{
|
|
||||||
filename: file.name,
|
|
||||||
content_type: file.type,
|
|
||||||
data: base64Data,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return { data: { url: response.data.data.url } };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Keep useUploadCV for compatibility, using team upload endpoint
|
|
||||||
export const useUploadCV = () => {
|
export const useUploadCV = () => {
|
||||||
const { session } = useAuthStore();
|
const { session } = useAuthStore();
|
||||||
|
|
||||||
@@ -194,29 +90,30 @@ export const useUploadCV = () => {
|
|||||||
throw new Error('You must be logged in to upload CV');
|
throw new Error('You must be logged in to upload CV');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate file type
|
// Generate a unique file name
|
||||||
if (file.type !== 'application/pdf') {
|
const fileExt = file.name.split('.').pop();
|
||||||
throw new Error('CV must be a PDF file');
|
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');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate file size (max 20MB)
|
// Get public URL
|
||||||
const maxSize = 20 * 1024 * 1024;
|
const { data: publicUrlData } = supabase.storage
|
||||||
if (file.size > maxSize) {
|
.from('hackathon-uploads')
|
||||||
throw new Error('File too large. Maximum size: 20MB');
|
.getPublicUrl(filePath);
|
||||||
}
|
|
||||||
|
|
||||||
const base64Data = await fileToBase64(file);
|
return { data: { url: publicUrlData.publicUrl } };
|
||||||
|
|
||||||
const response = await hackathonApi.post<HackathonApiResponse<UploadResponse>>(
|
|
||||||
'/upload/team',
|
|
||||||
{
|
|
||||||
filename: file.name,
|
|
||||||
content_type: file.type,
|
|
||||||
data: base64Data,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return { data: { url: response.data.data.url } };
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,41 +1,17 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { hackathonApi, HackathonApiResponse } from '../../api/hackathon';
|
import { userService } from '../../api/users';
|
||||||
|
import { supabase, getAuthenticatedClient } from '../../supabase';
|
||||||
import { useAuthStore } from '../auth';
|
import { useAuthStore } from '../auth';
|
||||||
|
|
||||||
// User type
|
// Supabase-based user hooks
|
||||||
interface User {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
fullname: string;
|
|
||||||
bio?: string;
|
|
||||||
location?: string;
|
|
||||||
avatar?: string;
|
|
||||||
skills?: string[];
|
|
||||||
created_at: string;
|
|
||||||
updated_at?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update user request type
|
|
||||||
interface UpdateUserRequest {
|
|
||||||
fullname?: string;
|
|
||||||
bio?: string;
|
|
||||||
location?: string;
|
|
||||||
avatar?: string;
|
|
||||||
skills?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend API-based user hooks
|
|
||||||
|
|
||||||
export const useUserMe = () => {
|
export const useUserMe = () => {
|
||||||
const { session } = useAuthStore();
|
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['user-me'],
|
queryKey: ['user-me'],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<User>>('/users/me');
|
const user = await userService.getUserMe();
|
||||||
return { data: response.data.data };
|
return { data: user };
|
||||||
},
|
},
|
||||||
enabled: !!session?.user?.id,
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -43,8 +19,8 @@ export const useUserById = (id: string) => {
|
|||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['user-by-id', id],
|
queryKey: ['user-by-id', id],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<User>>(`/users/${id}`);
|
const user = await userService.getUserById(id);
|
||||||
return { data: response.data.data };
|
return { data: user };
|
||||||
},
|
},
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
});
|
});
|
||||||
@@ -56,24 +32,35 @@ export const useUpdateUserMe = () => {
|
|||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationKey: ['update-user-me'],
|
mutationKey: ['update-user-me'],
|
||||||
mutationFn: async (data: UpdateUserRequest) => {
|
mutationFn: async (data: any) => {
|
||||||
if (!session?.user?.id) {
|
if (!session?.user?.id) {
|
||||||
throw new Error('You must be logged in to update profile');
|
throw new Error('You must be logged in to update profile');
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await hackathonApi.put<HackathonApiResponse<User>>('/users/me', {
|
// Supabase client now has auth context from setSession()
|
||||||
|
const { data: updatedUser, error } = await supabase
|
||||||
|
.from('users')
|
||||||
|
.update({
|
||||||
fullname: data.fullname,
|
fullname: data.fullname,
|
||||||
bio: data.bio,
|
bio: data.bio,
|
||||||
location: data.location,
|
location: data.location,
|
||||||
avatar: data.avatar,
|
avatar: data.avatar,
|
||||||
skills: data.skills,
|
skills: data.skills,
|
||||||
});
|
updated_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq('id', session.user.id)
|
||||||
|
.select()
|
||||||
|
.single();
|
||||||
|
|
||||||
return { data: response.data.data };
|
if (error) {
|
||||||
|
console.error('Failed to update user profile:', error);
|
||||||
|
throw new Error(error.message || 'Failed to update profile');
|
||||||
|
}
|
||||||
|
return { data: updatedUser };
|
||||||
},
|
},
|
||||||
onSuccess: (result) => {
|
onSuccess: (result) => {
|
||||||
// Update Zustand session store with new user data
|
// Update Zustand session store with new user data
|
||||||
if (session?.user && result.data) {
|
if (session && result.data) {
|
||||||
setSession({
|
setSession({
|
||||||
token: session.token,
|
token: session.token,
|
||||||
user: {
|
user: {
|
||||||
@@ -96,11 +83,9 @@ export const useUpdateUserById = () => {
|
|||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationKey: ['update-user-by-id'],
|
mutationKey: ['update-user-by-id'],
|
||||||
mutationFn: async ({ id, data }: { id: string; data: UpdateUserRequest }) => {
|
mutationFn: async ({ id, data }: { id: string; data: any }) => {
|
||||||
// Note: This might not be supported by backend (only /users/me for updates)
|
const updated = await userService.updateUserById(id, data);
|
||||||
// Keeping for API compatibility but it will likely fail
|
return { data: updated };
|
||||||
const response = await hackathonApi.put<HackathonApiResponse<User>>(`/users/${id}`, data);
|
|
||||||
return { data: response.data.data };
|
|
||||||
},
|
},
|
||||||
onSuccess: (_, variables) => {
|
onSuccess: (_, variables) => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['user-by-id', variables.id] });
|
queryClient.invalidateQueries({ queryKey: ['user-by-id', variables.id] });
|
||||||
@@ -110,10 +95,19 @@ export const useUpdateUserById = () => {
|
|||||||
|
|
||||||
export const useUserDetailsById = (userId: string) => {
|
export const useUserDetailsById = (userId: string) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['user-details', userId],
|
queryKey: ['user-supabase', userId],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await hackathonApi.get<HackathonApiResponse<User>>(`/users/${userId}`);
|
const { data, error } = await supabase
|
||||||
return { data: response.data.data };
|
.from('users')
|
||||||
|
.select('*')
|
||||||
|
.eq('id', userId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(error.message || 'Failed to fetch user');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { data };
|
||||||
},
|
},
|
||||||
enabled: !!userId,
|
enabled: !!userId,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,5 +2,5 @@ export * from './api';
|
|||||||
export * from './hooks';
|
export * from './hooks';
|
||||||
export * from './types';
|
export * from './types';
|
||||||
export * from './schemas';
|
export * from './schemas';
|
||||||
|
export * from './supabase';
|
||||||
export * from './storage';
|
export * from './storage';
|
||||||
// Note: Supabase export removed - using backend API instead
|
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ export type TTeamItem = {
|
|||||||
city: string;
|
city: string;
|
||||||
visibility: ETeamVisibility;
|
visibility: ETeamVisibility;
|
||||||
leader_id: string;
|
leader_id: string;
|
||||||
member_count: number;
|
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
};
|
};
|
||||||
@@ -44,6 +43,7 @@ export type TTeamItem = {
|
|||||||
export type TTeamDetailItem = TTeamItem & {
|
export type TTeamDetailItem = TTeamItem & {
|
||||||
leader: TUserItem;
|
leader: TUserItem;
|
||||||
members: TTeamMemberItem[];
|
members: TTeamMemberItem[];
|
||||||
|
member_count: number;
|
||||||
has_submission: boolean;
|
has_submission: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -125,7 +125,6 @@ export type TSubmitProjectRequest = {
|
|||||||
description: string;
|
description: string;
|
||||||
repository_url: string;
|
repository_url: string;
|
||||||
demo_url?: string;
|
demo_url?: string;
|
||||||
video_url?: string;
|
|
||||||
presentation_url?: string;
|
presentation_url?: string;
|
||||||
screenshots?: string[];
|
screenshots?: string[];
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,257 +3,64 @@ import {
|
|||||||
AuditOutlined,
|
AuditOutlined,
|
||||||
BookOutlined,
|
BookOutlined,
|
||||||
CommentOutlined,
|
CommentOutlined,
|
||||||
DownOutlined,
|
|
||||||
InboxOutlined,
|
InboxOutlined,
|
||||||
LogoutOutlined,
|
LogoutOutlined,
|
||||||
ReadOutlined,
|
|
||||||
ReloadOutlined,
|
ReloadOutlined,
|
||||||
RightOutlined,
|
|
||||||
ScheduleOutlined,
|
ScheduleOutlined,
|
||||||
SettingOutlined,
|
SettingOutlined,
|
||||||
StockOutlined,
|
|
||||||
UsergroupAddOutlined,
|
UsergroupAddOutlined,
|
||||||
UserOutlined,
|
UserOutlined,
|
||||||
UserSwitchOutlined,
|
UserSwitchOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { Button } from '../../atoms';
|
import { Button } from '../../atoms';
|
||||||
import { FC, ReactElement, useState } from 'react';
|
import { FC, ReactElement } from 'react';
|
||||||
import { Link, useLocation } from 'react-router-dom';
|
import { Link, useLocation } from 'react-router-dom';
|
||||||
import { cn, For, useSession } from '@imphnen-frontend-service/utils';
|
import { cn, For, useSession } from '@imphnen-frontend-service/utils';
|
||||||
|
|
||||||
type MenuItem = {
|
const MENUS = [
|
||||||
label: string;
|
{ label: 'Dashboard & Set Gacha', href: '/dashboard', icon: <AppstoreOutlined className="text-[20px]" /> },
|
||||||
href?: string;
|
{ label: 'Dashboard - Dimentorin', href: '/dashboard-dimentorin', icon: <AppstoreOutlined className="text-[20px]" /> },
|
||||||
icon?: ReactElement;
|
{ label: 'Gacha Roll', href: '/gacha-roll', icon: <ReloadOutlined className="text-[20px]" /> },
|
||||||
children?: Array<{ label: string; href: string; icon?: ReactElement }>;
|
{ label: 'Permissions', href: '/permissions', icon: <UserSwitchOutlined className="text-[20px]" /> },
|
||||||
};
|
{ label: 'Roles', href: '/roles', icon: <UsergroupAddOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'Data Akun', href: '/accounts', icon: <UserOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'Validasi Transaksi', href: '/transactions', icon: <AuditOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'Data Pengiriman Hadiah', href: '/prizes', icon: <InboxOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'User - Dimentorin', href: '/users-dimentorin', icon: <UserSwitchOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'Session - Dimentorin', href: '/session-dimentorin', icon: <ScheduleOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'Content & Roadmap', href: '/roadmap-dimentorin', icon: <BookOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'Feedback & Review', href: '/feedback-review-dimentorin', icon: <CommentOutlined className="text-[20px]" /> },
|
||||||
|
{ label: 'Settings - Dimentorin', href: '/settings-dimentorin', icon: <SettingOutlined className="text-[20px]" /> },
|
||||||
|
]
|
||||||
|
|
||||||
const MENUS: MenuItem[] = [
|
export const BackofficeSidebar: FC = (): ReactElement => {
|
||||||
{
|
|
||||||
label: 'Hackathon',
|
|
||||||
icon: <StockOutlined className="text-p3" />,
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
label: 'Dashboard',
|
|
||||||
href: '/hackathon-dashboard',
|
|
||||||
icon: <AppstoreOutlined className="text-p3" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Users',
|
|
||||||
href: '/hackathon-users',
|
|
||||||
icon: <UserOutlined className="text-p3" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Teams',
|
|
||||||
href: '/hackathon-teams',
|
|
||||||
icon: <UsergroupAddOutlined className="text-p3" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Submissions',
|
|
||||||
href: '/hackathon-submissions',
|
|
||||||
icon: <AuditOutlined className="text-p3" />,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Dimentorin',
|
|
||||||
icon: <ReadOutlined className="text-p3" />,
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
label: 'Dashboard - Dimentorin',
|
|
||||||
href: '/dashboard-dimentorin',
|
|
||||||
icon: <AppstoreOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'User - Dimentorin',
|
|
||||||
href: '/users-dimentorin',
|
|
||||||
icon: <UserSwitchOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Session - Dimentorin',
|
|
||||||
href: '/session-dimentorin',
|
|
||||||
icon: <ScheduleOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Content & Roadmap',
|
|
||||||
href: '/roadmap-dimentorin',
|
|
||||||
icon: <BookOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Feedback & Review',
|
|
||||||
href: '/feedback-review-dimentorin',
|
|
||||||
icon: <CommentOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Settings - Dimentorin',
|
|
||||||
href: '/settings-dimentorin',
|
|
||||||
icon: <SettingOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Gacha',
|
|
||||||
icon: <ReloadOutlined className="text-[20px]" />,
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
label: 'Dashboard & Set Gacha',
|
|
||||||
href: '/dashboard',
|
|
||||||
icon: <AppstoreOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Gacha Roll',
|
|
||||||
href: '/gacha-roll',
|
|
||||||
icon: <ReloadOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Validasi Transaksi',
|
|
||||||
href: '/transactions',
|
|
||||||
icon: <AuditOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Data Pengiriman Hadiah',
|
|
||||||
href: '/prizes',
|
|
||||||
icon: <InboxOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Permissions',
|
|
||||||
href: '/permissions',
|
|
||||||
icon: <UserSwitchOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Roles',
|
|
||||||
href: '/roles',
|
|
||||||
icon: <UsergroupAddOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Data Akun',
|
|
||||||
href: '/accounts',
|
|
||||||
icon: <UserOutlined className="text-[20px]" />,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
interface SidebarProps {
|
|
||||||
isOpen?: boolean;
|
|
||||||
onClose?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const BackofficeSidebar: FC<SidebarProps> = ({
|
|
||||||
isOpen = false,
|
|
||||||
onClose,
|
|
||||||
}): ReactElement => {
|
|
||||||
const { signOut } = useSession();
|
const { signOut } = useSession();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>({});
|
|
||||||
const isActive = (path: string) => {
|
const isActive = (path: string) => {
|
||||||
if (path === '/dashboard' && location.pathname === '/dashboard-dimentorin')
|
if (path === '/dashboard' && location.pathname === '/dashboard-dimentorin') return false
|
||||||
return false;
|
return location.pathname.includes(path)
|
||||||
return location.pathname.includes(path);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleGroup = (groupLabel: string) => {
|
return (
|
||||||
setOpenGroups((prev) => ({ ...prev, [groupLabel]: !prev[groupLabel] }));
|
<aside className="sticky top-0 left-0 w-[280px] bg-white h-svh py-[60px] px-[28px] shadow-xl flex flex-col justify-between">
|
||||||
};
|
<div className="flex flex-col gap-20 justify-between items-center">
|
||||||
|
<img src="/logos/simple.svg" alt="IMPHNEN Logo" className="w-[150px]" />
|
||||||
const sidebarContent = (
|
|
||||||
<div className="w-[280px] bg-white h-svh py-10 lg:py-[60px] px-7 shadow-xl flex flex-col justify-between">
|
|
||||||
<div className="flex flex-col gap-10 lg:gap-20 justify-between items-center">
|
|
||||||
<div className="flex justify-around lg:justify-center items-center w-full">
|
|
||||||
<img
|
|
||||||
src="/logos/simple.svg"
|
|
||||||
alt="IMPHNEN Logo"
|
|
||||||
className="w-[150px]"
|
|
||||||
/>
|
|
||||||
{onClose && (
|
|
||||||
<button
|
|
||||||
onClick={onClose}
|
|
||||||
className="lg:hidden p-2 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
|
|
||||||
aria-label="Close sidebar"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
className="w-5 h-5 text-gray-500"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth={2}
|
|
||||||
d="M6 18L18 6M6 6l12 12"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="flex flex-col gap-4 w-full h-[calc(100svh-20rem)] overflow-y-auto">
|
<nav className="flex flex-col gap-4 w-full h-[calc(100svh-20rem)] overflow-y-auto">
|
||||||
<For data={MENUS}>
|
<For data={MENUS}>
|
||||||
{(menu) =>
|
{({ label, href, icon }) => (
|
||||||
menu.children && menu.children.length > 0 ? (
|
|
||||||
<div key={menu.label} className="w-full">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => toggleGroup(menu.label)}
|
|
||||||
className={cn(
|
|
||||||
'flex items-center justify-between w-full gap-3 px-2 py-2.5 rounded-md cursor-pointer',
|
|
||||||
openGroups[menu.label]
|
|
||||||
? 'bg-primary-400 hover:bg-primary-500 text-white'
|
|
||||||
: 'text-gray-700 hover:bg-gray-100'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
{menu.icon}
|
|
||||||
<span className="text-p3 font-medium">{menu.label}</span>
|
|
||||||
</div>
|
|
||||||
<span className="text-label2">
|
|
||||||
{openGroups[menu.label] ? (
|
|
||||||
<DownOutlined className="text-label1" />
|
|
||||||
) : (
|
|
||||||
<RightOutlined className="text-label1" />
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{openGroups[menu.label] && (
|
|
||||||
<div className="mt-2 ml-6 flex flex-col gap-2">
|
|
||||||
{menu.children.map((child) => (
|
|
||||||
<Link
|
<Link
|
||||||
key={child.href}
|
key={href}
|
||||||
to={child.href}
|
to={href}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex items-center gap-3 px-2 py-2.5 rounded-md',
|
"flex items-center justify-items-start gap-3 px-[8px] py-[10px]",
|
||||||
isActive(child.href)
|
isActive(href) ? "bg-primary-500 text-white rounded-md" : "text-gray-700 hover:bg-gray-100"
|
||||||
? 'bg-primary-100 text-primary-700 hover:bg-primary-200'
|
|
||||||
: 'text-gray-700 hover:bg-gray-100'
|
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{child.icon}
|
{icon}
|
||||||
<span className="text-label1 font-medium">
|
<span className="text-p3 font-medium">{label}</span>
|
||||||
{child.label}
|
|
||||||
</span>
|
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<Link
|
|
||||||
key={menu.href ?? menu.label}
|
|
||||||
to={menu.href ?? '#'}
|
|
||||||
className={cn(
|
|
||||||
'flex items-center justify-items-start gap-3 px-2 py-2.5',
|
|
||||||
menu.href && isActive(menu.href)
|
|
||||||
? 'bg-primary-500 text-white rounded-md'
|
|
||||||
: 'text-gray-700 hover:bg-gray-100'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{menu.icon}
|
|
||||||
<span className="text-p3 font-medium">{menu.label}</span>
|
|
||||||
</Link>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
</For>
|
</For>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
@@ -263,36 +70,12 @@ export const BackofficeSidebar: FC<SidebarProps> = ({
|
|||||||
<Button
|
<Button
|
||||||
onClick={signOut}
|
onClick={signOut}
|
||||||
variant="text"
|
variant="text"
|
||||||
className="items-start justify-start gap-3 px-2 py-2.5 text-gray-700 hover:text-red-500 transition-colors w-full"
|
className="items-start justify-start gap-3 px-[8px] py-[10px] text-gray-700 hover:text-red-500 transition-colors w-full"
|
||||||
>
|
>
|
||||||
<LogoutOutlined className="text-p3" />
|
<LogoutOutlined className="text-[20px]" />
|
||||||
<span className="text-p3 font-medium">Log Out</span>
|
<span className="text-p3 font-medium">Log Out</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</aside>
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{/* Desktop Sidebar - visible on lg+, sticky */}
|
|
||||||
<div className="hidden lg:block sticky top-0 h-screen overflow-y-auto shadow">
|
|
||||||
{sidebarContent}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Mobile Sidebar - overlay */}
|
|
||||||
{isOpen && (
|
|
||||||
<div className="lg:hidden fixed inset-0 z-50">
|
|
||||||
{/* Backdrop */}
|
|
||||||
<div
|
|
||||||
className="fixed inset-0 bg-black/50 transition-opacity"
|
|
||||||
onClick={onClose}
|
|
||||||
/>
|
|
||||||
{/* Sidebar */}
|
|
||||||
<div className="fixed inset-y-0 left-0 z-50 transform transition-transform duration-300 ease-in-out">
|
|
||||||
{sidebarContent}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,16 +1,15 @@
|
|||||||
import { cn } from '@imphnen-frontend-service/utils';
|
import { cn } from "@imphnen-frontend-service/utils"
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react'
|
||||||
import { FC, ReactElement, ReactNode } from 'react';
|
import { FC, ReactElement, ReactNode } from "react"
|
||||||
import { Button } from '../../atoms';
|
import { Button } from "../../atoms"
|
||||||
import { useAuthStore } from '@imphnen-frontend-service/service';
|
|
||||||
|
|
||||||
export type TBackofficeWrapperProps = {
|
export type TBackofficeWrapperProps = {
|
||||||
children: ReactNode;
|
children: ReactNode
|
||||||
title?: string;
|
title?: string
|
||||||
className?: string;
|
className?: string
|
||||||
classHeader?: string;
|
classHeader?: string
|
||||||
classTitle?: string;
|
classTitle?: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export const BackofficeWrapper: FC<TBackofficeWrapperProps> = ({
|
export const BackofficeWrapper: FC<TBackofficeWrapperProps> = ({
|
||||||
children,
|
children,
|
||||||
@@ -19,52 +18,34 @@ export const BackofficeWrapper: FC<TBackofficeWrapperProps> = ({
|
|||||||
classHeader,
|
classHeader,
|
||||||
classTitle,
|
classTitle,
|
||||||
}): ReactElement => {
|
}): ReactElement => {
|
||||||
const { session } = useAuthStore();
|
|
||||||
const user = session?.user;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main
|
<main className={cn("w-full px-[48px] py-[40px] flex flex-col gap-8", className)}>
|
||||||
className={cn(
|
<header className={cn("bg-white py-5 px-7 rounded-md shadow flex items-center justify-between", classHeader)}>
|
||||||
'w-full px-[48px] py-[40px] flex flex-col gap-8',
|
<h1 className={cn("text-[19px] text-primary-500 font-semibold", classTitle)}>{title}</h1>
|
||||||
className
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<header
|
|
||||||
className={cn(
|
|
||||||
'bg-white py-5 px-7 rounded-md shadow flex items-center justify-between',
|
|
||||||
classHeader
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<h1
|
|
||||||
className={cn(
|
|
||||||
'text-[19px] text-primary-500 font-semibold',
|
|
||||||
classTitle
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{title}
|
|
||||||
</h1>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-x-6">
|
<div className="flex items-center gap-x-6">
|
||||||
{/* <Button type="button" variant="secondary" className="max-h-full p-3">
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
className="max-h-full p-3"
|
||||||
|
>
|
||||||
<Icon icon="mdi:bell-outline" className="size-6" />
|
<Icon icon="mdi:bell-outline" className="size-6" />
|
||||||
</Button> */}
|
</Button>
|
||||||
<div className="flex items-center gap-x-6">
|
<div className="flex items-center gap-x-6">
|
||||||
<div className="text-neutral-600 font-medium">
|
<div className="text-neutral-600 font-medium">
|
||||||
<p className="text-p3">{user?.fullname || 'Full Name'}</p>
|
<p className="text-p3">Rizal Syaepulloh</p>
|
||||||
<p className="text-label1">Admin</p>
|
<p className="text-label1">Super Admin</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="size-12 rounded-full overflow-hidden">
|
<div className="size-12 rounded-full overflow-hidden">
|
||||||
<img
|
<img src="/images/asd687hwq6nds4dfjj2983.webp" alt="Profile" className="size-full object-cover" />
|
||||||
src={user?.avatar || '/images/asd687hwq6nds4dfjj2983.webp'}
|
|
||||||
alt="Profile"
|
|
||||||
className="size-full object-cover"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<section>{children}</section>
|
<section>
|
||||||
|
{children}
|
||||||
|
</section>
|
||||||
</main>
|
</main>
|
||||||
);
|
)
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,113 +1,57 @@
|
|||||||
import {
|
import {
|
||||||
PaginationState,
|
PaginationState,
|
||||||
SortingState,
|
|
||||||
useReactTable,
|
useReactTable,
|
||||||
getCoreRowModel,
|
getCoreRowModel,
|
||||||
getPaginationRowModel,
|
getPaginationRowModel,
|
||||||
getSortedRowModel,
|
|
||||||
getFilteredRowModel,
|
|
||||||
flexRender,
|
flexRender,
|
||||||
ColumnDef,
|
ColumnDef,
|
||||||
Table,
|
Table,
|
||||||
RowData,
|
RowData,
|
||||||
TableOptions,
|
|
||||||
} from '@tanstack/react-table';
|
} from '@tanstack/react-table';
|
||||||
import { Pagination } from '../../molecules';
|
import { Pagination } from '../../molecules';
|
||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { cn } from '@imphnen-frontend-service/utils';
|
import { cn } from '@imphnen-frontend-service/utils';
|
||||||
|
|
||||||
interface DataTableProps<T extends RowData> {
|
interface DataTableProps<T> {
|
||||||
table?: Table<T>;
|
data: T[];
|
||||||
data?: T[];
|
columns: ColumnDef<T>[];
|
||||||
columns?: ColumnDef<T, unknown>[];
|
table: Table<T>;
|
||||||
pageSize?: number;
|
pageSize?: number;
|
||||||
className?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DataTable = <T extends RowData>({
|
export const DataTable = <T extends RowData>({
|
||||||
table,
|
data,
|
||||||
data = [],
|
columns,
|
||||||
columns = [],
|
|
||||||
pageSize = 9,
|
pageSize = 9,
|
||||||
className,
|
|
||||||
}: DataTableProps<T>) => {
|
}: DataTableProps<T>) => {
|
||||||
const [pagination, setPagination] = React.useState<PaginationState>({
|
const [pagination, setPagination] = React.useState<PaginationState>({
|
||||||
pageIndex: 0,
|
pageIndex: 0,
|
||||||
pageSize,
|
pageSize,
|
||||||
});
|
});
|
||||||
const [sorting, setSorting] = React.useState<SortingState>([]);
|
|
||||||
|
|
||||||
// Update pagination state when pageSize prop changes
|
const table = useReactTable({
|
||||||
React.useEffect(() => {
|
data,
|
||||||
setPagination((prev) => ({
|
columns,
|
||||||
...prev,
|
|
||||||
pageSize,
|
|
||||||
}));
|
|
||||||
}, [pageSize]);
|
|
||||||
|
|
||||||
// Reset pagination when data changes to prevent out-of-bounds errors
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (data.length > 0) {
|
|
||||||
setPagination((prev) => ({
|
|
||||||
...prev,
|
|
||||||
pageIndex: 0, // Reset to first page when data changes
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}, [data.length]);
|
|
||||||
|
|
||||||
// Memoize data and columns to prevent unnecessary re-renders
|
|
||||||
const memoizedData = React.useMemo(() => data, [data]);
|
|
||||||
const memoizedColumns = React.useMemo(() => columns, [columns]);
|
|
||||||
|
|
||||||
// Memoize table configuration to prevent recreation on every render
|
|
||||||
const tableConfig = React.useMemo(() => {
|
|
||||||
const config: TableOptions<T> = {
|
|
||||||
data: memoizedData,
|
|
||||||
columns: memoizedColumns,
|
|
||||||
state: {
|
state: {
|
||||||
pagination,
|
pagination,
|
||||||
sorting,
|
|
||||||
},
|
},
|
||||||
onPaginationChange: setPagination,
|
|
||||||
onSortingChange: setSorting,
|
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
getPaginationRowModel: getPaginationRowModel(),
|
getPaginationRowModel: getPaginationRowModel(),
|
||||||
getSortedRowModel: getSortedRowModel(),
|
onPaginationChange: setPagination,
|
||||||
getFilteredRowModel: getFilteredRowModel(),
|
});
|
||||||
};
|
|
||||||
|
|
||||||
return config;
|
|
||||||
}, [memoizedData, memoizedColumns, pagination, sorting]);
|
|
||||||
|
|
||||||
// Prefer external table instance if provided; otherwise create an internal one
|
|
||||||
const internalTable = useReactTable(tableConfig);
|
|
||||||
const t = table ?? internalTable;
|
|
||||||
|
|
||||||
// Handle empty data state
|
|
||||||
const isEmpty = t.getRowModel().rows.length === 0;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn('flex flex-col gap-8', className)}>
|
<div className="flex flex-col gap-8">
|
||||||
<div className="w-full overflow-x-auto">
|
<div className="w-full overflow-x-auto">
|
||||||
<table className="w-full min-w-full text-base">
|
<table className="w-full min-w-full text-base">
|
||||||
<thead className="bg-primary-50 mb-3 text-left text-nowrap">
|
<thead className="bg-primary-50 mb-3 text-left text-nowrap">
|
||||||
{t.getHeaderGroups().map((headerGroup) => (
|
{table.getHeaderGroups().map((headerGroup) => (
|
||||||
<tr key={headerGroup.id}>
|
<tr key={headerGroup.id}>
|
||||||
{headerGroup.headers.map((header) => (
|
{headerGroup.headers.map((header) => (
|
||||||
<th
|
<th
|
||||||
key={header.id}
|
key={header.id}
|
||||||
onClick={
|
className={cn("py-4 px-5 font-normal first:rounded-l-lg last:rounded-r-lg", header?.column?.columnDef?.meta?.headerClassName)}
|
||||||
header.column.getCanSort()
|
|
||||||
? header.column.getToggleSortingHandler()
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
className={cn(
|
|
||||||
'py-4 px-5 font-normal first:rounded-l-lg last:rounded-r-lg',
|
|
||||||
header.column.getCanSort() &&
|
|
||||||
'cursor-pointer select-none hover:bg-primary-100 transition-colors',
|
|
||||||
header?.column?.columnDef?.meta?.headerClassName
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
{header.isPlaceholder
|
{header.isPlaceholder
|
||||||
? null
|
? null
|
||||||
@@ -115,58 +59,28 @@ export const DataTable = <T extends RowData>({
|
|||||||
header.column.columnDef.header,
|
header.column.columnDef.header,
|
||||||
header.getContext()
|
header.getContext()
|
||||||
)}
|
)}
|
||||||
{header.column.getCanSort() && (
|
|
||||||
<span className="ml-2 text-xs text-gray-500">
|
|
||||||
{header.column.getIsSorted() === 'asc' && '▲'}
|
|
||||||
{header.column.getIsSorted() === 'desc' && '▼'}
|
|
||||||
{!header.column.getIsSorted() && <span>⇅</span>}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</th>
|
</th>
|
||||||
))}
|
))}
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{isEmpty ? (
|
{table.getRowModel().rows.map((row) => (
|
||||||
<tr>
|
<tr key={row.id} className="bg-primary-100 odd:bg-white">
|
||||||
<td
|
{row.getVisibleCells().map((cell, index) => (
|
||||||
colSpan={t.getAllColumns().length}
|
|
||||||
className="py-8 px-5 text-center text-neutral-500"
|
|
||||||
>
|
|
||||||
No data available
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
|
||||||
t.getRowModel().rows.map((row, rowIndex) => (
|
|
||||||
<tr
|
|
||||||
key={row.id}
|
|
||||||
className={cn(
|
|
||||||
'hover:bg-primary-50 transition-colors',
|
|
||||||
rowIndex % 2 === 0 ? 'bg-white' : 'bg-primary-100'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{row.getVisibleCells().map((cell) => (
|
|
||||||
<td
|
<td
|
||||||
key={cell.id}
|
key={cell.id}
|
||||||
className={cn(
|
className={cn("py-3 px-5 first:rounded-l-lg last:rounded-r-lg", cell?.column?.columnDef?.meta?.cellClassName)}
|
||||||
'py-3 px-5 first:rounded-l-lg last:rounded-r-lg',
|
|
||||||
cell?.column?.columnDef?.meta?.cellClassName
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
{flexRender(
|
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||||
cell.column.columnDef.cell,
|
|
||||||
cell.getContext()
|
|
||||||
)}
|
|
||||||
</td>
|
</td>
|
||||||
))}
|
))}
|
||||||
</tr>
|
</tr>
|
||||||
))
|
))}
|
||||||
)}
|
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<Pagination table={t} />
|
<Pagination table={table} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useAuthStore } from '@imphnen-frontend-service/service';
|
import { supabase, useAuthStore } from '@imphnen-frontend-service/service';
|
||||||
import { useNavigate } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
|
|
||||||
export const useSession = () => {
|
export const useSession = () => {
|
||||||
@@ -6,9 +6,9 @@ export const useSession = () => {
|
|||||||
const { clearSession, session, status } = useAuthStore();
|
const { clearSession, session, status } = useAuthStore();
|
||||||
const isAuthenticated = status === 'authenticated';
|
const isAuthenticated = status === 'authenticated';
|
||||||
|
|
||||||
const signOut = () => {
|
const signOut = async () => {
|
||||||
|
await supabase.auth.signOut();
|
||||||
clearSession();
|
clearSession();
|
||||||
localStorage.clear();
|
|
||||||
navigate('/auth/login');
|
navigate('/auth/login');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user