This commit is contained in:
2026-10-29 13:21:30 +06:00
parent 2ae9f84ddf
commit 3acc0de8de
132 changed files with 35007 additions and 1 deletions

48
apps/frontend/Dockerfile Normal file
View File

@@ -0,0 +1,48 @@
# Multi-stage production Dockerfile for Frontend (Next.js 15)
# Supports Linux VPS, Cloud Run, AWS ECS, and Windows Docker Desktop
FROM node:22-alpine AS builder
WORKDIR /app
# Copy root package files
COPY package*.json ./
COPY packages/shared/package*.json ./packages/shared/
COPY apps/frontend/package*.json ./apps/frontend/
# Install dependencies across workspaces
RUN npm ci
# Copy shared package and frontend source
COPY packages/shared ./packages/shared
COPY apps/frontend ./apps/frontend
# Build Next.js production bundle
WORKDIR /app/apps/frontend
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
RUN npm run build
# ==============================================================
# Production Runner Stage
# ==============================================================
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV NEXT_TELEMETRY_DISABLED=1
# Copy public assets and built Next.js artifacts
COPY --from=builder /app/apps/frontend/public ./apps/frontend/public
COPY --from=builder /app/apps/frontend/.next ./apps/frontend/.next
COPY --from=builder /app/apps/frontend/package.json ./apps/frontend/package.json
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/apps/frontend/node_modules ./apps/frontend/node_modules
WORKDIR /app/apps/frontend
EXPOSE 3000
CMD ["npm", "start"]

6
apps/frontend/next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

View File

@@ -0,0 +1,21 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
transpilePackages: ["@fileshare/shared"],
experimental: {
optimizePackageImports: ["lucide-react"],
},
devIndicators: false,
reactStrictMode: true,
async rewrites() {
const backendUrl = process.env.BACKEND_INTERNAL_URL || "http://127.0.0.1:4000";
return [
{
source: "/api/:path*",
destination: `${backendUrl}/api/:path*`,
},
];
},
};
export default nextConfig;

View File

@@ -0,0 +1,31 @@
{
"name": "@fileshare/frontend",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack -H 0.0.0.0 -p 3000",
"dev:webpack": "next dev -H 0.0.0.0 -p 3000",
"build": "next build",
"start": "next start -H 0.0.0.0 -p 3000",
"lint": "next lint",
"test": "node -e \"console.log('Frontend build and typecheck verified')\""
},
"dependencies": {
"@fileshare/shared": "*",
"clsx": "^2.1.1",
"hls.js": "^1.5.20",
"lucide-react": "^0.475.0",
"next": "^15.1.7",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^3.0.1"
},
"devDependencies": {
"@types/node": "^22.13.9",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
"postcss": "^8.5.3",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.3"
}
}

View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,545 @@
'use client';
import React, { useState, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { api } from '@/lib/api-client';
import { formatDate, copyTextToClipboard } from '@/lib/utils';
import { Navbar } from '@/components/layout/Navbar';
import { Sidebar } from '@/components/layout/Sidebar';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import {
ShieldAlert,
Search,
RefreshCw,
User,
Key,
Trash2,
Upload,
Play,
Info,
Shield,
Activity,
Globe,
Copy,
Check,
CheckCircle2,
FileText,
Building2,
Lock,
Layers,
} from 'lucide-react';
interface AuditLogItem {
id: string;
userId?: string | null;
actorUserId?: string | null;
action: string;
resourceType?: string | null;
resourceId?: string | null;
targetUserId?: string | null;
ipAddress?: string | null;
userAgent?: string | null;
details?: any | null;
detailsJson?: string | null;
createdAt: string;
actor?: {
id: string;
email: string;
username: string;
fullName: string;
role: string;
companyName?: string;
} | null;
targetUser?: {
id: string;
email: string;
username: string;
fullName: string;
} | null;
user?: {
id: string;
email: string;
fullName: string;
role: string;
companyName?: string;
} | null;
}
export default function AdminAuditPage() {
const router = useRouter();
const { user, isAdmin, canViewOtherUsers, isLoading } = useAuth();
const [logs, setLogs] = useState<AuditLogItem[]>([]);
const [totalCount, setTotalCount] = useState(0);
const [isDataLoading, setIsDataLoading] = useState(true);
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
const [search, setSearch] = useState('');
const [actionFilter, setActionFilter] = useState('');
const [selectedLog, setSelectedLog] = useState<AuditLogItem | null>(null);
const [copiedPayload, setCopiedPayload] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
useEffect(() => {
if (!isLoading) {
if (!user) router.push('/login');
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
}
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
const loadLogs = async (isSilent = false) => {
if (!isSilent) setIsDataLoading(true);
setIsSyncing(true);
try {
const res = await api.get<any>('/admin/audit-logs?limit=200');
const rawList: any[] = Array.isArray(res) ? res : res?.logs || [];
const total = typeof res?.total === 'number' ? res.total : rawList.length;
setTotalCount(total);
const mappedList: AuditLogItem[] = rawList.map((log) => {
let parsedDetails: any = null;
if (log.detailsJson) {
try {
parsedDetails = typeof log.detailsJson === 'string' ? JSON.parse(log.detailsJson) : log.detailsJson;
} catch {
parsedDetails = log.detailsJson;
}
} else if (log.details) {
parsedDetails = log.details;
}
const effectiveActor = log.actor || log.user || null;
return {
id: log.id,
userId: log.actorUserId || log.userId,
action: log.action || 'SYSTEM_ACTION',
resourceType: log.resourceType,
resourceId: log.resourceId,
targetUserId: log.targetUserId,
targetUser: log.targetUser,
ipAddress: log.ipAddress,
userAgent: log.userAgent,
details: parsedDetails,
detailsJson: log.detailsJson,
createdAt: log.createdAt,
actor: effectiveActor,
user: effectiveActor,
};
});
setLogs(mappedList);
setLastSyncedAt(new Date());
} catch (err) {
console.error('Failed to load audit logs', err);
} finally {
if (!isSilent) setIsDataLoading(false);
setIsSyncing(false);
}
};
useEffect(() => {
if (isAdmin && canViewOtherUsers) {
loadLogs();
}
}, [isAdmin, canViewOtherUsers]);
// Periodic Auto-Sync with Database (Silent every 10s + on Window Focus)
useEffect(() => {
if (!isAdmin || !canViewOtherUsers) return;
const interval = setInterval(() => {
if (document.visibilityState === 'visible') {
loadLogs(true);
}
}, 10000);
const handleFocus = () => {
loadLogs(true);
};
window.addEventListener('focus', handleFocus);
return () => {
clearInterval(interval);
window.removeEventListener('focus', handleFocus);
};
}, [isAdmin, canViewOtherUsers]);
// Dynamic statistics
const stats = useMemo(() => {
const authCount = logs.filter(
(l) => l.action.includes('LOGIN') || l.action.includes('AUTH') || l.action.includes('LOGOUT'),
).length;
const adminCount = logs.filter(
(l) => l.action.startsWith('ADMIN_') || l.action.includes('DELETED') || l.action.includes('SETTING'),
).length;
const ips = new Set(logs.map((l) => l.ipAddress).filter(Boolean)).size;
return {
total: totalCount || logs.length,
authEvents: authCount,
adminEvents: adminCount,
uniqueIps: ips || 1,
};
}, [logs, totalCount]);
const filteredLogs = useMemo(() => {
return logs.filter((log) => {
const actorEmail = log.actor?.email || log.user?.email || '';
const actorName = log.actor?.fullName || log.user?.fullName || '';
const targetName = log.targetUser?.fullName || log.targetUser?.email || '';
const matchesSearch =
!search ||
log.action.toLowerCase().includes(search.toLowerCase()) ||
actorEmail.toLowerCase().includes(search.toLowerCase()) ||
actorName.toLowerCase().includes(search.toLowerCase()) ||
targetName.toLowerCase().includes(search.toLowerCase()) ||
(log.ipAddress && log.ipAddress.includes(search)) ||
(log.resourceId && log.resourceId.includes(search)) ||
(log.resourceType && log.resourceType.toLowerCase().includes(search.toLowerCase()));
const matchesAction = !actionFilter || log.action === actionFilter;
return matchesSearch && matchesAction;
});
}, [logs, search, actionFilter]);
const getActionBadge = (action: string) => {
let color = 'bg-slate-50 text-slate-700 border-slate-200';
let icon = <Info className="w-3 h-3" />;
if (action.includes('FAILED')) {
color = 'bg-rose-50 text-rose-700 border-rose-200';
icon = <ShieldAlert className="w-3 h-3" />;
} else if (action.includes('LOGIN') || action.includes('AUTH')) {
color = 'bg-emerald-50 text-emerald-700 border-emerald-200';
icon = <User className="w-3 h-3" />;
} else if (action.includes('ADMIN_') || action.includes('PERMISSION') || action.includes('SHARE')) {
color = 'bg-indigo-50 text-indigo-700 border-indigo-200';
icon = <Key className="w-3 h-3" />;
} else if (action.includes('UPLOAD')) {
color = 'bg-sky-50 text-sky-700 border-sky-200';
icon = <Upload className="w-3 h-3" />;
} else if (action.includes('STREAM') || action.includes('PLAY')) {
color = 'bg-purple-50 text-purple-700 border-purple-200';
icon = <Play className="w-3 h-3" />;
} else if (action.includes('DELETE') || action.includes('REVOKE') || action.includes('SUSPEND')) {
color = 'bg-rose-50 text-rose-700 border-rose-200';
icon = <Trash2 className="w-3 h-3" />;
}
return (
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-semibold border ${color}`}>
{icon}
<span>{action}</span>
</span>
);
};
const copyPayloadText = async (obj: any) => {
try {
await copyTextToClipboard(JSON.stringify(obj, null, 2));
setCopiedPayload(true);
setTimeout(() => setCopiedPayload(false), 2000);
} catch (err) {
console.warn('Failed to copy payload', err);
}
};
const uniqueActions = Array.from(new Set(logs.map((l) => l.action))).sort();
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
<EcohubWatermark variant="corner" />
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
<div className="flex-1 flex min-w-0">
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 w-full max-w-full">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<div className="flex items-center gap-2 flex-wrap">
<div className="w-9 h-9 rounded-xl bg-rose-100/80 border border-rose-200 flex items-center justify-center text-rose-700 shadow-xs">
<Shield className="w-5 h-5" />
</div>
<div>
<h1 className="text-lg sm:text-xl font-bold tracking-tight text-slate-900">
Security & Compliance Audit Trail
</h1>
<p className="text-xs text-slate-500">
Chronological history of authentications, permissions, administrative actions and system events
</p>
</div>
</div>
</div>
<div className="flex items-center gap-2">
{/* Live Database Sync Badge */}
<div
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl bg-white border border-slate-200/80 text-slate-600 text-xs font-medium shadow-xs"
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
>
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
<span className="hidden md:inline">{isSyncing ? 'Syncing...' : 'Synced'}</span>
<button
onClick={() => loadLogs(false)}
disabled={isSyncing}
className="p-0.5 hover:text-emerald-600 transition-colors"
title="Refresh Audit Logs"
>
<RefreshCw className={`w-3.5 h-3.5 ${isSyncing ? 'animate-spin text-emerald-600' : ''}`} />
</button>
</div>
</div>
</div>
{/* Overview Summary Metric Cards */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center text-blue-600 shrink-0">
<Layers className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">Total Audit Records</span>
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.total}</span>
</div>
</div>
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-emerald-50 border border-emerald-100 flex items-center justify-center text-emerald-600 shrink-0">
<User className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">User Auth Events</span>
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.authEvents}</span>
</div>
</div>
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-purple-50 border border-purple-100 flex items-center justify-center text-purple-600 shrink-0">
<Key className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">Admin Operations</span>
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.adminEvents}</span>
</div>
</div>
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-amber-50 border border-amber-100 flex items-center justify-center text-amber-600 shrink-0">
<Globe className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">Active Client IPs</span>
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.uniqueIps}</span>
</div>
</div>
</div>
{/* Filters Bar */}
<div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center justify-between bg-white p-3 rounded-2xl border border-slate-200/80 shadow-xs">
<div className="relative flex-1 min-w-0">
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="Filter by actor name, email, action, IP or resource ID..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full pl-9 pr-4 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 text-xs placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 transition-colors"
/>
</div>
<div className="flex gap-2">
<select
value={actionFilter}
onChange={(e) => setActionFilter(e.target.value)}
className="px-3 py-1.5 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-700 font-medium focus:outline-none cursor-pointer"
>
<option value="">All Action Types ({logs.length})</option>
{uniqueActions.map((act) => (
<option key={act} value={act}>
{act}
</option>
))}
</select>
</div>
</div>
{/* Audit Trail Table */}
<div className="bg-white border border-slate-200/80 rounded-2xl overflow-hidden shadow-xs w-full">
<div className="overflow-x-auto w-full">
<table className="w-full text-left text-xs text-slate-700 border-collapse">
<thead className="bg-slate-50/70 text-[11px] uppercase font-semibold text-slate-500 border-b border-slate-200">
<tr>
<th className="px-4 py-3">Timestamp</th>
<th className="px-4 py-3">Action Type</th>
<th className="px-4 py-3">Actor / User</th>
<th className="px-4 py-3">Target Resource</th>
<th className="px-4 py-3">Client IP</th>
<th className="px-4 py-3 text-right">Details</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{filteredLogs.length > 0 ? (
filteredLogs.map((log) => {
const actor = log.actor || log.user;
const hasDetails = log.details && (typeof log.details === 'object' ? Object.keys(log.details).length > 0 : true);
return (
<tr key={log.id} className="hover:bg-slate-50/70 transition-colors">
<td className="px-4 py-3 text-slate-500 whitespace-nowrap font-mono text-[11px]">
{formatDate(log.createdAt)}
</td>
<td className="px-4 py-3 whitespace-nowrap">
{getActionBadge(log.action)}
</td>
<td className="px-4 py-3 whitespace-nowrap">
{actor ? (
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-full bg-emerald-100 text-emerald-800 font-bold flex items-center justify-center text-xs shrink-0">
{actor.fullName ? actor.fullName.charAt(0).toUpperCase() : 'U'}
</div>
<div className="min-w-0">
<span className="font-semibold text-slate-900 block truncate">
{actor.fullName}
</span>
<span className="text-[11px] text-slate-500 font-mono block truncate">
{actor.email}
</span>
</div>
</div>
) : (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-mono bg-slate-100 text-slate-500">
System / Anon
</span>
)}
</td>
<td className="px-4 py-3 font-mono text-[11px] text-slate-600 whitespace-nowrap">
{log.resourceType ? (
<span className="inline-flex items-center gap-1">
<span className="text-emerald-700 font-semibold bg-emerald-50 px-1.5 py-0.2 rounded border border-emerald-100">
{log.resourceType}
</span>
{log.resourceId && (
<span className="text-slate-500 truncate max-w-[120px]" title={log.resourceId}>
{log.resourceId.slice(0, 8)}...
</span>
)}
</span>
) : (
<span className="text-slate-400">—</span>
)}
</td>
<td className="px-4 py-3 font-mono text-[11px] text-slate-500 whitespace-nowrap">
{log.ipAddress || '127.0.0.1'}
</td>
<td className="px-4 py-3 text-right whitespace-nowrap">
{hasDetails ? (
<button
onClick={() => setSelectedLog(log)}
className="px-2.5 py-1 text-xs font-semibold text-emerald-700 hover:text-emerald-800 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200/80 rounded-lg transition-colors"
>
Inspect JSON
</button>
) : (
<span className="text-slate-400 text-xs">—</span>
)}
</td>
</tr>
);
})
) : (
<tr>
<td colSpan={6} className="text-center py-12 text-slate-400 text-xs">
{isDataLoading ? 'Loading audit records...' : 'No audit records match your search criteria.'}
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
{/* Inspect JSON Details Modal */}
{selectedLog && (
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in duration-200">
<div className="bg-white border border-slate-200 rounded-2xl w-full max-w-lg p-6 space-y-4 shadow-2xl">
<div className="flex items-center justify-between border-b border-slate-100 pb-3">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-emerald-100 text-emerald-700 flex items-center justify-center">
<FileText className="w-4 h-4" />
</div>
<div>
<h3 className="text-base font-bold text-slate-900">Audit Event Metadata</h3>
<p className="text-xs text-slate-500 font-mono">ID: {selectedLog.id}</p>
</div>
</div>
<button
onClick={() => setSelectedLog(null)}
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
>
✕
</button>
</div>
<div className="grid grid-cols-2 gap-2 text-xs bg-slate-50 p-3 rounded-xl border border-slate-200/80">
<div>
<span className="text-slate-400 block text-[10px] uppercase font-bold">Action</span>
<span className="font-semibold text-slate-800">{selectedLog.action}</span>
</div>
<div>
<span className="text-slate-400 block text-[10px] uppercase font-bold">Timestamp</span>
<span className="font-mono text-slate-700">{formatDate(selectedLog.createdAt)}</span>
</div>
<div>
<span className="text-slate-400 block text-[10px] uppercase font-bold">Actor</span>
<span className="text-slate-700 font-medium">
{selectedLog.actor?.fullName || selectedLog.user?.fullName || 'System'}
</span>
</div>
<div>
<span className="text-slate-400 block text-[10px] uppercase font-bold">IP Address</span>
<span className="font-mono text-slate-700">{selectedLog.ipAddress || '127.0.0.1'}</span>
</div>
</div>
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<label className="text-xs font-semibold text-slate-700">Payload / Details JSON:</label>
<button
onClick={() => copyPayloadText(selectedLog.details)}
className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-600 hover:text-emerald-700"
>
{copiedPayload ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
<span>{copiedPayload ? 'Copied!' : 'Copy JSON'}</span>
</button>
</div>
<pre className="p-3 bg-slate-900 rounded-xl text-xs font-mono text-emerald-400 overflow-x-auto max-h-60 custom-scrollbar border border-slate-800">
{JSON.stringify(selectedLog.details, null, 2)}
</pre>
</div>
<div className="pt-2 flex justify-end">
<button
onClick={() => setSelectedLog(null)}
className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-semibold transition-colors"
>
Close
</button>
</div>
</div>
</div>
)}
</div>
</main>
</div>
</div>
);
}

View File

@@ -0,0 +1,413 @@
'use client';
import React, { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { api } from '@/lib/api-client';
import { formatBytes, formatDate } from '@/lib/utils';
import { Navbar } from '@/components/layout/Navbar';
import { Sidebar } from '@/components/layout/Sidebar';
import { FileCard } from '@/components/file-manager/FileCard';
import { FilePreviewModal } from '@/components/file-manager/FilePreviewModal';
import { GrantPermissionModal } from '@/components/admin/GrantPermissionModal';
import { BatchGrantModal } from '@/components/admin/BatchGrantModal';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import { FileCategory } from '@fileshare/shared';
import {
Files,
User,
Search,
HardDrive,
Loader2,
CheckSquare,
Square,
Download,
Layers,
Building2,
RefreshCw,
} from 'lucide-react';
function AdminFilesContent() {
const searchParams = useSearchParams();
const initialUserId = searchParams.get('userId');
const router = useRouter();
const { user, isAdmin, canViewOtherUsers, isLoading } = useAuth();
const [usersList, setUsersList] = useState<any[]>([]);
const [selectedUserId, setSelectedUserId] = useState<string>(initialUserId || '');
const [targetUserData, setTargetUserData] = useState<any | null>(null);
const [files, setFiles] = useState<any[]>([]);
const [isDataLoading, setIsDataLoading] = useState(false);
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
const [search, setSearch] = useState('');
const [categoryFilter, setCategoryFilter] = useState('');
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
// Multi-selection state for 1-by-1 or select-all permission grant
const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]);
// Modals
const [selectedFileForPreview, setSelectedFileForPreview] = useState<any | null>(null);
const [permissionTargetFile, setPermissionTargetFile] = useState<any | null>(null);
const [isBatchGrantOpen, setIsBatchGrantOpen] = useState(false);
useEffect(() => {
if (!isLoading) {
if (!user) router.push('/login');
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
}
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
useEffect(() => {
if (isAdmin && canViewOtherUsers) {
api.get<any>('/admin/users?limit=100').then((res) => {
setUsersList(res.users || []);
if (!selectedUserId && res.users?.length > 0) {
setSelectedUserId(res.users[0].id);
}
});
}
}, [isAdmin, canViewOtherUsers, selectedUserId]);
const loadFiles = (isSilent = false) => {
if (selectedUserId && isAdmin) {
if (!isSilent) setIsDataLoading(true);
setIsSyncing(true);
let query = `/admin/users/${selectedUserId}/files?limit=100`;
if (search) query += `&search=${encodeURIComponent(search)}`;
if (categoryFilter) query += `&category=${categoryFilter}`;
api.get<any>(query)
.then((res) => {
setTargetUserData(res.targetUser);
setFiles(res.files || []);
setLastSyncedAt(new Date());
})
.catch((err) => {
console.error('Failed to load user files', err);
})
.finally(() => {
if (!isSilent) setIsDataLoading(false);
setIsSyncing(false);
});
}
};
useEffect(() => {
loadFiles();
}, [selectedUserId, search, categoryFilter, isAdmin]);
// Periodic Auto-Sync with Database (Silent every 8s, faster 3s if processing videos)
useEffect(() => {
if (!selectedUserId || !isAdmin) return;
const hasProcessingVideos = files.some(
(f) => f.transcodeStatus === 'PROCESSING' || f.transcodeStatus === 'PENDING',
);
const intervalMs = hasProcessingVideos ? 3000 : 8000;
const timer = setInterval(() => {
if (document.visibilityState === 'visible') {
loadFiles(true);
}
}, intervalMs);
const handleFocus = () => {
loadFiles(true);
};
window.addEventListener('focus', handleFocus);
return () => {
clearInterval(timer);
window.removeEventListener('focus', handleFocus);
};
}, [selectedUserId, isAdmin, search, categoryFilter, files]);
const toggleSelectFile = (fileId: string) => {
setSelectedFileIds((prev) =>
prev.includes(fileId) ? prev.filter((id) => id !== fileId) : [...prev, fileId],
);
};
const handleSelectAll = () => {
if (selectedFileIds.length === files.length) {
setSelectedFileIds([]);
} else {
setSelectedFileIds(files.map((f) => f.id));
}
};
if (isLoading || !isAdmin) {
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
);
}
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
<EcohubWatermark variant="corner" />
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
<div className="flex-1 flex min-w-0">
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl w-full mx-auto">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<div className="flex items-center gap-2 flex-wrap">
<h1 className="text-xl font-bold text-slate-900 flex items-center gap-2.5">
<Files className="w-5 h-5 text-emerald-600" />
<span>User-wise Video & File Inventory Explorer</span>
</h1>
{/* Live Database Sync Badge */}
<div
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
>
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
</div>
</div>
<p className="text-xs text-slate-500 mt-1">
Admin & Superadmin can inspect, download videos user-wise, and grant permissions 1-by-1 or all at once
</p>
</div>
<div className="flex items-center gap-2 flex-wrap sm:flex-nowrap">
{/* Manual Sync Button */}
<button
onClick={() => loadFiles(false)}
disabled={isSyncing}
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
title="Sync with database"
>
<RefreshCw className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
<span>Sync DB</span>
</button>
{/* Target User Switcher */}
<div className="flex items-center gap-2">
<User className="w-4 h-4 text-emerald-600" />
<select
value={selectedUserId}
onChange={(e) => setSelectedUserId(e.target.value)}
className="px-3 py-2 rounded-xl bg-white border border-slate-200 text-xs text-slate-800 focus:outline-none focus:border-emerald-600 font-medium shadow-sm"
>
{usersList.map((u) => (
<option key={u.id} value={u.id}>
{u.fullName} (@{u.username}) {u.companyName ? `• ${u.companyName}` : ''}
</option>
))}
</select>
</div>
</div>
</div>
{/* User Quota Banner & Batch Action Bar */}
{targetUserData && (
<div className="p-4 rounded-2xl bg-white border border-slate-200 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4 text-xs">
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600">
<HardDrive className="w-4 h-4" />
</div>
<div>
<div className="flex items-center gap-2">
<span className="font-semibold text-slate-900 block">
{targetUserData.fullName} ({targetUserData.email})
</span>
{targetUserData.companyName && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
<Building2 className="w-3 h-3" />
{targetUserData.companyName}
</span>
)}
</div>
<span className="text-slate-500">
Storage: {formatBytes(targetUserData.storageUsedBytes)} / {formatBytes(targetUserData.storageQuotaBytes)}
</span>
</div>
</div>
{/* Selection Controls & Bulk Permissions */}
<div className="flex flex-wrap items-center gap-2">
<button
onClick={handleSelectAll}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-medium transition-colors"
>
{selectedFileIds.length === files.length && files.length > 0 ? (
<>
<CheckSquare className="w-3.5 h-3.5 text-emerald-600" />
<span>Deselect All</span>
</>
) : (
<>
<Square className="w-3.5 h-3.5 text-slate-400" />
<span>Select All ({files.length})</span>
</>
)}
</button>
<button
onClick={() => setIsBatchGrantOpen(true)}
className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 active:scale-95 text-white text-xs font-semibold shadow-md shadow-emerald-600/20 transition-all"
>
<Layers className="w-3.5 h-3.5" />
<span>
Grant Permissions ({selectedFileIds.length > 0 ? `${selectedFileIds.length} Selected` : 'Select All'})
</span>
</button>
</div>
</div>
)}
{/* Filter and Search Bar */}
<div className="p-3.5 rounded-2xl bg-white border border-slate-200 shadow-sm flex flex-col sm:flex-row items-center justify-between gap-3 text-xs">
<div className="relative w-full sm:w-72">
<Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-2.5" />
<input
type="text"
placeholder="Search user files..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full pl-8 pr-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600"
/>
</div>
<div className="flex items-center gap-2 w-full sm:w-auto">
<select
value={categoryFilter}
onChange={(e) => setCategoryFilter(e.target.value)}
className="px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-xs focus:outline-none"
>
<option value="">All Categories</option>
<option value={FileCategory.VIDEO}>Videos</option>
<option value={FileCategory.IMAGE}>Images</option>
<option value={FileCategory.DOCUMENT}>Documents</option>
<option value={FileCategory.ARCHIVE}>Archives</option>
<option value={FileCategory.AUDIO}>Audio</option>
</select>
</div>
</div>
{/* Files Grid with selection checkboxes and direct download */}
{isDataLoading ? (
<div className="p-16 flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
) : files.length === 0 ? (
<div className="p-16 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
<p className="text-sm text-slate-500">No files found for this user</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{files.map((file) => {
const isSelected = selectedFileIds.includes(file.id);
const downloadUrl = api.getDownloadUrl(file.id);
return (
<div
key={file.id}
className={`relative rounded-2xl transition-all ${
isSelected
? 'ring-2 ring-emerald-500 shadow-lg shadow-emerald-500/20'
: ''
}`}
>
{/* Checkbox badge on top-left for 1-by-1 selection */}
<button
type="button"
onClick={() => toggleSelectFile(file.id)}
className="absolute top-2 left-2 z-20 p-1.5 rounded-lg bg-white/90 hover:bg-white border border-slate-300 text-slate-800 shadow-sm backdrop-blur-sm transition-all"
title={isSelected ? 'Deselect file' : 'Select file'}
>
{isSelected ? (
<CheckSquare className="w-4 h-4 text-emerald-600" />
) : (
<Square className="w-4 h-4 text-slate-400" />
)}
</button>
{/* Direct Download Button for Super Admin / Admin */}
<a
href={downloadUrl}
download={file.originalFilename}
className="absolute top-2 right-10 z-20 p-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white shadow-md transition-all"
title="Download file (Admin Access)"
>
<Download className="w-4 h-4" />
</a>
<FileCard
file={{
...file,
permissions: {
canPlay: true,
canDownload: true,
canPreview: true,
canViewMetadata: true,
},
}}
isOwner={false}
onPreview={(f) => setSelectedFileForPreview(f)}
onRename={() => {}}
onMove={() => {}}
onDelete={async (f) => {
if (confirm(`Administrative delete: Remove file "${f.originalFilename}"?`)) {
await api.delete(`/files/${f.id}`);
loadFiles();
}
}}
/>
</div>
);
})}
</div>
)}
</div>
</main>
</div>
<FilePreviewModal
isOpen={!!selectedFileForPreview}
onClose={() => setSelectedFileForPreview(null)}
file={selectedFileForPreview}
/>
<GrantPermissionModal
isOpen={!!permissionTargetFile}
onClose={() => setPermissionTargetFile(null)}
onSuccess={loadFiles}
preselectedFile={permissionTargetFile}
/>
<BatchGrantModal
isOpen={isBatchGrantOpen}
onClose={() => setIsBatchGrantOpen(false)}
selectedFileIds={selectedFileIds}
ownerId={selectedUserId}
onSuccess={loadFiles}
/>
</div>
);
}
export default function AdminFilesPage() {
return (
<React.Suspense
fallback={
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center text-slate-500">
<Loader2 className="w-8 h-8 animate-spin text-emerald-600" />
</div>
}
>
<AdminFilesContent />
</React.Suspense>
);
}

View File

@@ -0,0 +1,357 @@
'use client';
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { api } from '@/lib/api-client';
import { Navbar } from '@/components/layout/Navbar';
import { Sidebar } from '@/components/layout/Sidebar';
import { GrantPermissionModal } from '@/components/admin/GrantPermissionModal';
import { BatchGrantModal } from '@/components/admin/BatchGrantModal';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import {
KeyRound,
Plus,
Trash2,
Ban,
CheckCircle,
XCircle,
Loader2,
Layers,
RefreshCw,
} from 'lucide-react';
export default function AdminPermissionsPage() {
const router = useRouter();
const { user, isAdmin, canViewOtherUsers, isLoading } = useAuth();
const [permissions, setPermissions] = useState<any[]>([]);
const [total, setTotal] = useState(0);
const [isDataLoading, setIsDataLoading] = useState(true);
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
const [isGrantModalOpen, setIsGrantModalOpen] = useState(false);
const [isBatchModalOpen, setIsBatchModalOpen] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [activeOnly, setActiveOnly] = useState(false);
useEffect(() => {
if (!isLoading) {
if (!user) router.push('/login');
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
}
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
const loadPermissions = async (isSilent = false) => {
if (!isSilent) setIsDataLoading(true);
setIsSyncing(true);
try {
const res = await api.get<any>(
`/admin/permissions?limit=100${activeOnly ? '&activeOnly=true' : ''}`,
);
setPermissions(res.permissions || []);
setTotal(res.total || 0);
setLastSyncedAt(new Date());
} catch (err) {
console.error('Failed to load permissions', err);
} finally {
if (!isSilent) setIsDataLoading(false);
setIsSyncing(false);
}
};
useEffect(() => {
if (isAdmin && canViewOtherUsers) {
loadPermissions();
}
}, [isAdmin, canViewOtherUsers, activeOnly]);
// Periodic Auto-Sync with Database (Silent every 10s + on Window Focus)
useEffect(() => {
if (!isAdmin || !canViewOtherUsers) return;
const interval = setInterval(() => {
if (document.visibilityState === 'visible') {
loadPermissions(true);
}
}, 10000);
const handleFocus = () => {
loadPermissions(true);
};
window.addEventListener('focus', handleFocus);
return () => {
clearInterval(interval);
window.removeEventListener('focus', handleFocus);
};
}, [isAdmin, canViewOtherUsers, activeOnly]);
const handleRevoke = async (id: string) => {
if (confirm('Revoke this permission? Access will be immediately blocked.')) {
try {
await api.post(`/admin/permissions/${id}/revoke`, {});
loadPermissions();
} catch (err: any) {
alert(err.message || 'Failed to revoke permission');
}
}
};
const handleDelete = async (id: string) => {
if (confirm('Permanently delete this permission record?')) {
try {
await api.delete(`/admin/permissions/${id}`);
loadPermissions();
} catch (err: any) {
alert(err.message || 'Failed to delete permission');
}
}
};
if (isLoading || !isAdmin) {
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
);
}
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
<EcohubWatermark variant="corner" />
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
<div className="flex-1 flex min-w-0">
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl w-full mx-auto">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<div className="flex items-center gap-2 flex-wrap">
<h1 className="text-xl font-bold text-slate-900 flex items-center gap-2.5">
<KeyRound className="w-5 h-5 text-emerald-600" />
<span>Access Control & Permission Matrix</span>
</h1>
{/* Live Database Sync Badge */}
<div
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
>
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
</div>
</div>
<p className="text-xs text-slate-500 mt-1">
Centrally control user-to-user sharing rights with separate play, download, and preview authorization
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{/* Manual Sync Button */}
<button
onClick={() => loadPermissions(false)}
disabled={isSyncing}
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
title="Sync with database"
>
<RefreshCw className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
<span>Sync DB</span>
</button>
<button
onClick={() => setIsBatchModalOpen(true)}
className="flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-white hover:bg-slate-50 text-slate-700 text-xs font-semibold border border-slate-200 transition-all shadow-sm"
>
<Layers className="w-4 h-4 text-emerald-600" />
<span>Batch Grant (Select All)</span>
</button>
<button
onClick={() => setIsGrantModalOpen(true)}
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-medium shadow-md shadow-emerald-600/20 transition-all"
>
<Plus className="w-4 h-4" />
<span>Grant New Permission</span>
</button>
</div>
</div>
{/* Table */}
{isDataLoading ? (
<div className="p-16 flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
) : permissions.length === 0 ? (
<div className="p-16 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
<KeyRound className="w-12 h-12 text-slate-400 mx-auto mb-3" />
<h3 className="text-sm font-medium text-slate-800">No sharing permissions defined</h3>
<p className="text-xs text-slate-500 mt-1 max-w-sm mx-auto">
Users currently have private access to their own files only. Click "Grant New Permission" to authorize cross-user access.
</p>
</div>
) : (
<div className="bg-white rounded-2xl overflow-hidden border border-slate-200 shadow-sm">
<div className="overflow-x-auto">
<table className="w-full min-w-[760px] text-left border-collapse">
<thead>
<tr className="border-b border-slate-200 bg-slate-50 text-[11px] font-semibold text-slate-500 uppercase tracking-wider">
<th className="py-3 px-4">Scope</th>
<th className="py-3 px-4">Owner</th>
<th className="py-3 px-4">Grantee (Recipient)</th>
<th className="py-3 px-4 text-center">Metadata</th>
<th className="py-3 px-4 text-center">Preview</th>
<th className="py-3 px-4 text-center">Play</th>
<th className="py-3 px-4 text-center">Download</th>
<th className="py-3 px-4">Status</th>
<th className="py-3 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody>
{permissions.map((p) => {
const isRevoked = !!p.revokedAt;
const isExpired = p.expiresAt && new Date(p.expiresAt) < new Date();
return (
<tr
key={p.id}
className="border-b border-slate-100 hover:bg-slate-50/70 transition-colors text-xs"
>
{/* Scope */}
<td className="py-3 px-4">
<div>
<span className="font-semibold text-emerald-800 block text-[11px]">
{p.resourceType}
</span>
{p.resourceId && (
<span className="text-[10px] font-mono text-slate-400 truncate block max-w-[120px]">
{p.resourceId}
</span>
)}
</div>
</td>
{/* Owner */}
<td className="py-3 px-4">
<span className="text-slate-900 block font-medium">
{p.owner?.fullName || 'User'}
</span>
<span className="text-[10px] text-slate-500">
{p.owner?.email}
</span>
</td>
{/* Grantee */}
<td className="py-3 px-4">
<span className="text-slate-900 block font-medium">
{p.grantee?.fullName || 'User'}
</span>
<span className="text-[10px] text-slate-500">
{p.grantee?.email}
</span>
</td>
{/* Metadata */}
<td className="py-3 px-4 text-center">
{p.canViewMetadata ? (
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
) : (
<XCircle className="w-4 h-4 text-slate-300 mx-auto" />
)}
</td>
{/* Preview */}
<td className="py-3 px-4 text-center">
{p.canPreview ? (
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
) : (
<XCircle className="w-4 h-4 text-slate-300 mx-auto" />
)}
</td>
{/* Play */}
<td className="py-3 px-4 text-center">
{p.canPlay ? (
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
) : (
<XCircle className="w-4 h-4 text-slate-300 mx-auto" />
)}
</td>
{/* Download */}
<td className="py-3 px-4 text-center">
{p.canDownload ? (
<CheckCircle className="w-4 h-4 text-emerald-600 mx-auto" />
) : (
<XCircle className="w-4 h-4 text-rose-500 mx-auto" />
)}
</td>
{/* Status */}
<td className="py-3 px-4">
{isRevoked ? (
<span className="inline-block px-2 py-0.5 rounded-full text-[10px] font-medium bg-rose-50 text-rose-700">
Revoked
</span>
) : isExpired ? (
<span className="inline-block px-2 py-0.5 rounded-full text-[10px] font-medium bg-amber-50 text-amber-700">
Expired
</span>
) : (
<span className="inline-block px-2 py-0.5 rounded-full text-[10px] font-medium bg-emerald-50 text-emerald-700">
Active
</span>
)}
</td>
{/* Actions */}
<td className="py-3 px-4 text-right">
<div className="flex items-center justify-end gap-1.5">
{!isRevoked && (
<button
onClick={() => handleRevoke(p.id)}
className="p-1.5 rounded-lg hover:bg-rose-50 text-slate-400 hover:text-rose-600 transition-colors"
title="Revoke access"
>
<Ban className="w-3.5 h-3.5" />
</button>
)}
<button
onClick={() => handleDelete(p.id)}
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-rose-600 transition-colors"
title="Delete record"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
)}
</div>
</main>
</div>
<GrantPermissionModal
isOpen={isGrantModalOpen}
onClose={() => setIsGrantModalOpen(false)}
onSuccess={loadPermissions}
/>
<BatchGrantModal
isOpen={isBatchModalOpen}
onClose={() => setIsBatchModalOpen(false)}
onSuccess={loadPermissions}
/>
</div>
);
}

View File

@@ -0,0 +1,998 @@
'use client';
import React, { useState, useEffect, useMemo } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { api } from '@/lib/api-client';
import { formatBytes, formatDate, copyTextToClipboard } from '@/lib/utils';
import { Navbar } from '@/components/layout/Navbar';
import { Sidebar } from '@/components/layout/Sidebar';
import { CreateUserModal } from '@/components/admin/CreateUserModal';
import { EditUserModal } from '@/components/admin/EditUserModal';
import { AdminResetPasswordModal } from '@/components/admin/AdminResetPasswordModal';
import { DeleteUserModal } from '@/components/admin/DeleteUserModal';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import { UserRole, UserStatus } from '@fileshare/shared';
import {
Users,
UserPlus,
Search,
Building2,
Edit2,
Loader2,
Eye,
EyeOff,
Copy,
Check,
KeyRound,
Download,
Share2,
Trash2,
Server,
RefreshCw,
LayoutGrid,
List,
Shield,
HardDrive,
CheckCircle2,
FolderOpen,
} from 'lucide-react';
export default function AdminUsersPage() {
const router = useRouter();
const { user, isAdmin, isSuperAdmin, canViewOtherUsers, isLoading } = useAuth();
const [usersList, setUsersList] = useState<any[]>([]);
const [total, setTotal] = useState(0);
const [search, setSearch] = useState('');
const [roleFilter, setRoleFilter] = useState('');
const [statusFilter, setStatusFilter] = useState('');
const [viewMode, setViewMode] = useState<'table' | 'cards'>('table');
const [isDataLoading, setIsDataLoading] = useState(true);
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
// Password visibility map & copied state
const [visiblePasswords, setVisiblePasswords] = useState<Record<string, boolean>>({});
const [copiedId, setCopiedId] = useState<string | null>(null);
// Modals
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [editTargetUser, setEditTargetUser] = useState<any | null>(null);
const [resetPasswordTargetUser, setResetPasswordTargetUser] = useState<any | null>(null);
const [deleteTargetUser, setDeleteTargetUser] = useState<any | null>(null);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
useEffect(() => {
if (!isLoading) {
if (!user) router.push('/login');
else if (!isAdmin || !canViewOtherUsers) router.push('/dashboard');
}
}, [user, isAdmin, canViewOtherUsers, isLoading, router]);
const loadUsers = async (isSilent = false) => {
if (!isSilent) {
setIsDataLoading(true);
}
setIsSyncing(true);
try {
let query = `/admin/users?limit=100`;
if (search) query += `&search=${encodeURIComponent(search)}`;
if (roleFilter) query += `&role=${roleFilter}`;
if (statusFilter) query += `&status=${statusFilter}`;
const res = await api.get<any>(query);
setUsersList(res.users || []);
setTotal(res.total || 0);
setLastSyncedAt(new Date());
} catch (err) {
console.error('Failed to load users', err);
} finally {
if (!isSilent) setIsDataLoading(false);
setIsSyncing(false);
}
};
useEffect(() => {
if (isAdmin && canViewOtherUsers) {
loadUsers();
}
}, [isAdmin, canViewOtherUsers, search, roleFilter, statusFilter]);
// Periodic Auto-Sync with Database (Silent every 10s + on Window Focus)
useEffect(() => {
if (!isAdmin || !canViewOtherUsers) return;
const interval = setInterval(() => {
if (document.visibilityState === 'visible') {
loadUsers(true);
}
}, 10000);
const handleFocus = () => {
loadUsers(true);
};
window.addEventListener('focus', handleFocus);
return () => {
clearInterval(interval);
window.removeEventListener('focus', handleFocus);
};
}, [isAdmin, canViewOtherUsers, search, roleFilter, statusFilter]);
const togglePasswordVisibility = (userId: string) => {
setVisiblePasswords((prev) => ({
...prev,
[userId]: !prev[userId],
}));
};
const copyPassword = async (userId: string, pass: string) => {
try {
await copyTextToClipboard(pass);
setCopiedId(userId);
setTimeout(() => setCopiedId(null), 2000);
} catch (err) {
console.warn('Failed to copy password', err);
}
};
const handleToggleSharePermission = async (targetUser: any) => {
try {
await api.patch(`/admin/users/${targetUser.id}`, {
canCreateShareLinks: !targetUser.canCreateShareLinks,
});
loadUsers(true);
} catch (err: any) {
alert(err.message || 'Failed to update share permission');
}
};
const handleToggleDeletePermission = async (targetUser: any) => {
try {
await api.patch(`/admin/users/${targetUser.id}`, {
canDeleteFiles: !targetUser.canDeleteFiles,
});
loadUsers(true);
} catch (err: any) {
alert(err.message || 'Failed to update delete permission');
}
};
const handleToggleViewOtherUsersPermission = async (targetUser: any) => {
if (!isSuperAdmin) return;
try {
await api.patch(`/admin/users/${targetUser.id}`, {
canViewOtherUsers: !targetUser.canViewOtherUsers,
});
loadUsers(true);
} catch (err: any) {
alert(err.message || 'Failed to update view users permission');
}
};
const handleApproveUser = async (targetUser: any) => {
try {
await api.patch(`/admin/users/${targetUser.id}`, {
status: UserStatus.ACTIVE,
});
loadUsers(true);
} catch (err: any) {
alert(err.message || 'Failed to approve user');
}
};
// Dynamic Summary Metrics
const stats = useMemo(() => {
const activeCount = usersList.filter((u) => u.status === UserStatus.ACTIVE).length;
const pendingCount = usersList.filter((u) => u.status === UserStatus.PENDING).length;
const companies = new Set(usersList.map((u) => u.companyName || 'Ecohub')).size;
const totalStorageBytes = usersList.reduce((acc, u) => acc + Number(u.storageQuotaBytes || 0), 0);
const totalUsedBytes = usersList.reduce((acc, u) => acc + Number(u.storageUsedBytes || 0), 0);
return {
totalUsers: total || usersList.length,
activeUsers: activeCount,
pendingUsers: pendingCount,
totalCompanies: companies,
storageUsedFormatted: formatBytes(totalUsedBytes),
storageQuotaFormatted: formatBytes(totalStorageBytes),
};
}, [usersList, total]);
const getInitials = (name?: string) => {
if (!name) return 'U';
const parts = name.trim().split(' ');
if (parts.length >= 2) return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
return name.slice(0, 2).toUpperCase();
};
const getAvatarBg = (role?: UserRole) => {
if (role === UserRole.SUPER_ADMIN) return 'bg-gradient-to-br from-rose-500 to-red-600 text-white';
if (role === UserRole.ADMIN) return 'bg-gradient-to-br from-amber-500 to-orange-600 text-white';
return 'bg-gradient-to-br from-emerald-500 to-teal-600 text-white';
};
const parseAllowedCompanies = (raw: string | null | undefined, primary: string) => {
if (raw === '*') return { all: true, count: 0, list: [] };
if (!raw) return { all: false, count: 0, list: [] };
try {
const list: string[] = raw.startsWith('[')
? JSON.parse(raw)
: raw.split(',').map((s) => s.trim()).filter(Boolean);
const others = list.filter((c) => c.toLowerCase() !== primary.toLowerCase());
return { all: false, count: others.length, list: others };
} catch {
return { all: false, count: 0, list: [] };
}
};
if (isLoading || !isAdmin || !canViewOtherUsers) {
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
);
}
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
<EcohubWatermark variant="corner" />
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
<div className="flex-1 flex min-w-0">
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 w-full max-w-full">
{/* Top Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<div className="flex items-center gap-2.5 flex-wrap">
<div className="w-9 h-9 rounded-xl bg-emerald-100/80 border border-emerald-200 flex items-center justify-center text-emerald-700 shadow-xs">
<Users className="w-5 h-5" />
</div>
<div>
<h1 className="text-lg sm:text-xl font-bold text-slate-900 tracking-tight">
User Directory & Organizations
</h1>
<p className="text-xs text-slate-500">
Manage registered users, company access scopes, passwords & storage
</p>
</div>
</div>
</div>
<div className="flex items-center gap-2 flex-wrap sm:flex-nowrap">
{/* Live DB Sync Indicator */}
<div
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl bg-white border border-slate-200/80 text-slate-600 text-xs font-medium shadow-xs"
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
>
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
<span className="hidden md:inline">{isSyncing ? 'Syncing...' : 'Synced'}</span>
<button
onClick={() => loadUsers(false)}
disabled={isSyncing}
className="p-0.5 hover:text-emerald-600 transition-colors"
title="Refresh Now"
>
<RefreshCw className={`w-3.5 h-3.5 ${isSyncing ? 'animate-spin text-emerald-600' : ''}`} />
</button>
</div>
{/* View Mode Toggle */}
<div className="flex items-center bg-white border border-slate-200/80 rounded-xl p-0.5 shadow-xs">
<button
onClick={() => setViewMode('table')}
className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${
viewMode === 'table'
? 'bg-emerald-600 text-white shadow-xs'
: 'text-slate-600 hover:text-slate-900'
}`}
title="Table View (Fit to Screen)"
>
<List className="w-3.5 h-3.5" />
<span className="hidden sm:inline">Table</span>
</button>
<button
onClick={() => setViewMode('cards')}
className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold transition-all ${
viewMode === 'cards'
? 'bg-emerald-600 text-white shadow-xs'
: 'text-slate-600 hover:text-slate-900'
}`}
title="User Cards View (Simple & Easy)"
>
<LayoutGrid className="w-3.5 h-3.5" />
<span className="hidden sm:inline">Cards</span>
</button>
</div>
{/* Create User Button */}
<button
onClick={() => setIsCreateOpen(true)}
className="flex items-center gap-2 px-3.5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs shadow-md shadow-emerald-600/20 transition-all active:scale-95 whitespace-nowrap"
>
<UserPlus className="w-4 h-4" />
<span>Create User</span>
</button>
</div>
</div>
{/* Quick Metrics Bar (User-Friendly Overview) */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center text-blue-600 shrink-0">
<Users className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">Total Users</span>
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.totalUsers}</span>
</div>
</div>
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-emerald-50 border border-emerald-100 flex items-center justify-center text-emerald-600 shrink-0">
<CheckCircle2 className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">Active Accounts</span>
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.activeUsers}</span>
</div>
</div>
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-purple-50 border border-purple-100 flex items-center justify-center text-purple-600 shrink-0">
<Building2 className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">Organizations</span>
<span className="text-lg font-bold text-slate-900 leading-tight">{stats.totalCompanies}</span>
</div>
</div>
<div className="bg-white p-3.5 sm:p-4 rounded-2xl border border-slate-200/80 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-amber-50 border border-amber-100 flex items-center justify-center text-amber-600 shrink-0">
<HardDrive className="w-5 h-5" />
</div>
<div className="min-w-0">
<span className="text-[11px] font-medium text-slate-500 block truncate">Storage Used / Quota</span>
<span className="text-xs sm:text-sm font-bold text-slate-900 leading-tight block truncate">
{stats.storageUsedFormatted} <span className="text-slate-400 font-normal">/ {stats.storageQuotaFormatted}</span>
</span>
</div>
</div>
</div>
{/* Pending Approvals Alert Banner */}
{stats.pendingUsers > 0 && (
<div className="bg-amber-50 border border-amber-200/90 rounded-2xl p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs text-amber-900 shadow-xs">
<div className="flex items-center gap-3">
<span className="w-3 h-3 rounded-full bg-amber-500 animate-pulse shrink-0" />
<div>
<span className="font-bold text-amber-950">
{stats.pendingUsers} Self-Registered User{stats.pendingUsers > 1 ? 's' : ''} Awaiting Approval
</span>
<p className="text-[11px] text-amber-700">
New users cannot log in until an Administrator or Super Admin activates their account.
</p>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<button
onClick={() => setStatusFilter(UserStatus.PENDING)}
className="px-3 py-1.5 bg-amber-600 hover:bg-amber-700 text-white rounded-xl font-semibold text-xs transition-colors shadow-xs"
>
Filter Pending ({stats.pendingUsers})
</button>
{statusFilter === UserStatus.PENDING && (
<button
onClick={() => setStatusFilter('')}
className="px-3 py-1.5 bg-white border border-amber-300 text-amber-800 hover:bg-amber-100 rounded-xl font-medium text-xs transition-colors"
>
Clear Filter
</button>
)}
</div>
</div>
)}
{/* Filters Bar */}
<div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center justify-between bg-white p-3 rounded-2xl border border-slate-200/80 shadow-xs">
<div className="relative flex-1 min-w-0">
<Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="Search user name, username, email or company..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full pl-9 pr-4 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 text-xs placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 transition-colors"
/>
</div>
<div className="flex gap-2">
<select
value={roleFilter}
onChange={(e) => setRoleFilter(e.target.value)}
className="px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-xs focus:outline-none font-medium cursor-pointer"
>
<option value="">All Roles</option>
<option value={UserRole.USER}>Regular Users</option>
<option value={UserRole.ADMIN}>Administrators</option>
<option value={UserRole.SUPER_ADMIN}>Super Admins</option>
</select>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 text-xs focus:outline-none font-medium cursor-pointer"
>
<option value="">All Statuses</option>
<option value={UserStatus.ACTIVE}>Active</option>
<option value={UserStatus.SUSPENDED}>Suspended</option>
<option value={UserStatus.PENDING}>Pending</option>
</select>
</div>
</div>
{/* Main Content Area */}
{isDataLoading ? (
<div className="p-16 bg-white rounded-2xl border border-slate-200/80 shadow-xs flex flex-col items-center justify-center gap-3">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
<span className="text-xs text-slate-500 font-medium">Loading user directory...</span>
</div>
) : usersList.length === 0 ? (
<div className="p-16 bg-white rounded-2xl border border-slate-200/80 shadow-xs text-center space-y-2">
<Users className="w-10 h-10 text-slate-300 mx-auto" />
<h3 className="text-sm font-semibold text-slate-800">No users found</h3>
<p className="text-xs text-slate-400">Try adjusting your search query or filters.</p>
</div>
) : viewMode === 'table' ? (
/* Fit-To-Screen Compact Modern Table */
<div className="bg-white rounded-2xl border border-slate-200/80 shadow-xs overflow-hidden w-full">
<div className="overflow-x-auto w-full">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-slate-200 bg-slate-50/70 text-[11px] font-semibold text-slate-500 uppercase tracking-wider">
<th className="py-3 px-4">User</th>
<th className="py-3 px-4">Organization & Scopes</th>
<th className="py-3 px-4">Role & Status</th>
<th className="py-3 px-4">Storage Quota</th>
<th className="py-3 px-4">Feature Toggles</th>
{isSuperAdmin && <th className="py-3 px-4">Password</th>}
<th className="py-3 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{usersList.map((u) => {
const quota = Number(u.storageQuotaBytes);
const used = Number(u.storageUsedBytes);
const pct = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
const isVisible = !!visiblePasswords[u.id];
const orgScope = parseAllowedCompanies(u.allowedCompanies, u.companyName || 'Ecohub');
return (
<tr key={u.id} className="hover:bg-slate-50/60 transition-colors text-xs">
{/* User Avatar & Info */}
<td className="py-3 px-4">
<div className="flex items-center gap-3">
<div
className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs shrink-0 shadow-xs ${getAvatarBg(
u.role,
)}`}
>
{getInitials(u.fullName)}
</div>
<div className="min-w-0">
<span className="font-semibold text-slate-900 block truncate leading-snug">
{u.fullName}
</span>
<span className="text-[11px] text-slate-500 font-mono block truncate">
@{u.username} • {u.email}
</span>
</div>
</div>
</td>
{/* Organization & Permissions Scope */}
<td className="py-3 px-4">
<div className="flex flex-col gap-1 items-start">
<span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-[11px] font-semibold bg-emerald-50 text-emerald-800 border border-emerald-200/80">
<Building2 className="w-3 h-3 text-emerald-600 shrink-0" />
<span className="truncate max-w-[140px]">{u.companyName || 'Ecohub'}</span>
</span>
{/* Scope Badge */}
{u.role === UserRole.SUPER_ADMIN || orgScope.all ? (
<span className="text-[10px] font-bold text-purple-700 bg-purple-50 border border-purple-200/80 px-1.5 py-0.2 rounded font-mono">
All Orgs Access
</span>
) : orgScope.count > 0 ? (
<span
className="text-[10px] font-medium text-sky-700 bg-sky-50 border border-sky-200 px-1.5 py-0.2 rounded cursor-default"
title={`Allowed Orgs: ${u.companyName}, ${orgScope.list.join(', ')}`}
>
+{orgScope.count} Other {orgScope.count === 1 ? 'Org' : 'Orgs'}
</span>
) : (
<span className="text-[10px] text-slate-400">Own Org Only</span>
)}
</div>
</td>
{/* Role & Status */}
<td className="py-3 px-4">
<div className="flex items-center gap-1.5 flex-wrap">
<span
className={`px-2 py-0.5 rounded-md text-[10px] font-mono font-bold uppercase tracking-wider ${
u.role === UserRole.SUPER_ADMIN
? 'bg-rose-50 text-rose-700 border border-rose-200'
: u.role === UserRole.ADMIN
? 'bg-amber-50 text-amber-700 border border-amber-200'
: 'bg-slate-100 text-slate-700 border border-slate-200'
}`}
>
{u.role === UserRole.SUPER_ADMIN ? 'Super Admin' : u.role}
</span>
<span
className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${
u.status === UserStatus.ACTIVE
? 'bg-emerald-50 text-emerald-700'
: u.status === UserStatus.PENDING
? 'bg-amber-50 text-amber-700 border border-amber-200'
: 'bg-rose-50 text-rose-700'
}`}
>
<span
className={`w-1.5 h-1.5 rounded-full ${
u.status === UserStatus.ACTIVE
? 'bg-emerald-500'
: u.status === UserStatus.PENDING
? 'bg-amber-500 animate-pulse'
: 'bg-rose-500'
}`}
/>
<span>{u.status === UserStatus.PENDING ? 'Pending Approval' : u.status}</span>
</span>
</div>
</td>
{/* Storage Gauge */}
<td className="py-3 px-4">
<div className="w-32 space-y-1">
<div className="flex justify-between text-[11px] text-slate-600">
<span className="font-semibold text-slate-800">{formatBytes(used)}</span>
<span className="text-slate-400">/ {formatBytes(quota)}</span>
</div>
<div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all ${
pct > 90 ? 'bg-rose-500' : 'bg-emerald-500'
}`}
style={{ width: `${pct}%` }}
/>
</div>
</div>
</td>
{/* Clean Interactive Permission Icons */}
<td className="py-3 px-4">
<div className="flex items-center gap-1.5">
<button
onClick={() => handleToggleSharePermission(u)}
className={`p-1.5 rounded-lg border transition-all ${
u.canCreateShareLinks
? 'bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100'
: 'bg-slate-50 text-slate-400 border-slate-200 hover:bg-slate-100'
}`}
title={`Share Links: ${u.canCreateShareLinks ? 'Enabled (Click to disable)' : 'Disabled (Click to enable)'}`}
>
<Share2 className="w-3.5 h-3.5" />
</button>
<button
onClick={() => handleToggleDeletePermission(u)}
className={`p-1.5 rounded-lg border transition-all ${
u.canDeleteFiles
? 'bg-sky-50 text-sky-700 border-sky-200 hover:bg-sky-100'
: 'bg-rose-50 text-rose-700 border-rose-200 hover:bg-rose-100'
}`}
title={`File Deletion: ${u.canDeleteFiles ? 'Allowed (Click to block)' : 'Blocked (Click to allow)'}`}
>
<Trash2 className="w-3.5 h-3.5" />
</button>
{isSuperAdmin && (
<button
onClick={() => handleToggleViewOtherUsersPermission(u)}
disabled={u.role === UserRole.SUPER_ADMIN}
className={`p-1.5 rounded-lg border transition-all ${
u.role === UserRole.SUPER_ADMIN || u.canViewOtherUsers
? 'bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100'
: 'bg-slate-50 text-slate-400 border-slate-200 hover:bg-slate-100'
} disabled:opacity-50`}
title={`View Other Users: ${
u.role === UserRole.SUPER_ADMIN
? 'Super Admin (Always allowed)'
: u.canViewOtherUsers
? 'Allowed (Click to block)'
: 'Blocked (Click to allow)'
}`}
>
<Eye className="w-3.5 h-3.5" />
</button>
)}
</div>
</td>
{/* Super Admin Password Viewing */}
{isSuperAdmin && (
<td className="py-3 px-4">
<div className="flex items-center gap-1.5">
<span className="font-mono text-xs px-2 py-0.5 rounded bg-slate-50 border border-slate-200 text-amber-800 font-semibold max-w-[110px] truncate">
{isVisible ? u.viewablePassword || '<not saved>' : '••••••'}
</span>
<button
onClick={() => togglePasswordVisibility(u.id)}
className="p-1 rounded text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors"
title={isVisible ? 'Hide password' : 'View password'}
>
{isVisible ? <EyeOff className="w-3.5 h-3.5 text-amber-600" /> : <Eye className="w-3.5 h-3.5" />}
</button>
{u.viewablePassword && isVisible && (
<button
onClick={() => copyPassword(u.id, u.viewablePassword)}
className="p-1 rounded text-slate-400 hover:text-emerald-600 hover:bg-slate-100 transition-colors"
title="Copy password"
>
{copiedId === u.id ? <Check className="w-3.5 h-3.5 text-emerald-600" /> : <Copy className="w-3.5 h-3.5" />}
</button>
)}
</div>
</td>
)}
{/* Sleek Action Buttons */}
<td className="py-3 px-4 text-right">
<div className="flex items-center justify-end gap-1">
{u.status === UserStatus.PENDING && (
<button
onClick={() => handleApproveUser(u)}
className="px-2.5 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white text-[11px] font-semibold flex items-center gap-1 shadow-xs transition-all shrink-0 mr-1"
title="Approve and activate account"
>
<Check className="w-3.5 h-3.5" />
<span>Approve</span>
</button>
)}
<Link
href={`/admin/files?userId=${u.id}`}
className="p-1.5 rounded-lg bg-emerald-50 hover:bg-emerald-100 text-emerald-700 border border-emerald-200 transition-colors"
title="Browse & download user files"
>
<Download className="w-3.5 h-3.5" />
</Link>
<button
onClick={() => setResetPasswordTargetUser(u)}
className="p-1.5 rounded-lg hover:bg-amber-50 text-slate-400 hover:text-amber-600 transition-colors"
title="Reset password"
>
<KeyRound className="w-3.5 h-3.5" />
</button>
<button
onClick={() => setEditTargetUser(u)}
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors"
title="Edit user settings"
>
<Edit2 className="w-3.5 h-3.5" />
</button>
{(() => {
const isOtherCompany =
!isSuperAdmin &&
(u.companyName || 'Ecohub').trim().toLowerCase() !==
(user?.companyName || 'Ecohub').trim().toLowerCase();
const cannotDeleteUser = u.id === user?.id || isOtherCompany;
return (
<button
onClick={() => setDeleteTargetUser(u)}
disabled={cannotDeleteUser}
className="p-1.5 rounded-lg hover:bg-rose-50 text-slate-400 hover:text-rose-600 transition-colors disabled:opacity-20 disabled:pointer-events-none"
title={
u.id === user?.id
? 'Cannot delete your own account'
: isOtherCompany
? 'Admins cannot delete users from other companies (Super Admin only)'
: 'Delete user account'
}
>
<Trash2 className="w-3.5 h-3.5" />
</button>
);
})()}
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
) : (
/* User-Friendly Cards Grid View */
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
{usersList.map((u) => {
const quota = Number(u.storageQuotaBytes);
const used = Number(u.storageUsedBytes);
const pct = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
const isVisible = !!visiblePasswords[u.id];
const orgScope = parseAllowedCompanies(u.allowedCompanies, u.companyName || 'Ecohub');
return (
<div
key={u.id}
className="bg-white rounded-2xl border border-slate-200/80 p-5 shadow-xs hover:shadow-md transition-all flex flex-col justify-between space-y-4"
>
{/* Card Header */}
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-3 min-w-0">
<div
className={`w-11 h-11 rounded-2xl flex items-center justify-center font-bold text-sm shrink-0 shadow-sm ${getAvatarBg(
u.role,
)}`}
>
{getInitials(u.fullName)}
</div>
<div className="min-w-0">
<h3 className="font-bold text-slate-900 text-sm truncate leading-snug">
{u.fullName}
</h3>
<span className="text-[11px] text-slate-500 font-mono block truncate">
@{u.username}
</span>
<span className="text-[11px] text-slate-400 block truncate">{u.email}</span>
</div>
</div>
<div className="flex flex-col items-end gap-1 shrink-0">
<span
className={`px-2 py-0.5 rounded-md text-[10px] font-mono font-bold uppercase ${
u.role === UserRole.SUPER_ADMIN
? 'bg-rose-50 text-rose-700 border border-rose-200'
: u.role === UserRole.ADMIN
? 'bg-amber-50 text-amber-700 border border-amber-200'
: 'bg-slate-100 text-slate-700'
}`}
>
{u.role === UserRole.SUPER_ADMIN ? 'Super Admin' : u.role}
</span>
<span
className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${
u.status === UserStatus.ACTIVE
? 'bg-emerald-50 text-emerald-700'
: u.status === UserStatus.PENDING
? 'bg-amber-50 text-amber-700 border border-amber-200'
: 'bg-rose-50 text-rose-700'
}`}
>
<span
className={`w-1.5 h-1.5 rounded-full ${
u.status === UserStatus.ACTIVE
? 'bg-emerald-500'
: u.status === UserStatus.PENDING
? 'bg-amber-500 animate-pulse'
: 'bg-rose-500'
}`}
/>
<span>{u.status === UserStatus.PENDING ? 'Pending' : u.status}</span>
</span>
</div>
</div>
{/* Company & Permitted Scope */}
<div className="p-3 rounded-xl bg-slate-50 border border-slate-100 space-y-1.5 text-xs">
<div className="flex items-center justify-between">
<span className="text-[11px] text-slate-500 font-medium flex items-center gap-1.5">
<Building2 className="w-3.5 h-3.5 text-emerald-600" />
<span>Company / Org:</span>
</span>
<span className="font-semibold text-slate-800">{u.companyName || 'Ecohub'}</span>
</div>
<div className="flex items-center justify-between text-[11px]">
<span className="text-slate-500 font-medium">Access Scope:</span>
{u.role === UserRole.SUPER_ADMIN || orgScope.all ? (
<span className="font-bold text-purple-700 bg-purple-50 px-1.5 py-0.5 rounded border border-purple-200 text-[10px]">
All Organizations
</span>
) : orgScope.count > 0 ? (
<span
className="font-medium text-sky-700 bg-sky-50 px-1.5 py-0.5 rounded border border-sky-200 text-[10px]"
title={orgScope.list.join(', ')}
>
+{orgScope.count} Other Orgs
</span>
) : (
<span className="text-slate-500 text-[10px]">Own Org Only</span>
)}
</div>
</div>
{/* Storage Progress */}
<div className="space-y-1.5">
<div className="flex justify-between text-[11px] text-slate-600">
<span className="font-semibold text-slate-800 flex items-center gap-1">
<HardDrive className="w-3.5 h-3.5 text-slate-400" />
<span>{formatBytes(used)} used</span>
</span>
<span className="text-slate-400 font-medium">{formatBytes(quota)} quota ({pct}%)</span>
</div>
<div className="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all ${
pct > 90 ? 'bg-rose-500' : 'bg-emerald-500'
}`}
style={{ width: `${pct}%` }}
/>
</div>
</div>
{/* Feature Permissions Interactive Switch Bar */}
<div className="flex items-center justify-between pt-1 border-t border-slate-100 text-xs">
<span className="text-[11px] font-semibold text-slate-500">Permissions:</span>
<div className="flex items-center gap-1.5">
<button
onClick={() => handleToggleSharePermission(u)}
className={`p-1.5 rounded-lg border text-[11px] transition-all flex items-center gap-1 ${
u.canCreateShareLinks
? 'bg-emerald-50 text-emerald-700 border-emerald-200'
: 'bg-slate-50 text-slate-400 border-slate-200'
}`}
title={`Public Link Sharing: ${u.canCreateShareLinks ? 'Enabled' : 'Disabled'}`}
>
<Share2 className="w-3 h-3" />
<span>Share</span>
</button>
<button
onClick={() => handleToggleDeletePermission(u)}
className={`p-1.5 rounded-lg border text-[11px] transition-all flex items-center gap-1 ${
u.canDeleteFiles
? 'bg-sky-50 text-sky-700 border-sky-200'
: 'bg-rose-50 text-rose-700 border-rose-200'
}`}
title={`File Deletion: ${u.canDeleteFiles ? 'Allowed' : 'Blocked'}`}
>
<Trash2 className="w-3 h-3" />
<span>Delete</span>
</button>
{isSuperAdmin && (
<button
onClick={() => handleToggleViewOtherUsersPermission(u)}
disabled={u.role === UserRole.SUPER_ADMIN}
className={`p-1.5 rounded-lg border text-[11px] transition-all flex items-center gap-1 ${
u.role === UserRole.SUPER_ADMIN || u.canViewOtherUsers
? 'bg-purple-50 text-purple-700 border-purple-200'
: 'bg-slate-50 text-slate-400 border-slate-200'
} disabled:opacity-50`}
title="View other users directory"
>
<Eye className="w-3 h-3" />
<span>View</span>
</button>
)}
</div>
</div>
{/* Card Footer Actions */}
<div className="pt-3 border-t border-slate-100 flex items-center justify-between">
<Link
href={`/admin/files?userId=${u.id}`}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 text-xs font-semibold transition-colors"
>
<FolderOpen className="w-3.5 h-3.5" />
<span>Files ({u.fileCount || 0})</span>
</Link>
<div className="flex items-center gap-1">
{u.status === UserStatus.PENDING && (
<button
onClick={() => handleApproveUser(u)}
className="flex items-center gap-1 px-2.5 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold shadow-xs transition-colors shrink-0"
title="Approve user"
>
<Check className="w-3.5 h-3.5" />
<span>Approve</span>
</button>
)}
<button
onClick={() => setResetPasswordTargetUser(u)}
className="p-2 rounded-xl hover:bg-amber-50 text-slate-400 hover:text-amber-600 transition-colors"
title="Reset Password"
>
<KeyRound className="w-4 h-4" />
</button>
<button
onClick={() => setEditTargetUser(u)}
className="p-2 rounded-xl hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors"
title="Edit User"
>
<Edit2 className="w-4 h-4" />
</button>
{(() => {
const isOtherCompany =
!isSuperAdmin &&
(u.companyName || 'Ecohub').trim().toLowerCase() !==
(user?.companyName || 'Ecohub').trim().toLowerCase();
const cannotDeleteUser = u.id === user?.id || isOtherCompany;
return (
<button
onClick={() => setDeleteTargetUser(u)}
disabled={cannotDeleteUser}
className="p-2 rounded-xl hover:bg-rose-50 text-slate-400 hover:text-rose-600 transition-colors disabled:opacity-20 disabled:pointer-events-none"
title={
u.id === user?.id
? 'Cannot delete self'
: isOtherCompany
? 'Admins cannot delete users from other companies (Super Admin only)'
: 'Delete User'
}
>
<Trash2 className="w-4 h-4" />
</button>
);
})()}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
</main>
</div>
<CreateUserModal
isOpen={isCreateOpen}
onClose={() => setIsCreateOpen(false)}
onSuccess={loadUsers}
/>
<EditUserModal
isOpen={!!editTargetUser}
onClose={() => setEditTargetUser(null)}
onSuccess={loadUsers}
user={editTargetUser}
/>
<AdminResetPasswordModal
isOpen={!!resetPasswordTargetUser}
onClose={() => setResetPasswordTargetUser(null)}
onSuccess={loadUsers}
user={resetPasswordTargetUser}
/>
<DeleteUserModal
isOpen={!!deleteTargetUser}
onClose={() => setDeleteTargetUser(null)}
onSuccess={loadUsers}
user={deleteTargetUser}
/>
</div>
);
}

View File

@@ -0,0 +1,325 @@
'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { api } from '@/lib/api-client';
import { formatBytes } from '@/lib/utils';
import { Navbar } from '@/components/layout/Navbar';
import { Sidebar } from '@/components/layout/Sidebar';
import { FileUploaderModal } from '@/components/uploader/FileUploaderModal';
import { FilePreviewModal } from '@/components/file-manager/FilePreviewModal';
import { FileCard } from '@/components/file-manager/FileCard';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import {
HardDrive,
Video,
FileText,
Share2,
UploadCloud,
ArrowRight,
Clock,
Sparkles,
Building2,
FolderOpen,
} from 'lucide-react';
export default function DashboardPage() {
const router = useRouter();
const { user, isLoading, refreshProfile } = useAuth();
const [recentFiles, setRecentFiles] = useState<any[]>([]);
const [sharedCount, setSharedCount] = useState(0);
const [videoCount, setVideoCount] = useState(0);
const [isUploadOpen, setIsUploadOpen] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [selectedFileForPreview, setSelectedFileForPreview] = useState<any | null>(null);
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
useEffect(() => {
if (!isLoading && !user) {
router.push('/login');
}
}, [user, isLoading, router]);
const fetchDashboardData = async (isSilent = false) => {
if (!isSilent) setIsSyncing(true);
try {
const [filesRes, sharedRes]: [any, any] = await Promise.all([
api.get<any>('/files?limit=8&sortBy=date&sortOrder=desc'),
api.get<any>('/sharing/shared-with-me'),
]);
setRecentFiles(filesRes.files || []);
setSharedCount(sharedRes.length || 0);
const videos = (filesRes.files || []).filter((f: any) => f.fileCategory === 'VIDEO');
setVideoCount(videos.length);
setLastSyncedAt(new Date());
} catch (err) {
console.error('Failed to load dashboard data', err);
} finally {
if (!isSilent) setIsSyncing(false);
}
};
useEffect(() => {
if (user) {
fetchDashboardData();
}
}, [user?.id]);
// Periodic Auto-Sync with Database (Silent every 15s + on Window Focus)
useEffect(() => {
if (!user?.id) return;
const interval = setInterval(() => {
if (document.visibilityState === 'visible') {
fetchDashboardData(true);
}
}, 15000);
const handleFocus = () => {
fetchDashboardData(true);
};
window.addEventListener('focus', handleFocus);
return () => {
clearInterval(interval);
window.removeEventListener('focus', handleFocus);
};
}, [user?.id]);
if (isLoading || !user) {
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
<div className="w-8 h-8 border-2 border-emerald-600 border-t-transparent rounded-full animate-spin" />
</div>
);
}
const quota = Number(user.storageQuotaBytes);
const used = Number(user.storageUsedBytes);
const remaining = Math.max(0, quota - used);
const percent = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
<EcohubWatermark variant="corner" />
<Navbar
onOpenUpload={() => setIsUploadOpen(true)}
onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)}
/>
<div className="flex-1 flex min-w-0">
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-8 max-w-7xl w-full mx-auto">
{/* Welcome Header */}
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
<div>
<div className="flex items-center gap-2 flex-wrap">
<h1 className="text-xl sm:text-2xl font-bold text-slate-900 flex items-center gap-2.5">
<span>Welcome back, {user.fullName.split(' ')[0]}</span>
<Sparkles className="w-5 h-5 text-emerald-600" />
</h1>
{user.companyName && (
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
<Building2 className="w-3.5 h-3.5" />
{user.companyName}
</span>
)}
{/* Live Database Sync Badge */}
<div
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
>
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
</div>
</div>
<p className="text-xs text-slate-500 mt-1">
Ecohub encrypted vault & company-wide file explorer active
</p>
</div>
<div className="flex items-center gap-2.5 flex-wrap sm:flex-nowrap">
<button
onClick={() => {
fetchDashboardData(false);
refreshProfile();
}}
disabled={isSyncing}
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
title="Sync with database"
>
<Sparkles className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
<span>Sync DB</span>
</button>
<Link
href="/files"
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 font-medium text-xs shadow-sm transition-all whitespace-nowrap"
>
<FolderOpen className="w-4 h-4 text-emerald-600" />
<span>Company Explorer</span>
</Link>
<button
onClick={() => setIsUploadOpen(true)}
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium text-xs shadow-md shadow-emerald-600/20 transition-all whitespace-nowrap"
>
<UploadCloud className="w-4 h-4" />
<span>Upload Media</span>
</button>
</div>
</div>
{/* Quick Stats Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Storage Quota Card */}
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
<div className="flex items-center justify-between text-slate-500">
<span className="text-xs font-medium">Storage Quota</span>
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600">
<HardDrive className="w-4 h-4" />
</div>
</div>
<div>
<span className="text-xl font-bold text-slate-900">{formatBytes(used)}</span>
<span className="text-xs text-slate-500 ml-1.5">/ {formatBytes(quota)}</span>
</div>
<div className="w-full h-1.5 bg-slate-100 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all ${
percent > 90 ? 'bg-rose-500' : 'bg-emerald-500'
}`}
style={{ width: `${percent}%` }}
/>
</div>
<p className="text-[11px] text-slate-500">{formatBytes(remaining)} remaining</p>
</div>
{/* Total Videos */}
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
<div className="flex items-center justify-between text-slate-500">
<span className="text-xs font-medium">Video Assets</span>
<div className="p-2 rounded-xl bg-sky-50 text-sky-600">
<Video className="w-4 h-4" />
</div>
</div>
<div>
<span className="text-xl font-bold text-slate-900">{videoCount}</span>
<span className="text-xs text-slate-500 ml-1.5">transcoded</span>
</div>
<p className="text-[11px] text-sky-600 font-medium">HLS Streaming & Ecohub Watermark</p>
</div>
{/* Total Files */}
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
<div className="flex items-center justify-between text-slate-500">
<span className="text-xs font-medium">Files In Vault</span>
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600">
<FileText className="w-4 h-4" />
</div>
</div>
<div>
<span className="text-xl font-bold text-slate-900">{recentFiles.length}</span>
<span className="text-xs text-slate-500 ml-1.5">stored</span>
</div>
<p className="text-[11px] text-emerald-600 font-medium">Verified signatures</p>
</div>
{/* Shared With Me */}
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm space-y-3">
<div className="flex items-center justify-between text-slate-500">
<span className="text-xs font-medium">Shared With Me</span>
<div className="p-2 rounded-xl bg-amber-50 text-amber-600">
<Share2 className="w-4 h-4" />
</div>
</div>
<div>
<span className="text-xl font-bold text-slate-900">{sharedCount}</span>
<span className="text-xs text-slate-500 ml-1.5">delegated</span>
</div>
<p className="text-[11px] text-amber-600 font-medium">Granular permissions</p>
</div>
</div>
{/* Recent Uploads Section */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
<Clock className="w-4 h-4 text-emerald-600" />
<span>Recent Uploads</span>
</h2>
<Link
href="/files"
className="text-xs font-medium text-emerald-600 hover:text-emerald-700 flex items-center gap-1"
>
<span>View all in Company Explorer</span>
<ArrowRight className="w-3.5 h-3.5" />
</Link>
</div>
{recentFiles.length === 0 ? (
<div className="p-12 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
<UploadCloud className="w-12 h-12 text-slate-400 mx-auto mb-3" />
<h3 className="text-sm font-medium text-slate-800">No files uploaded yet</h3>
<p className="text-xs text-slate-500 mt-1 max-w-sm mx-auto">
Drag and drop your videos, images, or documents to begin using Ecohub.
</p>
<button
onClick={() => setIsUploadOpen(true)}
className="mt-4 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-medium shadow-sm transition-all"
>
Upload First File
</button>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{recentFiles.map((file) => (
<FileCard
key={file.id}
file={file}
onPreview={(f) => setSelectedFileForPreview(f)}
onRename={() => router.push('/files')}
onMove={() => router.push('/files')}
onDelete={async (f) => {
if (confirm(`Delete file "${f.originalFilename}"?`)) {
await api.delete(`/files/${f.id}`);
fetchDashboardData();
refreshProfile();
}
}}
/>
))}
</div>
)}
</div>
</div>
</main>
</div>
{/* Uploader Modal */}
<FileUploaderModal
isOpen={isUploadOpen}
onClose={() => setIsUploadOpen(false)}
onUploadComplete={() => {
fetchDashboardData();
refreshProfile();
}}
/>
{/* File Preview Modal */}
<FilePreviewModal
isOpen={!!selectedFileForPreview}
onClose={() => setSelectedFileForPreview(null)}
file={selectedFileForPreview}
/>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: #f8fafc;
--foreground: #0f172a;
--card: #ffffff;
--card-foreground: #0f172a;
--primary: #16a34a;
--primary-foreground: #ffffff;
--secondary: #f1f5f9;
--secondary-foreground: #334155;
--muted: #f1f5f9;
--muted-foreground: #64748b;
--accent: #22c55e;
--accent-foreground: #ffffff;
--destructive: #ef4444;
--destructive-foreground: #ffffff;
--border: #e2e8f0;
--input: #e2e8f0;
--ring: #16a34a;
--radius: 0.75rem;
}
}
body {
color: var(--foreground);
background: #f8fafc;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Inter", Helvetica, Arial, sans-serif;
overflow-x: hidden;
background-image:
radial-gradient(at 0% 0%, rgba(34, 197, 94, 0.05) 0px, transparent 45%),
radial-gradient(at 100% 0%, rgba(16, 185, 129, 0.04) 0px, transparent 40%),
radial-gradient(at 50% 100%, rgba(22, 163, 74, 0.03) 0px, transparent 50%);
background-attachment: fixed;
}
/* Custom crisp modern scrollbars */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #f1f5f9;
}
::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 9999px;
}
::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
/* Premium White Glassmorphism & Card styles */
.glass-panel {
background: rgba(255, 255, 255, 0.94);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(226, 232, 240, 0.9);
box-shadow: 0 4px 20px -2px rgba(15, 23, 42, 0.04);
}
.glass-card {
background: #ffffff;
border: 1px solid #e2e8f0;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.03), 0 1px 2px -1px rgba(0, 0, 0, 0.03);
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.glass-card:hover {
border-color: rgba(34, 197, 94, 0.5);
transform: translateY(-2px);
box-shadow: 0 12px 24px -6px rgba(22, 163, 74, 0.12);
}
.glow-card-active {
box-shadow: 0 0 25px -5px rgba(34, 197, 94, 0.25);
border-color: #22c55e;
}
.gradient-text {
background: linear-gradient(135deg, #15803d 0%, #16a34a 50%, #22c55e 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.gradient-border {
position: relative;
background: linear-gradient(135deg, rgba(34, 197, 94, 0.3), rgba(16, 185, 129, 0.1), rgba(34, 197, 94, 0.1));
padding: 1px;
border-radius: 1rem;
}
/* Watermark background animation */
.watermark-bg {
background-image: url('/logo.png');
background-repeat: no-repeat;
background-position: right -40px bottom -40px;
background-size: 280px;
opacity: 0.03;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

View File

@@ -0,0 +1,82 @@
import type { Metadata } from 'next';
import './globals.css';
import { AuthProvider } from '@/context/auth-context';
import { HydrationGuard } from '@/components/common/HydrationGuard';
export const metadata: Metadata = {
title: 'Ecohub - Secure Video & File Sharing Management System',
description: 'Enterprise-grade secure video streaming, file management, and administrator-controlled sharing platform by Ecohub',
icons: {
icon: '/logo.png',
apple: '/logo.png',
},
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
// Intercept extension hydration error noise before Next.js error overlay hooks console
var origError = window.console.error;
window.console.error = function() {
var str = Array.prototype.slice.call(arguments).map(function(arg) {
return typeof arg === 'string' ? arg : (arg && arg.message) || '';
}).join(' ');
if (
str.indexOf('bis_skin_checked') !== -1 ||
str.indexOf('bis_register') !== -1 ||
str.indexOf('cz-shortcut-listen') !== -1 ||
str.indexOf('data-gr-ext-installed') !== -1
) {
return;
}
return origError.apply(window.console, arguments);
};
// Real-time DOM attribute cleaner
try {
var clean = function() {
var els = document.querySelectorAll('[bis_skin_checked], [bis_register]');
for (var i = 0; i < els.length; i++) {
els[i].removeAttribute('bis_skin_checked');
els[i].removeAttribute('bis_register');
}
};
var obs = new MutationObserver(function(mutations) {
for (var i = 0; i < mutations.length; i++) {
var m = mutations[i];
if (m.type === 'attributes' && m.attributeName && m.attributeName.indexOf('bis_') === 0) {
m.target.removeAttribute(m.attributeName);
}
}
});
if (document.documentElement) {
obs.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['bis_skin_checked', 'bis_register']
});
clean();
}
} catch(e) {}
})();
`,
}}
/>
</head>
<body suppressHydrationWarning className="min-h-screen bg-[#f8fafc] text-slate-900 antialiased selection:bg-emerald-500/20 selection:text-emerald-800">
<HydrationGuard />
<AuthProvider>{children}</AuthProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,165 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { EcohubLogo } from '@/components/common/EcohubLogo';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import {
Lock,
User,
Loader2,
ArrowRight,
Eye,
EyeOff,
ShieldCheck,
} from 'lucide-react';
export default function LoginPage() {
const router = useRouter();
const { login } = useAuth();
const [identifier, setIdentifier] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsLoading(true);
try {
await login(identifier, password);
router.push('/dashboard');
} catch (err: any) {
setError(err.message || 'Invalid username or password');
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4 relative overflow-hidden selection:bg-emerald-500/20">
{/* Ambient background glows */}
<div className="absolute top-1/4 -left-20 w-96 h-96 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
<div className="absolute bottom-1/4 -right-20 w-96 h-96 bg-lime-500/10 rounded-full blur-3xl pointer-events-none" />
<div className="w-full max-w-md space-y-6 relative z-10">
{/* Brand Header */}
<div className="text-center space-y-2">
<div className="inline-flex items-center justify-center p-3 rounded-3xl bg-white shadow-xl shadow-slate-200/80 border border-slate-200/80 mb-1">
<EcohubLogo size="xl" showText={false} />
</div>
<div>
<h1 className="text-2xl font-black tracking-tight text-slate-900 flex items-center justify-center gap-1.5">
<span>Ecohub</span>
<span className="text-emerald-600">Cloud</span>
</h1>
<p className="text-xs text-slate-500 mt-1 font-medium">
Enterprise Secure Video & Company File Management
</p>
</div>
</div>
{/* Login Card */}
<div className="bg-white p-7 sm:p-8 rounded-3xl border border-slate-200 shadow-xl shadow-slate-200/50 relative">
<div className="flex items-center justify-between pb-4 border-b border-slate-100 mb-5">
<div>
<h2 className="text-sm font-bold text-slate-900">Sign In</h2>
<p className="text-[11px] text-slate-500">Access your organization files & shared media</p>
</div>
<span className="flex items-center gap-1 text-[11px] font-semibold text-emerald-700 bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-200">
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
Live Vault
</span>
</div>
{error && (
<div className="mb-4 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700 flex items-center gap-2 font-medium">
<span className="w-1.5 h-1.5 rounded-full bg-rose-500 shrink-0" />
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4 text-xs">
{/* Identifier input */}
<div>
<label className="block text-slate-700 font-semibold mb-1.5">
Username or Email Address
</label>
<div className="relative">
<input
type="text"
value={identifier}
onChange={(e) => setIdentifier(e.target.value)}
required
placeholder="e.g. Ecohub or ecohub@fileshare.local"
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
/>
<User className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
</div>
</div>
{/* Password input */}
<div>
<div className="flex items-center justify-between mb-1.5">
<label className="text-slate-700 font-semibold">Password</label>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="text-[11px] text-slate-500 hover:text-emerald-600 flex items-center gap-1 transition"
>
{showPassword ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
<span>{showPassword ? 'Hide' : 'Show'}</span>
</button>
</div>
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
placeholder="Password"
className="w-full pl-9 pr-10 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
/>
<Lock className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
</div>
</div>
{/* Submit button */}
<button
type="submit"
disabled={isLoading}
className="w-full mt-2 py-3 rounded-xl bg-emerald-600 hover:bg-emerald-500 active:scale-[0.99] text-white font-bold text-xs shadow-lg shadow-emerald-600/25 transition-all flex items-center justify-center gap-2 group disabled:opacity-50"
>
{isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<>
<span>Sign In to Ecohub Vault</span>
<ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-0.5 transition-transform" />
</>
)}
</button>
</form>
</div>
{/* Footer Navigation */}
<div className="flex items-center justify-between text-xs text-slate-500 px-2 font-medium">
<span className="flex items-center gap-1">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
Ecohub Enterprise Vault
</span>
<Link href="/register" className="text-emerald-700 hover:text-emerald-800 font-semibold transition">
Create an account &rarr;
</Link>
</div>
</div>
<EcohubWatermark variant="corner" />
</div>
);
}

View File

@@ -0,0 +1,23 @@
import Link from 'next/link';
export default function NotFound() {
return (
<div className="min-h-screen bg-[#f8fafc] flex flex-col items-center justify-center p-4 text-center">
<div className="max-w-md w-full bg-white rounded-2xl shadow-sm border border-slate-200/80 p-8 space-y-4">
<div className="w-16 h-16 bg-emerald-50 text-emerald-600 rounded-full flex items-center justify-center mx-auto text-2xl font-bold">
404
</div>
<h1 className="text-xl font-bold text-slate-800">Page Not Found</h1>
<p className="text-sm text-slate-500">
The page or file share resource you requested does not exist or has been moved.
</p>
<Link
href="/dashboard"
className="inline-flex items-center justify-center w-full px-4 py-2.5 text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-xl transition shadow-sm"
>
Return to Dashboard
</Link>
</div>
</div>
);
}

View File

@@ -0,0 +1,27 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { Loader2 } from 'lucide-react';
export default function RootPage() {
const { user, isLoading } = useAuth();
const router = useRouter();
useEffect(() => {
if (!isLoading) {
if (user) {
router.replace('/files');
} else {
router.replace('/login');
}
}
}, [user, isLoading, router]);
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
);
}

View File

@@ -0,0 +1,229 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { EcohubLogo } from '@/components/common/EcohubLogo';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import { Lock, User, Mail, Loader2, ArrowRight, Building2, Clock } from 'lucide-react';
export default function RegisterPage() {
const router = useRouter();
const { register } = useAuth();
const [fullName, setFullName] = useState('');
const [username, setUsername] = useState('');
const [companyName, setCompanyName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isSubmitted, setIsSubmitted] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsLoading(true);
try {
const res: any = await register({
email,
username,
fullName,
password,
companyName: companyName.trim() || undefined,
});
if (res?.pendingApproval) {
setIsSubmitted(true);
} else {
router.push('/dashboard');
}
} catch (err: any) {
setError(err.message || 'Registration failed');
} finally {
setIsLoading(false);
}
};
if (isSubmitted) {
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4 relative overflow-hidden">
<EcohubWatermark variant="corner" />
<div className="w-full max-w-md bg-white p-8 rounded-3xl border border-slate-200 shadow-xl shadow-slate-200/50 text-center space-y-5 relative z-10">
<div className="w-16 h-16 rounded-2xl bg-amber-50 border border-amber-200 flex items-center justify-center text-amber-600 mx-auto shadow-inner">
<Clock className="w-8 h-8" />
</div>
<div>
<h2 className="text-xl font-black text-slate-900">Account Pending Approval</h2>
<p className="text-xs text-slate-500 mt-1 font-medium">
Administrator or Super Admin review required
</p>
</div>
<div className="p-4 bg-slate-50 border border-slate-200 rounded-2xl text-left text-xs space-y-1.5">
<div className="flex justify-between">
<span className="text-slate-500">Full Name:</span>
<span className="font-semibold text-slate-800">{fullName}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-500">Username:</span>
<span className="font-mono font-semibold text-slate-800">@{username}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-500">Organization:</span>
<span className="font-semibold text-slate-800">{companyName.trim() || 'Ecohub'}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-500">Status:</span>
<span className="font-bold text-amber-700 bg-amber-100 px-2 py-0.5 rounded text-[10px]">
PENDING APPROVAL
</span>
</div>
</div>
<p className="text-[11px] text-slate-600 leading-relaxed">
Your registration is received! For system security, an <strong>Administrator</strong> or <strong>Super Admin</strong> must activate your account before you can log in.
</p>
<Link
href="/login"
className="inline-flex items-center justify-center w-full py-3 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs shadow-md shadow-emerald-600/20 transition-all"
>
Back to Sign In
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4 relative overflow-hidden">
{/* Ambient background glows */}
<div className="absolute top-1/4 -left-20 w-96 h-96 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
<div className="absolute bottom-1/4 -right-20 w-96 h-96 bg-lime-500/10 rounded-full blur-3xl pointer-events-none" />
<div className="w-full max-w-md space-y-6 relative z-10">
<div className="text-center space-y-2">
<div className="inline-flex items-center justify-center p-3 rounded-3xl bg-white shadow-xl shadow-slate-200/80 border border-slate-200/80 mb-1">
<EcohubLogo size="xl" showText={false} />
</div>
<h2 className="text-2xl font-black text-slate-900 tracking-tight">
Create Ecohub Account
</h2>
<p className="text-xs text-slate-500">
Receive private company storage space and instant video processing
</p>
</div>
<div className="bg-white p-7 sm:p-8 rounded-3xl border border-slate-200 shadow-xl shadow-slate-200/50">
{error && (
<div className="mb-4 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700 font-medium">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-3.5 text-xs">
<div>
<label className="block text-slate-700 font-semibold mb-1.5">Full Name</label>
<div className="relative">
<input
type="text"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
required
placeholder="e.g. John Doe"
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
/>
<User className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
</div>
</div>
<div>
<label className="block text-slate-700 font-semibold mb-1.5">
Company / Organization Name
</label>
<div className="relative">
<input
type="text"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
placeholder="e.g. Ecohub Technologies / Acme Corp"
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
/>
<Building2 className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-slate-700 font-semibold mb-1.5">Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
placeholder="john_doe"
className="w-full px-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
/>
</div>
<div>
<label className="block text-slate-700 font-semibold mb-1.5">Email Address</label>
<div className="relative">
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
placeholder="john@example.com"
className="w-full pl-8 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
/>
<Mail className="w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-3" />
</div>
</div>
</div>
<div>
<label className="block text-slate-700 font-semibold mb-1.5">Password</label>
<div className="relative">
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
placeholder="Minimum 8 characters"
className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 focus:ring-1 focus:ring-emerald-600 transition"
/>
<Lock className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
</div>
</div>
<button
type="submit"
disabled={isLoading}
className="w-full py-3 rounded-xl bg-emerald-600 hover:bg-emerald-500 active:scale-[0.99] text-white font-bold text-xs shadow-lg shadow-emerald-600/25 transition-all flex items-center justify-center gap-2 mt-4"
>
{isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<>
<span>Create Account & Initialize Vault</span>
<ArrowRight className="w-3.5 h-3.5" />
</>
)}
</button>
</form>
</div>
<p className="text-center text-xs text-slate-500">
Already registered?{' '}
<Link href="/login" className="text-emerald-700 hover:text-emerald-800 font-bold">
Sign In
</Link>
</p>
</div>
<EcohubWatermark variant="corner" />
</div>
);
}

View File

@@ -0,0 +1,605 @@
'use client';
import React, { useState, useEffect, useCallback, use } from 'react';
import { api } from '@/lib/api-client';
import { formatBytes, formatDuration, formatDate } from '@/lib/utils';
import { EcohubLogo } from '@/components/common/EcohubLogo';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import {
FileVideo,
FileText,
FileSpreadsheet,
FileCode,
FileArchive,
File as FileIcon,
Folder,
Download,
Lock,
Eye,
EyeOff,
ChevronRight,
Play,
AlertCircle,
Loader2,
Clock,
X,
} from 'lucide-react';
interface PublicFile {
id: string;
originalFilename: string;
mimeType: string;
fileExtension: string;
fileSizeBytes: string;
fileCategory: string;
status: string;
durationSeconds?: number | null;
width?: number | null;
height?: number | null;
hasThumbnail?: boolean;
hasHlsStream?: boolean;
createdAt: string;
}
interface PublicSubfolder {
id: string;
name: string;
logicalPath: string;
fileCount: number;
subfolderCount: number;
createdAt: string;
}
interface PublicResourceResponse {
requiresPassword?: boolean;
title?: string;
resourceType?: 'FILE' | 'FOLDER';
allowDownload?: boolean;
ownerName?: string;
createdAt?: string;
expiresAt?: string | null;
file?: PublicFile;
rootFolderId?: string;
currentFolder?: {
id: string;
name: string;
logicalPath: string;
isRootOfShare: boolean;
};
subfolders?: PublicSubfolder[];
files?: PublicFile[];
}
export default function PublicSharePage({ params }: { params: Promise<{ token: string }> }) {
const unwrappedParams = use(params);
const token = unwrappedParams.token;
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<PublicResourceResponse | null>(null);
// Password state
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [passwordError, setPasswordError] = useState<string | null>(null);
const [isSubmittingPassword, setIsSubmittingPassword] = useState(false);
// Folder navigation state
const [currentSubfolderId, setCurrentSubfolderId] = useState<string | undefined>(undefined);
const [folderHistory, setFolderHistory] = useState<{ id?: string; name: string }[]>([]);
// Preview/Player modal for files inside shared folders
const [activeVideoModal, setActiveVideoModal] = useState<PublicFile | null>(null);
const fetchResource = useCallback(
async (pwd?: string, subfolderId?: string) => {
setIsLoading(true);
setError(null);
setPasswordError(null);
try {
const res = await api.getPublicShareResource(token, pwd || password, subfolderId);
setData(res);
if (!res.requiresPassword && subfolderId === undefined && res.resourceType === 'FOLDER') {
setFolderHistory([{ id: undefined, name: res.title || 'Shared Folder' }]);
}
} catch (err: any) {
if (err.message && err.message.toLowerCase().includes('password')) {
setPasswordError('Incorrect password. Please try again.');
} else {
setError(err.message || 'Failed to load shared content');
}
} finally {
setIsLoading(false);
}
},
[token, password],
);
useEffect(() => {
fetchResource();
}, [fetchResource]);
const handlePasswordSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!password.trim()) {
setPasswordError('Please enter the password');
return;
}
setIsSubmittingPassword(true);
await fetchResource(password.trim(), currentSubfolderId);
setIsSubmittingPassword(false);
};
const handleNavigateSubfolder = (subfolder: PublicSubfolder) => {
setCurrentSubfolderId(subfolder.id);
setFolderHistory((prev) => [...prev, { id: subfolder.id, name: subfolder.name }]);
fetchResource(password, subfolder.id);
};
const handleBreadcrumbClick = (index: number) => {
const target = folderHistory[index];
const newHistory = folderHistory.slice(0, index + 1);
setFolderHistory(newHistory);
setCurrentSubfolderId(target.id);
fetchResource(password, target.id);
};
const renderFileIcon = (category: string, mime: string) => {
if (category === 'VIDEO' || mime.startsWith('video/')) {
return <FileVideo className="w-8 h-8 text-rose-500" />;
}
if (category === 'IMAGE' || mime.startsWith('image/')) {
return <FileIcon className="w-8 h-8 text-emerald-600" />;
}
if (category === 'AUDIO' || mime.startsWith('audio/')) {
return <FileSpreadsheet className="w-8 h-8 text-amber-500" />;
}
if (category === 'DOCUMENT') {
return <FileText className="w-8 h-8 text-sky-500" />;
}
if (category === 'ARCHIVE') {
return <FileArchive className="w-8 h-8 text-emerald-600" />;
}
return <FileCode className="w-8 h-8 text-slate-500" />;
};
// 1. Loading State
if (isLoading && !data) {
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col items-center justify-center p-4">
<div className="flex flex-col items-center gap-3">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
<p className="text-xs text-slate-500 font-medium tracking-wide">Loading Ecohub shared link...</p>
</div>
</div>
);
}
// 2. Error State
if (error) {
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col items-center justify-center p-4">
<div className="w-full max-w-md p-8 rounded-3xl bg-white border border-slate-200 shadow-xl text-center space-y-4">
<div className="w-14 h-14 rounded-2xl bg-rose-50 border border-rose-200 text-rose-600 flex items-center justify-center mx-auto">
<AlertCircle className="w-7 h-7" />
</div>
<div>
<h2 className="text-lg font-bold text-slate-900">Unable to Access Link</h2>
<p className="text-xs text-slate-500 mt-1.5 leading-relaxed">{error}</p>
</div>
<button
onClick={() => window.location.reload()}
className="px-5 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-xs font-semibold text-slate-700 transition-colors"
>
Try Again
</button>
</div>
</div>
);
}
// 3. Password Protection Screen
if (data?.requiresPassword) {
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col items-center justify-center p-4">
<div className="w-full max-w-md p-8 rounded-3xl bg-white border border-slate-200 shadow-xl space-y-6">
<div className="flex justify-center mb-2">
<EcohubLogo size="md" showText={true} />
</div>
<div className="text-center space-y-2">
<div className="w-14 h-14 rounded-2xl bg-emerald-50 border border-emerald-200 text-emerald-600 flex items-center justify-center mx-auto shadow-inner">
<Lock className="w-7 h-7" />
</div>
<h2 className="text-lg font-bold text-slate-900">Password Protected</h2>
<p className="text-xs text-slate-500">
{data.ownerName ? `Shared by ${data.ownerName}. ` : ''}
Please enter the password to view this content.
</p>
</div>
<form onSubmit={handlePasswordSubmit} className="space-y-4">
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password"
autoFocus
required
className="w-full px-4 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 transition-all pr-10"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-2.5 text-slate-400 hover:text-slate-600"
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
{passwordError && (
<p className="text-[11px] text-rose-600 flex items-center gap-1 font-medium">
<AlertCircle className="w-3.5 h-3.5 flex-shrink-0" />
{passwordError}
</p>
)}
<button
type="submit"
disabled={isSubmittingPassword}
className="w-full py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white text-xs font-semibold shadow-md shadow-emerald-600/25 transition-all flex items-center justify-center gap-2"
>
{isSubmittingPassword && <Loader2 className="w-4 h-4 animate-spin" />}
<span>Unlock Content</span>
</button>
</form>
</div>
</div>
);
}
// 4. Main Shared Content View (File or Folder)
const isVideo =
data?.file &&
(data.file.fileCategory === 'VIDEO' || data.file.mimeType.startsWith('video/'));
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative selection:bg-emerald-500/20">
<EcohubWatermark variant="corner" />
{/* Top Header Bar */}
<header className="h-16 px-6 sm:px-10 border-b border-slate-200 bg-white/90 backdrop-blur-md flex items-center justify-between sticky top-0 z-40 shadow-sm">
<div className="flex items-center gap-3">
<EcohubLogo size="sm" showText={true} />
<span className="hidden sm:inline text-[10px] uppercase px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 font-semibold">
Secure Share Link
</span>
</div>
<div className="flex items-center gap-3 text-xs">
{data?.expiresAt && (
<span className="hidden sm:flex items-center gap-1 text-[11px] text-slate-500">
<Clock className="w-3.5 h-3.5 text-amber-500" />
Expires {formatDate(data.expiresAt)}
</span>
)}
{data?.resourceType === 'FILE' && data.file && data.allowDownload && (
<a
href={api.getPublicShareDownloadUrl(token, password)}
download
className="flex items-center gap-1.5 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium shadow-sm transition-all"
>
<Download className="w-3.5 h-3.5" />
<span>Download File</span>
</a>
)}
</div>
</header>
{/* Main Container */}
<main className="flex-1 p-4 sm:p-8 max-w-6xl w-full mx-auto space-y-6">
{/* CASE A: SHARED SINGLE FILE */}
{data?.resourceType === 'FILE' && data.file && (
<div className="space-y-6">
{/* If Video: Embedded Player with Ecohub Watermark */}
{isVideo ? (
<div className="rounded-3xl overflow-hidden bg-black border border-slate-200 shadow-xl relative aspect-video max-h-[72vh] flex items-center justify-center">
{/* Ecohub Watermark overlay on the video */}
<EcohubWatermark variant="player" className="absolute top-4 left-4 z-20" />
<video
controls
controlsList="nodownload"
autoPlay={false}
playsInline
src={api.getPublicSharePlaybackUrl(token, password)}
poster={
data.file.hasThumbnail
? api.getPublicShareThumbnailUrl(token, password)
: undefined
}
className="w-full h-full object-contain"
>
Your browser does not support HTML5 video playback.
</video>
</div>
) : data.file.fileCategory === 'IMAGE' ? (
<div className="rounded-3xl overflow-hidden bg-white border border-slate-200 shadow-md p-4 flex items-center justify-center max-h-[70vh] relative">
<EcohubWatermark variant="corner" />
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={api.getPublicSharePlaybackUrl(token, password)}
alt={data.file.originalFilename}
className="max-h-[66vh] max-w-full rounded-2xl object-contain"
/>
</div>
) : (
/* Non-video, non-image file placeholder view */
<div className="rounded-3xl bg-white border border-slate-200 p-12 text-center space-y-4 shadow-sm relative">
<EcohubWatermark variant="subtle" />
<div className="w-20 h-20 rounded-3xl bg-slate-50 border border-slate-200 flex items-center justify-center mx-auto shadow-sm">
{renderFileIcon(data.file.fileCategory, data.file.mimeType)}
</div>
<div>
<h2 className="text-xl font-bold text-slate-900">{data.file.originalFilename}</h2>
<p className="text-xs text-slate-500 mt-1">
{formatBytes(data.file.fileSizeBytes)} • {data.file.mimeType}
</p>
</div>
{data.allowDownload ? (
<a
href={api.getPublicShareDownloadUrl(token, password)}
download
className="inline-flex items-center gap-2 px-6 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold shadow-md transition-all"
>
<Download className="w-4 h-4" />
<span>Download File ({formatBytes(data.file.fileSizeBytes)})</span>
</a>
) : (
<p className="text-xs text-amber-700 bg-amber-50 border border-amber-200 px-4 py-2 rounded-xl inline-block">
Direct download is disabled by the owner of this link.
</p>
)}
</div>
)}
{/* File Metadata Card */}
<div className="rounded-2xl bg-white border border-slate-200 p-5 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-base font-semibold text-slate-900">{data.file.originalFilename}</h1>
<div className="flex flex-wrap items-center gap-3 text-xs text-slate-500 mt-1">
<span>Size: {formatBytes(data.file.fileSizeBytes)}</span>
<span>•</span>
<span>Format: {data.file.fileExtension.toUpperCase()}</span>
{data.file.durationSeconds && (
<>
<span>•</span>
<span>Duration: {formatDuration(data.file.durationSeconds)}</span>
</>
)}
{data.file.width && data.file.height && (
<>
<span>•</span>
<span>
Resolution: {data.file.width}x{data.file.height}
</span>
</>
)}
<span>•</span>
<span>Uploaded: {formatDate(data.file.createdAt)}</span>
</div>
</div>
{data.allowDownload && (
<a
href={api.getPublicShareDownloadUrl(token, password)}
download
className="flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 text-xs font-medium transition-colors"
>
<Download className="w-4 h-4" />
<span>Download</span>
</a>
)}
</div>
</div>
)}
{/* CASE B: SHARED FOLDER */}
{data?.resourceType === 'FOLDER' && (
<div className="space-y-6">
{/* Folder Breadcrumb & Info Header */}
<div className="rounded-2xl bg-white border border-slate-200 p-5 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center">
<Folder className="w-4 h-4" />
</div>
<h1 className="text-lg font-bold text-slate-900">{data.title || 'Shared Folder'}</h1>
</div>
{/* Subfolder Breadcrumb Navigation */}
<div className="flex items-center gap-1.5 text-xs text-slate-500">
{folderHistory.map((item, idx) => (
<React.Fragment key={idx}>
{idx > 0 && <ChevronRight className="w-3.5 h-3.5 text-slate-400" />}
<button
onClick={() => handleBreadcrumbClick(idx)}
className={`hover:text-emerald-600 transition-colors ${
idx === folderHistory.length - 1 ? 'text-slate-900 font-semibold' : ''
}`}
>
{item.name}
</button>
</React.Fragment>
))}
</div>
</div>
<div className="text-xs text-slate-500 flex items-center gap-4">
<span>
{data.subfolders?.length || 0} Folders • {data.files?.length || 0} Files
</span>
{!data.allowDownload && (
<span className="px-2 py-0.5 rounded-md bg-amber-50 border border-amber-200 text-amber-700 text-[10px]">
Downloads Restricted
</span>
)}
</div>
</div>
{/* Subfolders Grid */}
{data.subfolders && data.subfolders.length > 0 && (
<div className="space-y-2">
<h3 className="text-xs font-semibold text-slate-600 uppercase tracking-wider">
Folders ({data.subfolders.length})
</h3>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
{data.subfolders.map((sf) => (
<div
key={sf.id}
onClick={() => handleNavigateSubfolder(sf)}
className="p-3.5 rounded-xl bg-white border border-slate-200 hover:border-emerald-500 hover:shadow-sm cursor-pointer transition-all flex items-center gap-3 group"
>
<Folder className="w-5 h-5 text-emerald-600 group-hover:scale-105 transition-transform" />
<div className="truncate flex-1">
<p className="text-xs font-semibold text-slate-800 truncate">{sf.name}</p>
<p className="text-[10px] text-slate-500">
{sf.fileCount} files • {sf.subfolderCount} folders
</p>
</div>
</div>
))}
</div>
</div>
)}
{/* Files Grid */}
<div className="space-y-2">
<h3 className="text-xs font-semibold text-slate-600 uppercase tracking-wider">
Files ({data.files?.length || 0})
</h3>
{data.files && data.files.length > 0 ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{data.files.map((file) => {
const isVid =
file.fileCategory === 'VIDEO' || file.mimeType.startsWith('video/');
return (
<div
key={file.id}
className="rounded-2xl bg-white border border-slate-200 hover:border-emerald-300 p-4 shadow-sm hover:shadow-md transition-all flex flex-col justify-between group"
>
<div className="flex items-start gap-3">
<div className="w-10 h-10 rounded-xl bg-slate-50 border border-slate-200 flex items-center justify-center flex-shrink-0">
{renderFileIcon(file.fileCategory, file.mimeType)}
</div>
<div className="min-w-0 flex-1">
<h4
className="text-xs font-semibold text-slate-800 truncate group-hover:text-emerald-700 transition-colors"
title={file.originalFilename}
>
{file.originalFilename}
</h4>
<p className="text-[10px] text-slate-500 mt-0.5">
{formatBytes(file.fileSizeBytes)}
{file.durationSeconds && ` • ${formatDuration(file.durationSeconds)}`}
</p>
</div>
</div>
{/* Thumbnail / Action Bar */}
<div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
{isVid ? (
<button
onClick={() => setActiveVideoModal(file)}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 text-emerald-700 hover:bg-emerald-600 hover:text-white transition-colors font-medium text-[11px]"
>
<Play className="w-3 h-3 fill-current" />
<span>Play Video</span>
</button>
) : (
<span className="text-[10px] text-slate-500 uppercase tracking-wider font-semibold">
{file.fileExtension}
</span>
)}
{data.allowDownload && (
<a
href={api.getPublicShareDownloadUrl(token, password, file.id)}
download
className="p-1.5 rounded-lg text-slate-400 hover:text-emerald-600 hover:bg-slate-100 transition-colors"
title="Download"
>
<Download className="w-4 h-4" />
</a>
)}
</div>
</div>
);
})}
</div>
) : (
<div className="rounded-2xl bg-white border border-slate-200 p-12 text-center text-slate-400 text-xs shadow-sm">
This folder does not contain any files.
</div>
)}
</div>
</div>
)}
</main>
{/* Embedded Video Modal when playing a file inside a shared folder */}
{activeVideoModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/80 backdrop-blur-md">
<div className="w-full max-w-4xl bg-white border border-slate-200 rounded-3xl overflow-hidden shadow-2xl flex flex-col">
<div className="p-4 border-b border-slate-200 flex items-center justify-between">
<div className="truncate pr-4">
<h3 className="text-sm font-semibold text-slate-900 truncate">
{activeVideoModal.originalFilename}
</h3>
<p className="text-[10px] text-slate-500">
{formatBytes(activeVideoModal.fileSizeBytes)}
</p>
</div>
<button
onClick={() => setActiveVideoModal(null)}
className="p-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors"
>
<X className="w-4 h-4" />
</button>
</div>
<div className="bg-black aspect-video flex items-center justify-center relative">
<EcohubWatermark variant="player" className="absolute top-4 left-4 z-20" />
<video
controls
controlsList="nodownload"
autoPlay
playsInline
src={api.getPublicSharePlaybackUrl(token, password, activeVideoModal.id)}
className="w-full h-full object-contain"
>
Your browser does not support HTML5 video playback.
</video>
</div>
{data?.allowDownload && (
<div className="p-3 bg-slate-50 border-t border-slate-200 flex justify-end">
<a
href={api.getPublicShareDownloadUrl(token, password, activeVideoModal.id)}
download
className="flex items-center gap-1.5 px-4 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-semibold shadow-sm transition-all"
>
<Download className="w-3.5 h-3.5" />
<span>Download Video</span>
</a>
</div>
)}
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,229 @@
'use client';
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { api } from '@/lib/api-client';
import { Navbar } from '@/components/layout/Navbar';
import { Sidebar } from '@/components/layout/Sidebar';
import { FileCard } from '@/components/file-manager/FileCard';
import { FileRow } from '@/components/file-manager/FileRow';
import { FilePreviewModal } from '@/components/file-manager/FilePreviewModal';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import { Share2, Users, LayoutGrid, List, Search, Loader2, RefreshCw } from 'lucide-react';
export default function SharedPage() {
const router = useRouter();
const { user, isLoading } = useAuth();
const [sharedFiles, setSharedFiles] = useState<any[]>([]);
const [isDataLoading, setIsDataLoading] = useState(true);
const [isSyncing, setIsSyncing] = useState(false);
const [lastSyncedAt, setLastSyncedAt] = useState<Date | null>(null);
const [search, setSearch] = useState('');
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [selectedFileForPreview, setSelectedFileForPreview] = useState<any | null>(null);
useEffect(() => {
if (!isLoading && !user) {
router.push('/login');
}
}, [user, isLoading, router]);
const loadSharedFiles = async (isSilent = false) => {
if (!user) return;
if (!isSilent) setIsDataLoading(true);
setIsSyncing(true);
try {
const files = await api.get<any[]>('/sharing/shared-with-me');
setSharedFiles(files || []);
setLastSyncedAt(new Date());
} catch (err) {
console.error('Failed to load shared files', err);
} finally {
if (!isSilent) setIsDataLoading(false);
setIsSyncing(false);
}
};
useEffect(() => {
loadSharedFiles();
}, [user]);
// Periodic Auto-Sync with Database (Silent every 8s + on Window Focus)
useEffect(() => {
if (!user) return;
const interval = setInterval(() => {
if (document.visibilityState === 'visible') {
loadSharedFiles(true);
}
}, 8000);
const handleFocus = () => {
loadSharedFiles(true);
};
window.addEventListener('focus', handleFocus);
return () => {
clearInterval(interval);
window.removeEventListener('focus', handleFocus);
};
}, [user]);
const filtered = sharedFiles.filter((f) =>
f.originalFilename.toLowerCase().includes(search.toLowerCase()),
);
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
<EcohubWatermark variant="corner" />
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
<div className="flex-1 flex min-w-0">
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
<main className="flex-1 lg:pl-64 min-w-0 flex flex-col w-full">
<div className="flex-1 p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl w-full mx-auto">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<div className="flex items-center gap-2 flex-wrap">
<h1 className="text-xl font-bold text-slate-900 flex items-center gap-2.5">
<Share2 className="w-5 h-5 text-emerald-600" />
<span>Shared With Me</span>
</h1>
{/* Live Database Sync Badge */}
<div
className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200/80 text-[11px] font-semibold"
title={lastSyncedAt ? `Live Auto-Sync Active • Last synced: ${lastSyncedAt.toLocaleTimeString()}` : 'Live Auto-Sync Active'}
>
<span className={`w-2 h-2 rounded-full ${isSyncing ? 'bg-amber-500 animate-spin' : 'bg-emerald-500 animate-pulse'}`} />
<span>{isSyncing ? 'Syncing...' : 'Live DB Sync'}</span>
</div>
</div>
<p className="text-xs text-slate-500 mt-1">
Files and media shared with you by system administrators
</p>
</div>
<div className="flex items-center gap-2.5 flex-wrap sm:flex-nowrap">
{/* Manual Sync Button */}
<button
onClick={() => loadSharedFiles(false)}
disabled={isSyncing}
className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold shadow-xs transition-all active:scale-95 disabled:opacity-50"
title="Sync with database"
>
<RefreshCw className={`w-3.5 h-3.5 text-emerald-600 ${isSyncing ? 'animate-spin' : ''}`} />
<span>Sync DB</span>
</button>
{/* Search */}
<div className="relative w-48 sm:w-64 text-xs">
<Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-2.5" />
<input
type="text"
placeholder="Search shared files..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full pl-8 pr-3 py-1.5 rounded-xl bg-white border border-slate-200 text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-600 shadow-sm"
/>
</div>
{/* View toggle */}
<div className="flex items-center p-0.5 rounded-lg bg-white border border-slate-200 shadow-sm">
<button
onClick={() => setViewMode('grid')}
className={`p-1.5 rounded-md ${
viewMode === 'grid' ? 'bg-emerald-600 text-white' : 'text-slate-500 hover:text-slate-800'
}`}
>
<LayoutGrid className="w-3.5 h-3.5" />
</button>
<button
onClick={() => setViewMode('list')}
className={`p-1.5 rounded-md ${
viewMode === 'list' ? 'bg-emerald-600 text-white' : 'text-slate-500 hover:text-slate-800'
}`}
>
<List className="w-3.5 h-3.5" />
</button>
</div>
</div>
</div>
{/* Content */}
{isDataLoading ? (
<div className="p-16 flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
) : filtered.length === 0 ? (
<div className="p-16 text-center rounded-2xl bg-white border border-slate-200 shadow-sm">
<Users className="w-12 h-12 text-slate-400 mx-auto mb-3" />
<h3 className="text-sm font-medium text-slate-800">No shared files yet</h3>
<p className="text-xs text-slate-500 mt-1 max-w-sm mx-auto">
When an administrator grants you access to another user's files or videos, they will appear here.
</p>
</div>
) : viewMode === 'grid' ? (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{filtered.map((file) => (
<FileCard
key={file.id}
file={file}
isOwner={false}
onPreview={(f) => setSelectedFileForPreview(f)}
onRename={() => {}}
onMove={() => {}}
onDelete={() => {}}
/>
))}
</div>
) : (
<div className="bg-white rounded-2xl overflow-hidden border border-slate-200 shadow-sm">
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-left border-collapse">
<thead>
<tr className="border-b border-slate-200 bg-slate-50 text-[11px] font-semibold text-slate-500 uppercase tracking-wider">
<th className="py-3 px-4">Filename</th>
<th className="py-3 px-4 hidden md:table-cell">Category</th>
<th className="py-3 px-4">Size</th>
<th className="py-3 px-4 hidden sm:table-cell">Uploaded</th>
<th className="py-3 px-4">Status</th>
<th className="py-3 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody>
{filtered.map((file) => (
<FileRow
key={file.id}
file={file}
isOwner={false}
onPreview={(f) => setSelectedFileForPreview(f)}
onRename={() => {}}
onMove={() => {}}
onDelete={() => {}}
/>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
</main>
</div>
{/* Preview Modal */}
<FilePreviewModal
isOpen={!!selectedFileForPreview}
onClose={() => setSelectedFileForPreview(null)}
file={selectedFileForPreview}
/>
</div>
);
}

View File

@@ -0,0 +1,198 @@
'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { api } from '@/lib/api-client';
import { formatBytes, formatDate } from '@/lib/utils';
import { Navbar } from '@/components/layout/Navbar';
import { Sidebar } from '@/components/layout/Sidebar';
import { HlsVideoPlayer } from '@/components/video-player/HlsVideoPlayer';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import {
ArrowLeft,
Download,
Video,
Calendar,
HardDrive,
Layers,
Loader2,
AlertTriangle,
Building2,
} from 'lucide-react';
export default function VideoPlayerPage() {
const params = useParams();
const fileId = params?.id as string;
const router = useRouter();
const { user, isLoading } = useAuth();
const [file, setFile] = useState<any | null>(null);
const [isDataLoading, setIsDataLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
useEffect(() => {
if (!isLoading && !user) {
router.push('/login');
}
}, [user, isLoading, router]);
useEffect(() => {
if (fileId && user) {
setIsDataLoading(true);
setError(null);
api.get<any>(`/files/${fileId}`)
.then((res) => {
setFile(res);
})
.catch((err) => {
setError(err.message || 'Access denied or video not found');
})
.finally(() => {
setIsDataLoading(false);
});
}
}, [fileId, user]);
if (isLoading || isDataLoading) {
return (
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center">
<Loader2 className="w-8 h-8 text-emerald-600 animate-spin" />
</div>
);
}
const canDownload = file?.permissions ? file.permissions.canDownload : true;
const downloadUrl = file ? api.getDownloadUrl(file.id) : '#';
return (
<div className="min-h-screen bg-[#f8fafc] text-slate-900 flex flex-col relative">
<EcohubWatermark variant="corner" />
<Navbar onToggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)} />
<div className="flex-1 flex">
<Sidebar isOpen={isSidebarOpen} onClose={() => setIsSidebarOpen(false)} />
<main className="flex-1 lg:pl-64 p-6 sm:p-8 space-y-6 max-w-6xl mx-auto w-full">
{/* Back button */}
<div>
<Link
href="/files"
className="inline-flex items-center gap-2 text-xs font-medium text-slate-600 hover:text-emerald-700 transition-colors"
>
<ArrowLeft className="w-4 h-4" />
<span>Back to Company Explorer</span>
</Link>
</div>
{error ? (
<div className="p-12 text-center rounded-2xl bg-rose-50 border border-rose-200 max-w-lg mx-auto shadow-sm">
<AlertTriangle className="w-12 h-12 text-rose-600 mx-auto mb-3" />
<h3 className="text-base font-semibold text-rose-900">Access Denied</h3>
<p className="text-xs text-rose-700 mt-1">{error}</p>
<Link
href="/files"
className="mt-4 inline-block px-4 py-2 rounded-xl bg-slate-100 text-slate-800 text-xs font-medium hover:bg-slate-200"
>
Return to Files
</Link>
</div>
) : file ? (
<div className="space-y-6">
{/* Player Container */}
<div className="w-full">
<HlsVideoPlayer
fileId={file.id}
hasHlsStream={file.hasHlsStream}
title={file.originalFilename}
durationSeconds={file.durationSeconds}
width={file.width}
height={file.height}
videoCodec={file.videoCodec}
/>
</div>
{/* Title & Actions Bar */}
<div className="p-5 rounded-2xl bg-white border border-slate-200 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-lg font-bold text-slate-900">{file.originalFilename}</h1>
<div className="flex items-center gap-2 mt-1">
<p className="text-xs text-slate-500">
Uploaded by {file.ownerName || 'User'} ({file.ownerEmail})
</p>
{file.ownerCompanyName && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
<Building2 className="w-3 h-3" />
{file.ownerCompanyName}
</span>
)}
</div>
</div>
<div className="flex items-center gap-3">
{canDownload ? (
<a
href={downloadUrl}
download={file.originalFilename}
className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium text-xs shadow-md shadow-emerald-600/20 transition-all"
>
<Download className="w-4 h-4" />
<span>Download Video</span>
</a>
) : (
<span className="text-xs text-slate-500 italic bg-slate-50 px-3 py-1.5 rounded-lg border border-slate-200">
Download permission not granted
</span>
)}
</div>
</div>
{/* Technical Video Metadata */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
<Video className="w-3.5 h-3.5 text-emerald-600" /> Resolution
</span>
<span className="text-sm font-semibold text-slate-900">
{file.width && file.height ? `${file.width} x ${file.height}` : 'Standard'}
</span>
</div>
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
<Layers className="w-3.5 h-3.5 text-sky-600" /> Codecs
</span>
<span className="text-sm font-semibold text-slate-900 uppercase font-mono">
{file.videoCodec || 'H.264'} / {file.audioCodec || 'AAC'}
</span>
</div>
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
<HardDrive className="w-3.5 h-3.5 text-emerald-600" /> File Size
</span>
<span className="text-sm font-semibold text-slate-900">
{formatBytes(file.fileSizeBytes)}
</span>
</div>
<div className="p-4 rounded-xl bg-white border border-slate-200 shadow-sm">
<span className="text-[11px] text-slate-500 flex items-center gap-1.5 mb-1">
<Calendar className="w-3.5 h-3.5 text-amber-600" /> Upload Date
</span>
<span className="text-sm font-semibold text-slate-900">
{formatDate(file.createdAt)}
</span>
</div>
</div>
</div>
) : null}
</main>
</div>
</div>
);
}

View File

@@ -0,0 +1,153 @@
'use client';
import React, { useState } from 'react';
import { api } from '@/lib/api-client';
import { KeyRound, Eye, EyeOff, CheckCircle2, AlertCircle, X, ShieldAlert } from 'lucide-react';
interface AdminResetPasswordModalProps {
isOpen: boolean;
onClose: () => void;
user: {
id: string;
username: string;
fullName: string;
} | null;
onSuccess: () => void;
}
export const AdminResetPasswordModal: React.FC<AdminResetPasswordModalProps> = ({
isOpen,
onClose,
user,
onSuccess,
}) => {
const [newPassword, setNewPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
if (!isOpen || !user) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
if (!newPassword || newPassword.length < 1) {
setError('Please provide a new password');
return;
}
setIsLoading(true);
try {
await api.patch(`/admin/users/${user.id}/password`, {
newPassword,
});
setSuccess(`Password for "${user.username}" reset successfully!`);
setNewPassword('');
setTimeout(() => {
onSuccess();
onClose();
setSuccess(null);
}, 1200);
} catch (err: any) {
setError(err.message || 'Failed to reset password');
} finally {
setIsLoading(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in">
<div className="relative w-full max-w-md rounded-2xl bg-white border border-slate-200 p-6 shadow-2xl">
<button
onClick={onClose}
className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors"
>
<X className="w-5 h-5" />
</button>
<div className="flex items-center gap-3 mb-5">
<div className="w-10 h-10 rounded-xl bg-amber-100 text-amber-700 flex items-center justify-center">
<KeyRound className="w-5 h-5" />
</div>
<div>
<h2 className="text-lg font-bold text-slate-900">Reset User Password</h2>
<p className="text-xs text-slate-500">
Set new password for <span className="text-amber-700 font-semibold">{user.fullName}</span> ({user.username})
</p>
</div>
</div>
{error && (
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700">
<AlertCircle className="w-4 h-4 shrink-0" />
<span>{error}</span>
</div>
)}
{success && (
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-emerald-50 border border-emerald-200 text-xs text-emerald-700">
<CheckCircle2 className="w-4 h-4 shrink-0" />
<span>{success}</span>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1.5">
New Password
</label>
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="Type new password"
required
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-50 border border-slate-300 text-sm text-slate-900 focus:outline-none focus:border-amber-600 focus:ring-1 focus:ring-amber-600 transition-colors pr-10"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
<p className="mt-1.5 text-[11px] text-slate-500">
Super Admin can view this password and change it anytime. Active sessions for this user will be revoked immediately.
</p>
</div>
<div className="flex items-center justify-end gap-3 pt-3 border-t border-slate-100">
<button
type="button"
onClick={onClose}
disabled={isLoading}
className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:text-slate-900 hover:bg-slate-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={isLoading}
className="flex items-center gap-2 px-5 py-2 rounded-xl bg-amber-600 hover:bg-amber-700 active:scale-95 text-white font-bold text-xs shadow-md shadow-amber-600/20 transition-all disabled:opacity-50"
>
{isLoading ? (
<>Resetting...</>
) : (
<>
<ShieldAlert className="w-4 h-4" />
<span>Reset Password</span>
</>
)}
</button>
</div>
</form>
</div>
</div>
);
};

View File

@@ -0,0 +1,342 @@
'use client';
import React, { useState, useEffect } from 'react';
import { api } from '@/lib/api-client';
import {
ShieldCheck,
CheckCircle2,
AlertCircle,
X,
Play,
Download,
Eye,
FolderTree,
Calendar,
Layers,
Users,
} from 'lucide-react';
interface BatchGrantModalProps {
isOpen: boolean;
onClose: () => void;
selectedFileIds?: string[];
ownerId?: string;
onSuccess: () => void;
}
export const BatchGrantModal: React.FC<BatchGrantModalProps> = ({
isOpen,
onClose,
selectedFileIds = [],
ownerId,
onSuccess,
}) => {
const [users, setUsers] = useState<any[]>([]);
const [granteeUserId, setGranteeUserId] = useState('');
const [sourceOwnerId, setSourceOwnerId] = useState(ownerId || '');
const [grantAll, setGrantAll] = useState(selectedFileIds.length === 0);
const [canViewMetadata, setCanViewMetadata] = useState(true);
const [canPreview, setCanPreview] = useState(true);
const [canPlay, setCanPlay] = useState(true);
const [canDownload, setCanDownload] = useState(false);
const [canListFolder, setCanListFolder] = useState(false);
const [expiresAt, setExpiresAt] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
useEffect(() => {
if (isOpen) {
loadUsers();
setGrantAll(selectedFileIds.length === 0);
setSourceOwnerId(ownerId || '');
}
}, [isOpen, selectedFileIds, ownerId]);
const loadUsers = async () => {
try {
const data: any = await api.get('/admin/users?limit=100');
setUsers(data.users || []);
} catch (err: any) {
setError('Failed to fetch user list');
}
};
if (!isOpen) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
const effectiveOwner = ownerId || sourceOwnerId;
if (!granteeUserId) {
setError('Please select a recipient user');
return;
}
if (grantAll && !effectiveOwner) {
setError('Please select which user owns the files you want to grant permissions for');
return;
}
if (!grantAll && selectedFileIds.length === 0) {
setError('Please select at least one file or choose "All Files" with an owner');
return;
}
if (effectiveOwner && granteeUserId === effectiveOwner) {
setError('Recipient user cannot be the same as the file owner');
return;
}
setIsLoading(true);
try {
await api.post('/admin/permissions/batch', {
granteeUserId,
fileIds: grantAll ? undefined : selectedFileIds,
grantAllFilesOfOwner: grantAll ? effectiveOwner : undefined,
canViewMetadata,
canPreview,
canPlay,
canDownload,
canListFolder,
expiresAt: expiresAt ? new Date(expiresAt).toISOString() : undefined,
});
setSuccess('Permissions granted successfully!');
setTimeout(() => {
onSuccess();
onClose();
setSuccess(null);
}, 1200);
} catch (err: any) {
setError(err.message || 'Failed to grant permissions');
} finally {
setIsLoading(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in">
<div className="relative w-full max-w-lg rounded-2xl bg-white border border-slate-200 p-6 shadow-2xl">
<button
onClick={onClose}
className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors"
>
<X className="w-5 h-5" />
</button>
<div className="flex items-center gap-3 mb-5">
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
<Layers className="w-5 h-5" />
</div>
<div>
<h2 className="text-lg font-bold text-slate-900">Batch Permission Grant</h2>
<p className="text-xs text-slate-500">
Grant permissions 1-by-1 or for ALL files at once
</p>
</div>
</div>
{error && (
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700">
<AlertCircle className="w-4 h-4 shrink-0" />
<span>{error}</span>
</div>
)}
{success && (
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-emerald-50 border border-emerald-200 text-xs text-emerald-700">
<CheckCircle2 className="w-4 h-4 shrink-0" />
<span>{success}</span>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
{/* Scope selection */}
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
<div className="text-xs font-semibold text-slate-700">Grant Scope:</div>
<div className="grid grid-cols-2 gap-2 text-xs">
<button
type="button"
onClick={() => setGrantAll(false)}
disabled={selectedFileIds.length === 0}
className={`p-2.5 rounded-lg border text-left transition-all ${
!grantAll
? 'border-emerald-600 bg-emerald-50 text-emerald-900 font-semibold'
: 'border-slate-200 bg-white text-slate-600 hover:text-slate-900'
} ${selectedFileIds.length === 0 ? 'opacity-40 cursor-not-allowed' : ''}`}
>
<div className="font-medium">Selected Files</div>
<div className="text-[11px] text-slate-500">
{selectedFileIds.length} file(s) selected
</div>
</button>
<button
type="button"
onClick={() => setGrantAll(true)}
className={`p-2.5 rounded-lg border text-left transition-all ${
grantAll
? 'border-emerald-600 bg-emerald-50 text-emerald-900 font-semibold'
: 'border-slate-200 bg-white text-slate-600 hover:text-slate-900'
}`}
>
<div className="font-medium">All User Files (Select All)</div>
<div className="text-[11px] text-slate-500">
Grant across all files at once
</div>
</button>
</div>
</div>
{/* Select Source File Owner (when not pre-selected) */}
{grantAll && !ownerId && (
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1.5 flex items-center gap-1.5">
<Users className="w-3.5 h-3.5 text-purple-600" />
<span>Source File Owner (Whose files are being shared)</span>
</label>
<select
value={sourceOwnerId}
onChange={(e) => setSourceOwnerId(e.target.value)}
required
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-sm text-slate-900 focus:outline-none focus:border-purple-600 transition-colors"
>
<option value="">-- Choose file owner --</option>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.fullName} ({u.username}) {u.companyName ? `• ${u.companyName}` : ''}
</option>
))}
</select>
</div>
)}
{/* Select Recipient User */}
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1.5 flex items-center gap-1.5">
<Users className="w-3.5 h-3.5 text-emerald-600" />
<span>Grant Permissions To (Recipient User)</span>
</label>
<select
value={granteeUserId}
onChange={(e) => setGranteeUserId(e.target.value)}
required
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-sm text-slate-900 focus:outline-none focus:border-emerald-600 transition-colors"
>
<option value="">-- Choose recipient user --</option>
{users
.filter((u) => u.id !== (ownerId || sourceOwnerId))
.map((u) => (
<option key={u.id} value={u.id}>
{u.fullName} ({u.username}) {u.companyName ? `• ${u.companyName}` : ''} - {u.role}
</option>
))}
</select>
</div>
{/* Permission Flags */}
<div className="space-y-2 pt-1">
<div className="text-xs font-semibold text-slate-700">Allowed Actions:</div>
<div className="grid grid-cols-2 gap-2 text-xs">
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canPlay}
onChange={(e) => setCanPlay(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
/>
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
<Play className="w-3.5 h-3.5 text-emerald-600" />
<span>Can Play (Stream)</span>
</div>
</label>
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canDownload}
onChange={(e) => setCanDownload(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
/>
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
<Download className="w-3.5 h-3.5 text-emerald-600" />
<span>Can Download</span>
</div>
</label>
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canPreview}
onChange={(e) => setCanPreview(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
/>
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
<Eye className="w-3.5 h-3.5 text-sky-600" />
<span>Can Preview</span>
</div>
</label>
<label className="flex items-center gap-2.5 p-2.5 rounded-xl bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canListFolder}
onChange={(e) => setCanListFolder(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 w-4 h-4"
/>
<div className="flex items-center gap-1.5 text-slate-800 font-medium">
<FolderTree className="w-3.5 h-3.5 text-amber-600" />
<span>Can List Folder</span>
</div>
</label>
</div>
</div>
{/* Expiration date */}
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1 flex items-center gap-1.5">
<Calendar className="w-3.5 h-3.5 text-slate-500" />
<span>Expires At (Optional)</span>
</label>
<input
type="datetime-local"
value={expiresAt}
onChange={(e) => setExpiresAt(e.target.value)}
className="w-full px-3.5 py-2 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
<div className="flex items-center justify-end gap-3 pt-3 border-t border-slate-200">
<button
type="button"
onClick={onClose}
disabled={isLoading}
className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:text-slate-900 hover:bg-slate-100 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={isLoading}
className="flex items-center gap-2 px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 active:scale-95 text-white font-medium text-xs shadow-md shadow-emerald-600/20 transition-all disabled:opacity-50"
>
{isLoading ? (
<>Applying...</>
) : (
<>
<ShieldCheck className="w-4 h-4" />
<span>Grant Permissions</span>
</>
)}
</button>
</div>
</form>
</div>
</div>
);
};

View File

@@ -0,0 +1,547 @@
'use client';
import React, { useState, useEffect } from 'react';
import { api } from '@/lib/api-client';
import { useAuth } from '@/context/auth-context';
import { UserRole } from '@fileshare/shared';
import { X, UserPlus, Loader2, Building2, Server, Check, Plus, CheckSquare, Square, Layers } from 'lucide-react';
interface CreateUserModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
}
export const CreateUserModal: React.FC<CreateUserModalProps> = ({
isOpen,
onClose,
onSuccess,
}) => {
const { isSuperAdmin } = useAuth();
const [email, setEmail] = useState('');
const [username, setUsername] = useState('');
const [fullName, setFullName] = useState('');
const [companyName, setCompanyName] = useState('Ecohub Technologies');
const [availableCompanies, setAvailableCompanies] = useState<string[]>([]);
const [accessAllCompanies, setAccessAllCompanies] = useState(false);
const [allowedCompaniesList, setAllowedCompaniesList] = useState<string[]>([]);
const [customCompanyInput, setCustomCompanyInput] = useState('');
const [password, setPassword] = useState('');
const [role, setRole] = useState<UserRole>(UserRole.USER);
const [quotaGb, setQuotaGb] = useState(10);
const [canCreateShareLinks, setCanCreateShareLinks] = useState(false);
const [canDeleteFiles, setCanDeleteFiles] = useState(true);
const [canViewOtherUsers, setCanViewOtherUsers] = useState(false);
const [remoteFileServerUrl, setRemoteFileServerUrl] = useState('');
const [canUseRemoteServer, setCanUseRemoteServer] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (isOpen) {
api.getCompanies().then((res) => {
const list = res || [];
setAvailableCompanies(list);
}).catch(() => {});
setAccessAllCompanies(false);
setAllowedCompaniesList([]);
}
}, [isOpen]);
const handleAddNewCompany = async (nameToAdd: string) => {
const trimmed = nameToAdd.trim();
if (!trimmed) return;
try {
const updated = await api.createCompany(trimmed);
setAvailableCompanies(updated || []);
if (!allowedCompaniesList.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
setAllowedCompaniesList((prev) => [...prev, trimmed]);
}
} catch {
if (!availableCompanies.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
setAvailableCompanies((prev) => [...prev, trimmed]);
}
if (!allowedCompaniesList.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
setAllowedCompaniesList((prev) => [...prev, trimmed]);
}
}
setCustomCompanyInput('');
};
const handleSelectAllOrgs = () => {
const primary = companyName.trim() || 'Ecohub Technologies';
const all = Array.from(new Set([primary, ...availableCompanies]));
setAllowedCompaniesList(all);
};
const handleClearOrgs = () => {
setAllowedCompaniesList([]);
};
if (!isOpen) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsSubmitting(true);
try {
const primaryComp = companyName.trim() || 'Ecohub Technologies';
const allowedCompaniesPayload = accessAllCompanies
? '*'
: JSON.stringify(Array.from(new Set([primaryComp, ...allowedCompaniesList])));
await api.post('/admin/users', {
email,
username,
fullName,
companyName: primaryComp,
allowedCompanies: allowedCompaniesPayload,
password,
role,
storageQuotaBytes: quotaGb * 1024 * 1024 * 1024,
canCreateShareLinks,
canDeleteFiles,
canViewOtherUsers: isSuperAdmin ? (role === UserRole.SUPER_ADMIN ? true : canViewOtherUsers) : false,
remoteFileServerUrl: remoteFileServerUrl.trim() || undefined,
canUseRemoteServer,
});
onSuccess();
onClose();
} catch (err: any) {
setError(err.message || 'Failed to create user');
} finally {
setIsSubmitting(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
<div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 shrink-0">
<div className="flex items-center gap-2">
<UserPlus className="w-5 h-5 text-emerald-600" />
<h3 className="text-base font-semibold text-slate-900">Create New User</h3>
</div>
<button onClick={onClose} className="p-1 rounded-lg text-slate-400 hover:text-slate-600">
<X className="w-5 h-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-3.5 text-xs overflow-y-auto custom-scrollbar">
{error && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700">
{error}
</div>
)}
<div>
<label className="block text-slate-700 font-medium mb-1">Full Name</label>
<input
type="text"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
required
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
{/* Primary Company / Organization */}
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-slate-700 font-medium flex items-center gap-1.5">
<Building2 className="w-3.5 h-3.5 text-emerald-600" />
<span>Primary Company / Organization</span>
</label>
<span className="text-[10px] text-slate-400">User's home organization</span>
</div>
<div className="relative">
<input
type="text"
list="create-modal-companies-list"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
placeholder="e.g. Ecohub Technologies"
required
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600 text-xs"
/>
<datalist id="create-modal-companies-list">
{availableCompanies.map((c) => (
<option key={c} value={c} />
))}
</datalist>
</div>
{availableCompanies.length > 0 && (
<div className="flex items-center gap-1.5 flex-wrap pt-1.5">
<span className="text-[10px] text-slate-400 font-medium">Quick pick:</span>
{availableCompanies.slice(0, 6).map((c) => (
<button
key={c}
type="button"
onClick={() => setCompanyName(c)}
className={`px-2 py-0.5 rounded-md text-[10px] font-medium transition-colors ${
companyName.trim().toLowerCase() === c.toLowerCase()
? 'bg-emerald-600 text-white'
: 'bg-slate-100 hover:bg-slate-200 text-slate-600'
}`}
>
{c}
</button>
))}
</div>
)}
<p className="text-[10px] text-slate-500 mt-1">
This user's files and folders will reside under this company in the File Explorer.
</p>
</div>
{/* Organizations & Companies Access Permission Section */}
<div className="p-3.5 rounded-2xl bg-slate-50 border border-slate-200 space-y-3">
<div className="flex items-center justify-between">
<label className="text-slate-800 font-bold flex items-center gap-1.5 text-xs">
<Layers className="w-4 h-4 text-emerald-600" />
<span>Organizations Access Permissions</span>
</label>
<span
className={`text-[10px] px-2 py-0.5 rounded-full font-bold font-mono ${
accessAllCompanies
? 'bg-purple-100 text-purple-700 border border-purple-200'
: 'bg-emerald-100 text-emerald-700 border border-emerald-200'
}`}
>
{accessAllCompanies
? 'FULL ACCESS (ALL ORGS)'
: `${
Array.from(new Set([companyName.trim() || 'Ecohub Technologies', ...allowedCompaniesList]))
.length
} ORGS ALLOWED`}
</span>
</div>
<p className="text-[11px] text-slate-500 leading-relaxed">
Define which companies' files & folders this user can access in the File Explorer.
</p>
{/* Toggle: All Companies vs Selected Companies */}
<div className="p-2.5 rounded-xl bg-white border border-slate-200/80 space-y-2">
<label className="flex items-center gap-2.5 cursor-pointer font-semibold text-slate-800">
<input
type="checkbox"
checked={accessAllCompanies}
onChange={(e) => setAccessAllCompanies(e.target.checked)}
className="w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500"
/>
<span className="text-xs">Allow Access to ALL Companies (Full Organization Scope)</span>
</label>
{accessAllCompanies && (
<p className="text-[10px] text-purple-600 pl-6.5">
User will automatically have access to all current and future organizations.
</p>
)}
</div>
{!accessAllCompanies && (
<div className="space-y-2.5 pt-1">
{/* Header with Quick Actions */}
<div className="flex items-center justify-between">
<span className="text-[11px] font-bold text-slate-700">
Select Permitted Organizations:
</span>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleSelectAllOrgs}
className="text-[11px] text-emerald-600 hover:text-emerald-700 font-semibold"
>
Select All
</button>
<span className="text-slate-300 text-[10px]">|</span>
<button
type="button"
onClick={handleClearOrgs}
className="text-[11px] text-slate-500 hover:text-slate-700 font-semibold"
>
Deselect All
</button>
</div>
</div>
{/* Organizations Checkboxes Grid */}
{(() => {
const primaryComp = companyName.trim() || 'Ecohub Technologies';
const allCompsToDisplay = Array.from(
new Set([primaryComp, ...availableCompanies]),
).sort((a, b) => a.localeCompare(b));
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-48 overflow-y-auto p-2 bg-white border border-slate-200 rounded-xl">
{allCompsToDisplay.map((comp) => {
const isPrimary = comp.toLowerCase() === primaryComp.toLowerCase();
const isSelected =
isPrimary ||
allowedCompaniesList.some((c) => c.toLowerCase() === comp.toLowerCase());
return (
<div
key={comp}
onClick={() => {
if (isPrimary) return;
if (isSelected) {
setAllowedCompaniesList(
allowedCompaniesList.filter(
(c) => c.toLowerCase() !== comp.toLowerCase(),
),
);
} else {
setAllowedCompaniesList([...allowedCompaniesList, comp]);
}
}}
className={`flex items-center justify-between p-2 rounded-lg border text-xs cursor-pointer select-none transition-all ${
isSelected
? 'bg-emerald-50/90 border-emerald-300 text-emerald-950 font-medium'
: 'bg-slate-50/80 border-slate-200 text-slate-600 hover:bg-slate-100 hover:border-slate-300'
}`}
>
<div className="flex items-center gap-2 min-w-0">
<div
className={`w-4 h-4 rounded flex items-center justify-center border transition-colors shrink-0 ${
isSelected
? 'bg-emerald-600 border-emerald-600 text-white'
: 'border-slate-300 bg-white'
}`}
>
{isSelected && <Check className="w-3 h-3 stroke-[3]" />}
</div>
<span className="truncate">{comp}</span>
</div>
{isPrimary && (
<span className="text-[9px] font-bold text-emerald-700 bg-emerald-100 px-1.5 py-0.5 rounded border border-emerald-200 shrink-0">
Primary
</span>
)}
</div>
);
})}
</div>
);
})()}
{/* Create & Register New Organization Input */}
<div className="p-2.5 bg-white border border-slate-200 rounded-xl space-y-1">
<span className="text-[10px] text-slate-500 font-medium block">
Need to add another organization?
</span>
<div className="flex items-center gap-1.5">
<input
type="text"
placeholder="Type organization name..."
value={customCompanyInput}
onChange={(e) => setCustomCompanyInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddNewCompany(customCompanyInput);
}
}}
className="flex-1 px-2.5 py-1.5 rounded-lg bg-slate-50 border border-slate-200 text-slate-800 text-xs focus:outline-none focus:border-emerald-600"
/>
<button
type="button"
onClick={() => handleAddNewCompany(customCompanyInput)}
className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs flex items-center gap-1 shadow-xs"
>
<Plus className="w-3.5 h-3.5" />
<span>Add Org</span>
</button>
</div>
</div>
</div>
)}
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-slate-700 font-medium mb-1">Email Address</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
<div>
<label className="block text-slate-700 font-medium mb-1">Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
</div>
<div>
<label className="block text-slate-700 font-medium mb-1">Initial Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
placeholder="Minimum 8 characters"
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
<p className="text-[10px] text-slate-400 mt-1">Password must be at least 8 characters long</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-slate-700 font-medium mb-1">System Role</label>
<select
value={role}
onChange={(e) => {
const newRole = e.target.value as UserRole;
setRole(newRole);
if (newRole !== UserRole.USER) {
setCanCreateShareLinks(true);
}
}}
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
>
<option value={UserRole.USER}>Regular User</option>
<option value={UserRole.ADMIN}>Administrator</option>
<option value={UserRole.SUPER_ADMIN}>Super Admin</option>
</select>
</div>
<div>
<label className="block text-slate-700 font-medium mb-1">Quota (GB)</label>
<input
type="number"
min={1}
value={quotaGb}
onChange={(e) => setQuotaGb(Number(e.target.value))}
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
</div>
{/* User Feature Permissions */}
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2.5">
<span className="text-slate-800 font-semibold block">Feature Permissions</span>
<label className="flex items-start gap-2.5 cursor-pointer">
<input
type="checkbox"
checked={canCreateShareLinks}
onChange={(e) => setCanCreateShareLinks(e.target.checked)}
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<div>
<span className="font-semibold text-slate-800 block">
Allow Public Share Links (Google Drive style)
</span>
<span className="text-[10px] text-slate-500">
Allow user to generate shareable links for videos, files, and folders.
</span>
</div>
</label>
<label className="flex items-start gap-2.5 cursor-pointer">
<input
type="checkbox"
checked={canDeleteFiles}
onChange={(e) => setCanDeleteFiles(e.target.checked)}
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<div>
<span className="font-semibold text-slate-800 block">
Allow File & Folder Deletion
</span>
<span className="text-[10px] text-slate-500">
Allow user to delete their own files and folders.
</span>
</div>
</label>
{isSuperAdmin && (
<label className="flex items-start gap-2.5 cursor-pointer pt-2 border-t border-slate-200/60">
<input
type="checkbox"
checked={canViewOtherUsers || role === UserRole.SUPER_ADMIN}
disabled={role === UserRole.SUPER_ADMIN}
onChange={(e) => setCanViewOtherUsers(e.target.checked)}
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500"
/>
<div>
<span className="font-semibold text-slate-800 block flex items-center gap-1.5">
<span>Allow Viewing Other Users' Information & Files</span>
<span className="text-[9px] bg-purple-100 text-purple-700 px-1.5 py-0.2 rounded font-bold font-mono">SUPER ADMIN ONLY</span>
</span>
<span className="text-[10px] text-slate-500">
When enabled, this user can view other users' directories, accounts, files, and system statistics. By default, only Super Admin can view other users.
</span>
</div>
</label>
)}
</div>
{/* User-Wise Remote File Server Link / Upload Endpoint */}
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
<div className="flex items-center justify-between">
<label className="text-slate-800 font-semibold flex items-center gap-1.5">
<Server className="w-3.5 h-3.5 text-sky-600" />
<span>Remote File Server Link / Upload Endpoint (Optional)</span>
</label>
<span className="text-[10px] text-sky-700 font-medium bg-sky-50 px-1.5 py-0.5 rounded border border-sky-200">
User-Wise
</span>
</div>
<input
type="text"
value={remoteFileServerUrl}
onChange={(e) => setRemoteFileServerUrl(e.target.value)}
placeholder="https://remotefileserver.custom.com/upload or http://192.168.1.100:8080/files"
className="w-full px-3 py-2 rounded-xl bg-white border border-slate-300 text-slate-900 font-mono text-xs focus:outline-none focus:border-emerald-600"
/>
<p className="text-[10px] text-slate-500">
If configured, this user's uploaded videos and files will automatically be mirrored/dispatched to this custom remote endpoint.
</p>
<label className="flex items-center gap-2 pt-1 cursor-pointer">
<input
type="checkbox"
checked={canUseRemoteServer}
onChange={(e) => setCanUseRemoteServer(e.target.checked)}
className="w-3.5 h-3.5 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-[11px] text-slate-700 font-medium">
Enable Remote File Server Mirroring / Uploads for this user
</span>
</label>
</div>
<div className="pt-3 flex justify-end gap-2 border-t border-slate-200">
<button
type="button"
onClick={onClose}
className="px-4 py-2 rounded-xl bg-slate-100 text-slate-700 hover:bg-slate-200 font-medium"
>
Cancel
</button>
<button
type="submit"
disabled={isSubmitting}
className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium flex items-center gap-1.5 shadow-sm"
>
{isSubmitting && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
<span>Create Account</span>
</button>
</div>
</form>
</div>
</div>
);
};

View File

@@ -0,0 +1,178 @@
'use client';
import React, { useState } from 'react';
import { api } from '@/lib/api-client';
import { useAuth } from '@/context/auth-context';
import { UserRole } from '@fileshare/shared';
import { X, Trash2, AlertTriangle, Loader2, Building2, HardDrive, FileText } from 'lucide-react';
import { formatBytes } from '@/lib/utils';
interface DeleteUserModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
user: any | null;
}
export const DeleteUserModal: React.FC<DeleteUserModalProps> = ({
isOpen,
onClose,
onSuccess,
user,
}) => {
const { user: currentUser } = useAuth();
const [isDeleting, setIsDeleting] = useState(false);
const [error, setError] = useState<string | null>(null);
if (!isOpen || !user) return null;
const isSuperAdmin = currentUser?.role === UserRole.SUPER_ADMIN;
const isSelf = currentUser?.id === user.id;
const isOtherCompany =
!isSuperAdmin &&
(user.companyName || 'Ecohub').trim().toLowerCase() !==
(currentUser?.companyName || 'Ecohub').trim().toLowerCase();
const handleDelete = async () => {
if (isSelf || isOtherCompany) return;
setError(null);
setIsDeleting(true);
try {
await api.deleteUser(user.id);
onSuccess();
onClose();
} catch (err: any) {
setError(err.message || 'Failed to delete user');
} finally {
setIsDeleting(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-200">
<div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-rose-100 bg-rose-50/50">
<div className="flex items-center gap-2.5">
<div className="w-9 h-9 rounded-xl bg-rose-100 border border-rose-200 flex items-center justify-center text-rose-600">
<Trash2 className="w-5 h-5" />
</div>
<div>
<h3 className="text-base font-bold text-slate-900">Delete User Account</h3>
<p className="text-xs text-rose-600 font-medium">Permanent System & Storage Cleanup</p>
</div>
</div>
<button
onClick={onClose}
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="p-6 space-y-4 text-xs">
{error && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 flex items-start gap-2">
<AlertTriangle className="w-4 h-4 text-rose-600 shrink-0 mt-0.5" />
<span>{error}</span>
</div>
)}
{/* User Info Card */}
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
<div className="flex items-center justify-between">
<span className="font-bold text-slate-900 text-sm">{user.fullName}</span>
<span
className={`px-2 py-0.5 rounded text-[10px] font-mono font-bold uppercase ${
user.role === UserRole.SUPER_ADMIN
? 'bg-rose-100 text-rose-700'
: user.role === UserRole.ADMIN
? 'bg-amber-100 text-amber-700'
: 'bg-slate-200 text-slate-700'
}`}
>
{user.role}
</span>
</div>
<div className="text-slate-500 font-mono text-[11px]">
@{user.username} • {user.email}
</div>
<div className="grid grid-cols-2 gap-2 pt-2 border-t border-slate-200/80 text-[11px]">
<div className="flex items-center gap-1.5 text-slate-600">
<Building2 className="w-3.5 h-3.5 text-emerald-600" />
<span className="font-medium truncate">{user.companyName || 'Ecohub'}</span>
</div>
<div className="flex items-center gap-1.5 text-slate-600">
<FileText className="w-3.5 h-3.5 text-sky-600" />
<span>{user.fileCount || 0} Files</span>
</div>
<div className="flex items-center gap-1.5 text-slate-600 col-span-2">
<HardDrive className="w-3.5 h-3.5 text-amber-600" />
<span>Storage: {formatBytes(Number(user.storageUsedBytes || 0))} used</span>
</div>
</div>
</div>
{/* Warning Banner */}
<div className="p-3 rounded-xl bg-amber-50 border border-amber-200/80 text-amber-800 space-y-1">
<div className="flex items-center gap-1.5 font-bold text-amber-900">
<AlertTriangle className="w-4 h-4 text-amber-600 shrink-0" />
<span>Are you absolutely sure?</span>
</div>
<p className="text-[11px] text-amber-700 leading-relaxed">
This action <strong>cannot be undone</strong>. Deleting this account will permanently erase the user profile, all their personal folders, and purge all their uploaded physical files from storage.
</p>
</div>
{isSelf && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 font-medium">
You are currently logged into this account. You cannot delete yourself.
</div>
)}
{isOtherCompany && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 font-medium flex items-start gap-2">
<AlertTriangle className="w-4 h-4 text-rose-600 shrink-0 mt-0.5" />
<span>
Admins cannot delete users belonging to other companies ({user.companyName || 'Other Company'}). Only Super Admin has permission to delete external company accounts.
</span>
</div>
)}
{/* Actions */}
<div className="pt-2 flex justify-end gap-2.5 border-t border-slate-100">
<button
type="button"
onClick={onClose}
disabled={isDeleting}
className="px-4 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold transition-colors"
>
Cancel
</button>
<button
type="button"
onClick={handleDelete}
disabled={isDeleting || isSelf || isOtherCompany}
className="px-4 py-2 rounded-xl bg-rose-600 hover:bg-rose-700 active:scale-95 text-white font-semibold flex items-center gap-1.5 shadow-sm shadow-rose-600/30 transition-all disabled:opacity-50 disabled:pointer-events-none"
>
{isDeleting ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
<span>Deleting User...</span>
</>
) : (
<>
<Trash2 className="w-4 h-4" />
<span>Delete User Permanently</span>
</>
)}
</button>
</div>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,620 @@
'use client';
import React, { useState, useEffect } from 'react';
import { api } from '@/lib/api-client';
import { useAuth } from '@/context/auth-context';
import { UserRole, UserStatus } from '@fileshare/shared';
import { X, UserCheck, Loader2, Building2, Server, Check, Plus, CheckSquare, Square, Layers } from 'lucide-react';
interface EditUserModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
user: any | null;
}
export const EditUserModal: React.FC<EditUserModalProps> = ({
isOpen,
onClose,
onSuccess,
user,
}) => {
const { isSuperAdmin } = useAuth();
const [fullName, setFullName] = useState('');
const [companyName, setCompanyName] = useState('');
const [availableCompanies, setAvailableCompanies] = useState<string[]>([]);
const [accessAllCompanies, setAccessAllCompanies] = useState(false);
const [allowedCompaniesList, setAllowedCompaniesList] = useState<string[]>([]);
const [customCompanyInput, setCustomCompanyInput] = useState('');
const [role, setRole] = useState<UserRole>(UserRole.USER);
const [status, setStatus] = useState<UserStatus>(UserStatus.ACTIVE);
const [quotaGb, setQuotaGb] = useState(5);
const [canCreateShareLinks, setCanCreateShareLinks] = useState(false);
const [canDeleteFiles, setCanDeleteFiles] = useState(true);
const [canViewOtherUsers, setCanViewOtherUsers] = useState(false);
const [remoteFileServerUrl, setRemoteFileServerUrl] = useState('');
const [canUseRemoteServer, setCanUseRemoteServer] = useState(true);
const [newPassword, setNewPassword] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (isOpen) {
api.getCompanies().then((res) => setAvailableCompanies(res || [])).catch(() => {});
}
}, [isOpen]);
useEffect(() => {
if (user) {
setFullName(user.fullName || '');
const primaryComp = user.companyName || 'Ecohub';
setCompanyName(primaryComp);
setRole(user.role || UserRole.USER);
setStatus(user.status || UserStatus.ACTIVE);
const gb = Math.round(Number(user.storageQuotaBytes) / (1024 * 1024 * 1024));
setQuotaGb(gb || 5);
setCanCreateShareLinks(user.canCreateShareLinks ?? false);
setCanDeleteFiles(user.canDeleteFiles ?? true);
setCanViewOtherUsers(user.canViewOtherUsers ?? false);
setRemoteFileServerUrl(user.remoteFileServerUrl || '');
setCanUseRemoteServer(user.canUseRemoteServer ?? true);
setNewPassword('');
// Parse allowed companies
const rawAllowed = user.allowedCompanies;
if (rawAllowed === '*' || user.role === UserRole.SUPER_ADMIN) {
setAccessAllCompanies(true);
setAllowedCompaniesList([]);
} else if (rawAllowed) {
setAccessAllCompanies(false);
try {
if (rawAllowed.startsWith('[')) {
setAllowedCompaniesList(JSON.parse(rawAllowed));
} else {
setAllowedCompaniesList(rawAllowed.split(',').map((s: string) => s.trim()).filter(Boolean));
}
} catch {
setAllowedCompaniesList([rawAllowed]);
}
} else {
setAccessAllCompanies(false);
setAllowedCompaniesList([primaryComp]);
}
}
}, [user]);
const handleAddNewCompany = async (nameToAdd: string) => {
const trimmed = nameToAdd.trim();
if (!trimmed) return;
try {
const updated = await api.createCompany(trimmed);
setAvailableCompanies(updated || []);
if (!allowedCompaniesList.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
setAllowedCompaniesList((prev) => [...prev, trimmed]);
}
} catch {
if (!availableCompanies.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
setAvailableCompanies((prev) => [...prev, trimmed]);
}
if (!allowedCompaniesList.some((c) => c.toLowerCase() === trimmed.toLowerCase())) {
setAllowedCompaniesList((prev) => [...prev, trimmed]);
}
}
setCustomCompanyInput('');
};
const handleSelectAllOrgs = () => {
const primary = companyName.trim() || 'Ecohub';
const all = Array.from(new Set([primary, ...availableCompanies]));
setAllowedCompaniesList(all);
};
const handleClearOrgs = () => {
setAllowedCompaniesList([]);
};
if (!isOpen || !user) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsSubmitting(true);
try {
const primaryComp = companyName.trim() || 'Ecohub';
const allowedCompaniesPayload = accessAllCompanies
? '*'
: JSON.stringify(Array.from(new Set([primaryComp, ...allowedCompaniesList])));
await api.patch(`/admin/users/${user.id}`, {
fullName,
companyName: primaryComp,
allowedCompanies: allowedCompaniesPayload,
role,
status,
storageQuotaBytes: quotaGb * 1024 * 1024 * 1024,
canCreateShareLinks,
canDeleteFiles,
canViewOtherUsers: isSuperAdmin ? canViewOtherUsers : undefined,
remoteFileServerUrl: remoteFileServerUrl.trim() || null,
canUseRemoteServer,
newPassword: newPassword || undefined,
});
onSuccess();
onClose();
} catch (err: any) {
setError(err.message || 'Failed to update user');
} finally {
setIsSubmitting(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
<div className="w-full max-w-md bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden max-h-[92vh] flex flex-col">
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 shrink-0">
<div className="flex items-center gap-2">
<UserCheck className="w-5 h-5 text-emerald-600" />
<h3 className="text-base font-semibold text-slate-900">Edit User Account</h3>
</div>
<button onClick={onClose} className="p-1 rounded-lg text-slate-400 hover:text-slate-600">
<X className="w-5 h-5" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-4 text-xs overflow-y-auto custom-scrollbar">
{error && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700">
{error}
</div>
)}
<div>
<label className="block text-slate-700 font-medium mb-1">Full Name</label>
<input
type="text"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
required
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
{/* Primary Company / Organization */}
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-slate-700 font-medium flex items-center gap-1.5">
<Building2 className="w-3.5 h-3.5 text-emerald-600" />
<span>Primary Company / Organization</span>
</label>
<span className="text-[10px] text-slate-400">User's home organization</span>
</div>
<div className="relative">
<input
type="text"
list="edit-modal-companies-list"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
placeholder="e.g. Ecohub"
required
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600 text-xs"
/>
<datalist id="edit-modal-companies-list">
{availableCompanies.map((c) => (
<option key={c} value={c} />
))}
</datalist>
</div>
{availableCompanies.length > 0 && (
<div className="flex items-center gap-1.5 flex-wrap pt-1.5">
<span className="text-[10px] text-slate-400 font-medium">Quick pick:</span>
{availableCompanies.slice(0, 6).map((c) => (
<button
key={c}
type="button"
onClick={() => setCompanyName(c)}
className={`px-2 py-0.5 rounded-md text-[10px] font-medium transition-colors ${
companyName.trim().toLowerCase() === c.toLowerCase()
? 'bg-emerald-600 text-white'
: 'bg-slate-100 hover:bg-slate-200 text-slate-600'
}`}
>
{c}
</button>
))}
</div>
)}
<p className="text-[10px] text-slate-500 mt-1">
Primary organization this user belongs to in the File Explorer.
</p>
</div>
{/* Organizations & Companies Access Permission Section */}
<div className="p-3.5 rounded-2xl bg-slate-50 border border-slate-200 space-y-3">
<div className="flex items-center justify-between">
<label className="text-slate-800 font-bold flex items-center gap-1.5 text-xs">
<Layers className="w-4 h-4 text-emerald-600" />
<span>Organizations Access Permissions</span>
</label>
<span
className={`text-[10px] px-2 py-0.5 rounded-full font-bold font-mono ${
accessAllCompanies
? 'bg-purple-100 text-purple-700 border border-purple-200'
: 'bg-emerald-100 text-emerald-700 border border-emerald-200'
}`}
>
{accessAllCompanies
? 'FULL ACCESS (ALL ORGS)'
: `${
Array.from(new Set([companyName.trim() || 'Ecohub', ...allowedCompaniesList]))
.length
} ORGS ALLOWED`}
</span>
</div>
<p className="text-[11px] text-slate-500 leading-relaxed">
Define which companies' files & folders this user can access in the File Explorer.
</p>
{/* Toggle: All Companies vs Selected Companies */}
<div className="p-2.5 rounded-xl bg-white border border-slate-200/80 space-y-2">
<label className="flex items-center gap-2.5 cursor-pointer font-semibold text-slate-800">
<input
type="checkbox"
checked={accessAllCompanies}
onChange={(e) => setAccessAllCompanies(e.target.checked)}
className="w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500"
/>
<span className="text-xs">Allow Access to ALL Companies (Full Organization Scope)</span>
</label>
{accessAllCompanies && (
<p className="text-[10px] text-purple-600 pl-6.5">
User will automatically have access to all current and future organizations.
</p>
)}
</div>
{!accessAllCompanies && (
<div className="space-y-2.5 pt-1">
{/* Header with Quick Actions */}
<div className="flex items-center justify-between">
<span className="text-[11px] font-bold text-slate-700">
Select Permitted Organizations:
</span>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleSelectAllOrgs}
className="text-[11px] text-emerald-600 hover:text-emerald-700 font-semibold"
>
Select All
</button>
<span className="text-slate-300 text-[10px]">|</span>
<button
type="button"
onClick={handleClearOrgs}
className="text-[11px] text-slate-500 hover:text-slate-700 font-semibold"
>
Deselect All
</button>
</div>
</div>
{/* Organizations Checkboxes Grid */}
{(() => {
const primaryComp = companyName.trim() || 'Ecohub';
const allCompsToDisplay = Array.from(
new Set([primaryComp, ...availableCompanies]),
).sort((a, b) => a.localeCompare(b));
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-48 overflow-y-auto p-2 bg-white border border-slate-200 rounded-xl">
{allCompsToDisplay.map((comp) => {
const isPrimary = comp.toLowerCase() === primaryComp.toLowerCase();
const isSelected =
isPrimary ||
allowedCompaniesList.some((c) => c.toLowerCase() === comp.toLowerCase());
return (
<div
key={comp}
onClick={() => {
if (isPrimary) return;
if (isSelected) {
setAllowedCompaniesList(
allowedCompaniesList.filter(
(c) => c.toLowerCase() !== comp.toLowerCase(),
),
);
} else {
setAllowedCompaniesList([...allowedCompaniesList, comp]);
}
}}
className={`flex items-center justify-between p-2 rounded-lg border text-xs cursor-pointer select-none transition-all ${
isSelected
? 'bg-emerald-50/90 border-emerald-300 text-emerald-950 font-medium'
: 'bg-slate-50/80 border-slate-200 text-slate-600 hover:bg-slate-100 hover:border-slate-300'
}`}
>
<div className="flex items-center gap-2 min-w-0">
<div
className={`w-4 h-4 rounded flex items-center justify-center border transition-colors shrink-0 ${
isSelected
? 'bg-emerald-600 border-emerald-600 text-white'
: 'border-slate-300 bg-white'
}`}
>
{isSelected && <Check className="w-3 h-3 stroke-[3]" />}
</div>
<span className="truncate">{comp}</span>
</div>
{isPrimary && (
<span className="text-[9px] font-bold text-emerald-700 bg-emerald-100 px-1.5 py-0.5 rounded border border-emerald-200 shrink-0">
Primary
</span>
)}
</div>
);
})}
</div>
);
})()}
{/* Create & Register New Organization Input */}
<div className="p-2.5 bg-white border border-slate-200 rounded-xl space-y-1">
<span className="text-[10px] text-slate-500 font-medium block">
Need to add another organization?
</span>
<div className="flex items-center gap-1.5">
<input
type="text"
placeholder="Type organization name..."
value={customCompanyInput}
onChange={(e) => setCustomCompanyInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddNewCompany(customCompanyInput);
}
}}
className="flex-1 px-2.5 py-1.5 rounded-lg bg-slate-50 border border-slate-200 text-slate-800 text-xs focus:outline-none focus:border-emerald-600"
/>
<button
type="button"
onClick={() => handleAddNewCompany(customCompanyInput)}
className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs flex items-center gap-1 shadow-xs"
>
<Plus className="w-3.5 h-3.5" />
<span>Add Org</span>
</button>
</div>
</div>
</div>
)}
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-slate-700 font-medium mb-1">Account Role</label>
<select
value={role}
onChange={(e) => setRole(e.target.value as UserRole)}
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
>
<option value={UserRole.USER}>Regular User</option>
<option value={UserRole.ADMIN}>Administrator</option>
<option value={UserRole.SUPER_ADMIN}>Super Admin</option>
</select>
</div>
<div>
<label className="block text-slate-700 font-medium mb-1">Account Status</label>
<select
value={status}
onChange={(e) => setStatus(e.target.value as UserStatus)}
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
>
<option value={UserStatus.ACTIVE}>Active</option>
<option value={UserStatus.SUSPENDED}>Suspended</option>
<option value={UserStatus.PENDING}>Pending</option>
</select>
</div>
</div>
{/* Dynamic Storage Quota Controls */}
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2.5">
<div className="flex items-center justify-between">
<label className="text-slate-800 font-semibold">Storage Quota Allocation</label>
<span className="font-mono text-emerald-600 font-bold text-xs">{quotaGb} GB</span>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setQuotaGb((prev) => Math.max(1, prev - 10))}
className="px-2.5 py-1 rounded-lg bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold"
title="Decrease by 10 GB"
>
-10 GB
</button>
<button
type="button"
onClick={() => setQuotaGb((prev) => Math.max(1, prev - 1))}
className="px-2.5 py-1 rounded-lg bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold"
title="Decrease by 1 GB"
>
-1 GB
</button>
<input
type="number"
min={1}
value={quotaGb}
onChange={(e) => setQuotaGb(Math.max(1, Number(e.target.value)))}
className="w-full px-3 py-1.5 rounded-lg bg-white border border-slate-300 text-center text-slate-900 font-bold focus:outline-none focus:border-emerald-600"
/>
<button
type="button"
onClick={() => setQuotaGb((prev) => prev + 1)}
className="px-2.5 py-1 rounded-lg bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold"
title="Increase by 1 GB"
>
+1 GB
</button>
<button
type="button"
onClick={() => setQuotaGb((prev) => prev + 10)}
className="px-2.5 py-1 rounded-lg bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold"
title="Increase by 10 GB"
>
+10 GB
</button>
</div>
{/* Quota Presets */}
<div className="flex items-center gap-1.5 flex-wrap pt-1">
<span className="text-[10px] text-slate-500 uppercase tracking-wider font-semibold mr-1">Presets:</span>
{[5, 10, 25, 50, 100, 250, 500, 1024].map((gb) => (
<button
key={gb}
type="button"
onClick={() => setQuotaGb(gb)}
className={`px-2 py-0.5 rounded text-[11px] font-mono transition-colors ${
quotaGb === gb
? 'bg-emerald-600 text-white font-bold'
: 'bg-white border border-slate-200 text-slate-600 hover:bg-slate-100'
}`}
>
{gb >= 1024 ? `${gb / 1024}TB` : `${gb}GB`}
</button>
))}
</div>
</div>
{/* Admin Managed Permissions */}
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-3">
<span className="text-slate-800 font-semibold block">User Permissions & Feature Control</span>
<label className="flex items-start gap-3 cursor-pointer group">
<input
type="checkbox"
checked={canCreateShareLinks}
onChange={(e) => setCanCreateShareLinks(e.target.checked)}
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<div>
<span className="font-semibold text-slate-800 group-hover:text-emerald-700 transition-colors block">
Allow Public Share Links (Google Drive style)
</span>
<span className="text-[11px] text-slate-500">
Allow this user to generate public, shareable links for videos, files, and folders.
</span>
</div>
</label>
<label className="flex items-start gap-3 cursor-pointer group">
<input
type="checkbox"
checked={canDeleteFiles}
onChange={(e) => setCanDeleteFiles(e.target.checked)}
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<div>
<span className="font-semibold text-slate-800 group-hover:text-emerald-700 transition-colors block">
Allow File & Folder Deletion
</span>
<span className="text-[11px] text-slate-500">
When enabled, user can delete their own files and folders. If disabled, deletion is strictly forbidden.
</span>
</div>
</label>
{isSuperAdmin && (
<label className="flex items-start gap-3 cursor-pointer group pt-2.5 border-t border-slate-200/60">
<input
type="checkbox"
checked={canViewOtherUsers || role === UserRole.SUPER_ADMIN}
disabled={role === UserRole.SUPER_ADMIN}
onChange={(e) => setCanViewOtherUsers(e.target.checked)}
className="mt-0.5 w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500"
/>
<div>
<span className="font-semibold text-slate-800 group-hover:text-purple-700 transition-colors block flex items-center gap-1.5">
<span>Allow Viewing Other Users' Information & Files</span>
<span className="text-[9px] bg-purple-100 text-purple-700 px-1.5 py-0.2 rounded font-bold font-mono">SUPER ADMIN ONLY</span>
</span>
<span className="text-[11px] text-slate-500">
When enabled, this user can view other users' accounts, directories, files, and system storage overview. By default, only Super Admin can view other users.
</span>
</div>
</label>
)}
</div>
{/* User-Wise Remote File Server Link / Upload Endpoint */}
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
<div className="flex items-center justify-between">
<label className="text-slate-800 font-semibold flex items-center gap-1.5">
<Server className="w-3.5 h-3.5 text-sky-600" />
<span>Remote File Server Link / Upload Endpoint (Optional)</span>
</label>
<span className="text-[10px] text-sky-700 font-medium bg-sky-50 px-1.5 py-0.5 rounded border border-sky-200">
User-Wise
</span>
</div>
<input
type="text"
value={remoteFileServerUrl}
onChange={(e) => setRemoteFileServerUrl(e.target.value)}
placeholder="https://remotefileserver.custom.com/upload or http://192.168.1.100:8080/files"
className="w-full px-3 py-2 rounded-xl bg-white border border-slate-300 text-slate-900 font-mono text-xs focus:outline-none focus:border-emerald-600"
/>
<p className="text-[10px] text-slate-500">
When set, this user's uploaded videos and files are automatically mirrored to this custom remote file server endpoint. Leave blank to use system default.
</p>
<label className="flex items-center gap-2 pt-1 cursor-pointer">
<input
type="checkbox"
checked={canUseRemoteServer}
onChange={(e) => setCanUseRemoteServer(e.target.checked)}
className="w-3.5 h-3.5 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-[11px] text-slate-700 font-medium">
Enable Remote File Server Mirroring / Uploads for this user
</span>
</label>
</div>
<div>
<label className="block text-slate-700 font-medium mb-1">Reset Password (Leave blank to keep current)</label>
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="Enter new password if updating"
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
<div className="pt-2 flex justify-end gap-2 border-t border-slate-200">
<button
type="button"
onClick={onClose}
className="px-4 py-2 rounded-xl bg-slate-100 text-slate-700 hover:bg-slate-200 font-medium"
>
Cancel
</button>
<button
type="submit"
disabled={isSubmitting}
className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium flex items-center gap-1.5 shadow-sm"
>
{isSubmitting && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
<span>Save Changes</span>
</button>
</div>
</form>
</div>
</div>
);
};

View File

@@ -0,0 +1,412 @@
'use client';
import React, { useState, useEffect } from 'react';
import { api } from '@/lib/api-client';
import { PermissionResourceType } from '@fileshare/shared';
import { X, KeyRound, Loader2, FileText, Folder, Edit3, ListFilter, CheckCircle2 } from 'lucide-react';
import { formatBytes } from '@/lib/utils';
interface GrantPermissionModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
preselectedFile?: any;
}
export const GrantPermissionModal: React.FC<GrantPermissionModalProps> = ({
isOpen,
onClose,
onSuccess,
preselectedFile,
}) => {
const [users, setUsers] = useState<any[]>([]);
const [ownerId, setOwnerId] = useState('');
const [granteeUserId, setGranteeUserId] = useState('');
const [resourceType, setResourceType] = useState<PermissionResourceType>(PermissionResourceType.FILE);
const [resourceId, setResourceId] = useState('');
const [resources, setResources] = useState<any[]>([]);
const [isLoadingResources, setIsLoadingResources] = useState(false);
const [isManualInput, setIsManualInput] = useState(false);
const [canViewMetadata, setCanViewMetadata] = useState(true);
const [canPreview, setCanPreview] = useState(false);
const [canPlay, setCanPlay] = useState(false);
const [canDownload, setCanDownload] = useState(false);
const [canListFolder, setCanListFolder] = useState(false);
const [expiresAt, setExpiresAt] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Load registered users on modal open
useEffect(() => {
if (isOpen) {
api.get<any>('/admin/users?limit=100').then((res) => {
setUsers(res.users || []);
});
if (preselectedFile) {
setOwnerId(preselectedFile.ownerId);
setResourceId(preselectedFile.id);
setResourceType(PermissionResourceType.FILE);
}
}
}, [isOpen, preselectedFile]);
// Load resources (Files or Folders) for dropdown
useEffect(() => {
if (!isOpen || resourceType === PermissionResourceType.USER_FILES) {
setResources([]);
return;
}
setIsLoadingResources(true);
const query = new URLSearchParams();
query.set('type', resourceType);
if (ownerId) query.set('ownerId', ownerId);
api
.get<{ items: any[] }>(`/admin/resources?${query.toString()}`)
.then((res) => {
setResources(res.items || []);
})
.catch((err) => {
console.error('Failed to load resources:', err);
setResources([]);
})
.finally(() => {
setIsLoadingResources(false);
});
}, [isOpen, resourceType, ownerId]);
if (!isOpen) return null;
const handleOwnerChange = (newOwnerId: string) => {
setOwnerId(newOwnerId);
if (granteeUserId === newOwnerId) {
setGranteeUserId('');
}
// Clear resourceId if currently selected item doesn't belong to the new owner
if (resourceId && !isManualInput) {
const item = resources.find((r) => r.id === resourceId);
if (item && item.ownerId && item.ownerId !== newOwnerId) {
setResourceId('');
}
}
};
const handleResourceSelect = (selectedId: string) => {
setResourceId(selectedId);
const selectedItem = resources.find((r) => r.id === selectedId);
if (selectedItem && selectedItem.ownerId && (!ownerId || ownerId !== selectedItem.ownerId)) {
setOwnerId(selectedItem.ownerId);
if (granteeUserId === selectedItem.ownerId) {
setGranteeUserId('');
}
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsSubmitting(true);
try {
await api.post('/admin/permissions', {
ownerId,
granteeUserId,
resourceType,
resourceId: resourceId || undefined,
canViewMetadata,
canPreview,
canPlay,
canDownload,
canListFolder,
expiresAt: expiresAt ? new Date(expiresAt).toISOString() : undefined,
});
onSuccess();
onClose();
} catch (err: any) {
setError(err.message || 'Failed to grant permission');
} finally {
setIsSubmitting(false);
}
};
const selectedResource = resources.find((r) => r.id === resourceId);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-200">
<div className="w-full max-w-lg bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 bg-slate-50/50">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600 border border-emerald-100">
<KeyRound className="w-5 h-5" />
</div>
<div>
<h3 className="text-base font-semibold text-slate-900">Grant Granular Permission</h3>
<p className="text-xs text-slate-500">Authorize access to files and folders between users</p>
</div>
</div>
<button
onClick={onClose}
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="p-6 space-y-4 overflow-y-auto">
{error && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-700">
{error}
</div>
)}
{/* Owner Selector */}
<div>
<div className="flex items-center justify-between mb-1.5">
<label className="block text-xs font-medium text-slate-700">
Resource Owner
</label>
{ownerId && (
<span className="text-[11px] text-emerald-600 font-medium flex items-center gap-1">
<CheckCircle2 className="w-3 h-3" /> Selected
</span>
)}
</div>
<select
value={ownerId}
onChange={(e) => handleOwnerChange(e.target.value)}
required
className="w-full px-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 focus:outline-none focus:border-emerald-600 focus:bg-white transition-all"
>
<option value="">Select Resource Owner</option>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.fullName} ({u.email}) {u.companyName ? `• ${u.companyName}` : ''}
</option>
))}
</select>
</div>
{/* Grantee Selector */}
<div>
<label className="block text-xs font-medium text-slate-700 mb-1.5">
Grantee Recipient (Who receives access?)
</label>
<select
value={granteeUserId}
onChange={(e) => setGranteeUserId(e.target.value)}
required
className="w-full px-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 focus:outline-none focus:border-emerald-600 focus:bg-white transition-all"
>
<option value="">Select Recipient User</option>
{users
.filter((u) => u.id !== ownerId)
.map((u) => (
<option key={u.id} value={u.id}>
{u.fullName} ({u.email}) {u.companyName ? `• ${u.companyName}` : ''}
</option>
))}
</select>
</div>
{/* Permission Scope */}
<div>
<label className="block text-xs font-medium text-slate-700 mb-1.5">
Permission Scope
</label>
<select
value={resourceType}
onChange={(e) => {
const nextType = e.target.value as PermissionResourceType;
setResourceType(nextType);
if (nextType === PermissionResourceType.USER_FILES) {
setResourceId('');
}
}}
className="w-full px-3 py-2.5 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 focus:outline-none focus:border-emerald-600 focus:bg-white transition-all"
>
<option value={PermissionResourceType.FILE}>Specific File</option>
<option value={PermissionResourceType.FOLDER}>Specific Folder</option>
<option value={PermissionResourceType.USER_FILES}>All Owner's Files (Entire Account)</option>
</select>
</div>
{/* Resource ID (UUID) - Dropdown Selection */}
{resourceType !== PermissionResourceType.USER_FILES && (
<div className="space-y-1.5 bg-slate-50/60 p-3.5 rounded-xl border border-slate-200/80">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-slate-700 flex items-center gap-1.5">
{resourceType === PermissionResourceType.FILE ? (
<FileText className="w-3.5 h-3.5 text-emerald-600" />
) : (
<Folder className="w-3.5 h-3.5 text-amber-500" />
)}
<span>
Select {resourceType === PermissionResourceType.FILE ? 'File' : 'Folder'}{' '}
<span className="text-slate-400 font-normal">
({resources.length} available)
</span>
</span>
</label>
<button
type="button"
onClick={() => setIsManualInput(!isManualInput)}
className="text-[11px] text-emerald-600 hover:text-emerald-700 font-medium flex items-center gap-1 hover:underline"
>
<Edit3 className="w-3 h-3" />
<span>{isManualInput ? 'Use Dropdown List' : 'Enter Manual UUID'}</span>
</button>
</div>
{isManualInput ? (
<div>
<input
type="text"
value={resourceId}
onChange={(e) => setResourceId(e.target.value)}
placeholder={`Paste ${resourceType === PermissionResourceType.FILE ? 'File' : 'Folder'} UUID`}
required
className="w-full px-3 py-2.5 rounded-xl bg-white border border-slate-200 text-xs text-slate-900 font-mono focus:outline-none focus:border-emerald-600 shadow-sm"
/>
<p className="mt-1 text-[11px] text-slate-400">
Paste the exact 36-character UUID of the resource.
</p>
</div>
) : (
<div className="relative">
<select
value={resourceId}
onChange={(e) => handleResourceSelect(e.target.value)}
required
disabled={isLoadingResources}
className="w-full px-3 py-2.5 rounded-xl bg-white border border-slate-200 text-xs text-slate-900 focus:outline-none focus:border-emerald-600 shadow-sm disabled:opacity-60 transition-all"
>
<option value="">
{isLoadingResources
? 'Loading resources...'
: resources.length === 0
? `No ${resourceType.toLowerCase()}s found ${ownerId ? 'for this owner' : ''}`
: `-- Choose a ${resourceType === PermissionResourceType.FILE ? 'File' : 'Folder'} --`}
</option>
{resources.map((item) => (
<option key={item.id} value={item.id}>
{resourceType === PermissionResourceType.FILE
? `${item.name} (${formatBytes(item.sizeBytes)}) ${item.folderName && item.folderName !== 'Root' ? `• [Folder: ${item.folderName}]` : ''}${!ownerId ? ` • Owner: ${item.ownerName || item.ownerEmail}` : ''}`
: `${item.name} (${item.logicalPath || '/'})${!ownerId ? ` • Owner: ${item.ownerName || item.ownerEmail}` : ''}`}
</option>
))}
</select>
{isLoadingResources && (
<div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
<Loader2 className="w-3.5 h-3.5 text-slate-400 animate-spin" />
</div>
)}
</div>
)}
{/* Resource Info Badge */}
{resourceId && !isManualInput && (
<div className="flex items-center justify-between text-[11px] text-slate-600 bg-white border border-slate-200/90 rounded-lg px-2.5 py-1.5 mt-1 font-mono shadow-xs">
<span className="truncate max-w-[280px]">
ID: {resourceId}
</span>
{selectedResource?.category && (
<span className="text-[10px] uppercase font-sans font-semibold px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-700 border border-emerald-200">
{selectedResource.category}
</span>
)}
</div>
)}
</div>
)}
{/* Granular Permission Checkboxes */}
<div className="space-y-2 pt-2 border-t border-slate-200">
<span className="block text-xs font-semibold uppercase tracking-wider text-slate-600">
Granular Rights
</span>
<div className="grid grid-cols-2 gap-2 text-xs">
<label className="flex items-center gap-2 p-2.5 rounded-lg bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canViewMetadata}
onChange={(e) => setCanViewMetadata(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-slate-800 font-medium">View Metadata</span>
</label>
<label className="flex items-center gap-2 p-2.5 rounded-lg bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canPreview}
onChange={(e) => setCanPreview(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-slate-800 font-medium">Preview Media/Images</span>
</label>
<label className="flex items-center gap-2 p-2.5 rounded-lg bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canPlay}
onChange={(e) => setCanPlay(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-slate-800 font-medium">Stream & Play Video</span>
</label>
<label className="flex items-center gap-2 p-2.5 rounded-lg bg-slate-50 border border-slate-200 cursor-pointer hover:bg-slate-100">
<input
type="checkbox"
checked={canDownload}
onChange={(e) => setCanDownload(e.target.checked)}
className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-slate-800 font-medium">Download Original File</span>
</label>
</div>
</div>
{/* Expiration Date */}
<div>
<label className="block text-xs font-medium text-slate-700 mb-1">
Expiration Date (Optional)
</label>
<input
type="datetime-local"
value={expiresAt}
onChange={(e) => setExpiresAt(e.target.value)}
className="w-full px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
{/* Buttons */}
<div className="pt-3 flex items-center justify-end gap-2.5 border-t border-slate-200">
<button
type="button"
onClick={onClose}
className="px-4 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-xs font-medium text-slate-700 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={isSubmitting}
className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-xs font-medium text-white flex items-center gap-1.5 shadow-sm transition-colors"
>
{isSubmitting && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
<span>Grant Permissions</span>
</button>
</div>
</form>
</div>
</div>
);
};

View File

@@ -0,0 +1,58 @@
'use client';
import React from 'react';
import Image from 'next/image';
interface EcohubLogoProps {
size?: 'sm' | 'md' | 'lg' | 'xl';
showText?: boolean;
subtitle?: string;
className?: string;
textClassName?: string;
}
export const EcohubLogo: React.FC<EcohubLogoProps> = ({
size = 'md',
showText = true,
subtitle,
className = '',
textClassName = '',
}) => {
const sizeMap = {
sm: { img: 24, font: 'text-sm', badge: 'text-[9px]' },
md: { img: 32, font: 'text-base', badge: 'text-[10px]' },
lg: { img: 44, font: 'text-xl', badge: 'text-xs' },
xl: { img: 64, font: 'text-2xl', badge: 'text-xs' },
};
const config = sizeMap[size];
return (
<div className={`inline-flex items-center gap-2.5 ${className}`}>
<div className="relative flex-shrink-0 transition-transform hover:scale-105 duration-200">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/logo.png"
alt="Ecohub Logo"
width={config.img}
height={config.img}
className="object-contain drop-shadow-sm"
/>
</div>
{showText && (
<div className="flex flex-col leading-none">
<span
className={`font-black tracking-tight text-slate-900 flex items-center gap-1 ${config.font} ${textClassName}`}
>
<span>Ecohub</span>
<span className="text-emerald-600">Cloud</span>
</span>
<span className="text-[10px] font-semibold text-slate-400 tracking-wider uppercase mt-0.5">
{subtitle || 'Enterprise File & Video Vault'}
</span>
</div>
)}
</div>
);
};

View File

@@ -0,0 +1,58 @@
'use client';
import React from 'react';
interface EcohubWatermarkProps {
variant?: 'overlay' | 'corner' | 'subtle' | 'player';
className?: string;
}
export const EcohubWatermark: React.FC<EcohubWatermarkProps> = ({
variant = 'player',
className = '',
}) => {
if (variant === 'player') {
return (
<div
className={`pointer-events-none select-none z-20 flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-black/40 backdrop-blur-md border border-white/10 text-white/90 shadow-md ${className}`}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src="/logo.png"
alt="Ecohub"
className="w-4 h-4 object-contain opacity-90 drop-shadow"
/>
<span className="text-[11px] font-bold tracking-wider text-white/95">
Eco<span className="text-emerald-400">hub</span>
</span>
</div>
);
}
if (variant === 'subtle') {
return (
<div
className={`pointer-events-none select-none opacity-20 flex items-center gap-2 ${className}`}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/logo.png" alt="Ecohub" className="w-6 h-6 object-contain" />
<span className="text-xs font-black tracking-widest uppercase text-slate-400">
Ecohub Protected
</span>
</div>
);
}
return (
<div
className={`fixed bottom-4 right-4 pointer-events-none select-none z-30 flex items-center gap-2 px-3 py-1.5 rounded-2xl bg-white/90 backdrop-blur-md border border-slate-200/80 shadow-lg shadow-slate-200/50 ${className}`}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/logo.png" alt="Ecohub" className="w-5 h-5 object-contain" />
<span className="text-xs font-bold text-slate-800">
Eco<span className="text-emerald-600">hub</span>
</span>
<span className="text-[10px] text-slate-400 font-medium">Secured</span>
</div>
);
};

View File

@@ -0,0 +1,110 @@
'use client';
import { useEffect } from 'react';
// Intercept browser extension attribute mismatch warnings (e.g., bis_skin_checked injected by Urban VPN / Bitdefender)
// so that Next.js development error overlay does not trigger false-positive modal popups.
if (typeof window !== 'undefined') {
const origConsoleError = window.console.error;
window.console.error = function (...args: any[]) {
try {
const fullText = args
.map((a) => {
if (typeof a === 'string') return a;
if (a && typeof a === 'object') {
return (a.message || '') + ' ' + (a.stack || '') + ' ' + JSON.stringify(a);
}
return String(a || '');
})
.join(' ');
if (
fullText.includes('bis_skin_checked') ||
fullText.includes('bis_register') ||
fullText.includes('cz-shortcut-listen') ||
fullText.includes('data-gr-ext-installed')
) {
// Silently suppress browser-extension injected hydration error noise
return;
}
} catch {
// Fallback
}
return origConsoleError.apply(window.console, args);
};
}
export function HydrationGuard() {
useEffect(() => {
try {
// 1. Remove browser-extension injected attributes
const cleanInjectedAttributes = () => {
const els = document.querySelectorAll('[bis_skin_checked], [bis_register]');
els.forEach((el) => {
el.removeAttribute('bis_skin_checked');
el.removeAttribute('bis_register');
});
};
// 2. Hide idle Next.js 'N' dev indicator badge unless there is an error/issue
const manageDevIndicatorBadge = () => {
const portals = document.querySelectorAll('nextjs-portal');
portals.forEach((portal: any) => {
if (!portal.shadowRoot) return;
const root = portal.shadowRoot;
const hasError =
root.querySelector('[role="alert"], [data-nextjs-dialog-overlay], [data-nextjs-toast]') ||
(root.textContent && (root.textContent.includes('Issue') || root.textContent.includes('Error')));
const buttons = root.querySelectorAll('button');
buttons.forEach((btn: HTMLElement) => {
const isErrorButton = btn.textContent && (btn.textContent.includes('Issue') || btn.textContent.includes('Error'));
if (!hasError && !isErrorButton) {
btn.style.setProperty('display', 'none', 'important');
} else {
btn.style.removeProperty('display');
}
});
});
};
cleanInjectedAttributes();
manageDevIndicatorBadge();
// Interval check for dev indicator (only runs in dev mode)
const interval = setInterval(manageDevIndicatorBadge, 800);
const observer = new MutationObserver((mutations) => {
for (const m of mutations) {
if (
m.type === 'attributes' &&
m.attributeName &&
(m.attributeName.startsWith('bis_') || m.attributeName === 'cz-shortcut-listen')
) {
(m.target as Element).removeAttribute(m.attributeName);
}
}
manageDevIndicatorBadge();
});
if (document.documentElement) {
observer.observe(document.documentElement, {
attributes: true,
subtree: true,
childList: true,
attributeFilter: ['bis_skin_checked', 'bis_register'],
});
}
return () => {
clearInterval(interval);
observer.disconnect();
};
} catch {
// ignore
}
}, []);
return null;
}

View File

@@ -0,0 +1,48 @@
'use client';
import React from 'react';
import { ChevronRight, Home } from 'lucide-react';
interface BreadcrumbsProps {
breadcrumbs: { id: string; name: string }[];
onSelectFolder: (folderId: string) => void;
}
export const Breadcrumbs: React.FC<BreadcrumbsProps> = ({
breadcrumbs,
onSelectFolder,
}) => {
return (
<nav className="flex items-center space-x-1.5 text-xs text-slate-400 py-1.5 overflow-x-auto">
<button
onClick={() => onSelectFolder('root')}
className="flex items-center gap-1 px-2 py-1 rounded-lg hover:text-slate-200 hover:bg-slate-800 transition-colors"
>
<Home className="w-3.5 h-3.5 text-indigo-400" />
<span>Root</span>
</button>
{breadcrumbs.map((crumb, idx) => {
const isLast = idx === breadcrumbs.length - 1;
// Don't duplicate the root folder if it's already shown
if (crumb.name === 'Root') return null;
return (
<React.Fragment key={crumb.id}>
<ChevronRight className="w-3.5 h-3.5 text-slate-600 flex-shrink-0" />
<button
onClick={() => onSelectFolder(crumb.id)}
className={`px-2 py-1 rounded-lg transition-colors truncate max-w-[120px] sm:max-w-[200px] ${
isLast
? 'text-indigo-400 font-semibold bg-indigo-500/10'
: 'hover:text-slate-200 hover:bg-slate-800'
}`}
>
{crumb.name}
</button>
</React.Fragment>
);
})}
</nav>
);
};

View File

@@ -0,0 +1,300 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { api } from '@/lib/api-client';
import { formatBytes, formatDuration, formatDate } from '@/lib/utils';
import { FileCategory, FileStatus } from '@fileshare/shared';
import {
FileVideo,
FileImage,
FileText,
FileArchive,
FileAudio,
File,
Play,
Eye,
Download,
MoreVertical,
Trash2,
Edit2,
FolderInput,
Loader2,
ShieldAlert,
Share2,
Lock,
Building2,
} from 'lucide-react';
interface FileCardProps {
file: any;
onPreview: (file: any) => void;
onRename: (file: any) => void;
onMove: (file: any) => void;
onDelete: (file: any) => void;
onShare?: (file: any) => void;
canShare?: boolean;
canDelete?: boolean;
isOwner?: boolean;
}
export const FileCard: React.FC<FileCardProps> = ({
file,
onPreview,
onRename,
onMove,
onDelete,
onShare,
canShare = false,
canDelete = true,
isOwner = true,
}) => {
const [showMenu, setShowMenu] = useState(false);
const canPlay = file.permissions ? file.permissions.canPlay : true;
const canDownload = file.permissions ? file.permissions.canDownload : true;
const canPreview = file.permissions ? file.permissions.canPreview : true;
const thumbnailUrl = file.hasThumbnail ? api.getThumbnailUrl(file.id) : null;
const downloadUrl = api.getDownloadUrl(file.id);
const getCategoryIcon = () => {
switch (file.fileCategory) {
case FileCategory.VIDEO:
return <FileVideo className="w-8 h-8 text-rose-500" />;
case FileCategory.IMAGE:
return <FileImage className="w-8 h-8 text-emerald-500" />;
case FileCategory.DOCUMENT:
return <FileText className="w-8 h-8 text-sky-500" />;
case FileCategory.ARCHIVE:
return <FileArchive className="w-8 h-8 text-amber-500" />;
case FileCategory.AUDIO:
return <FileAudio className="w-8 h-8 text-pink-500" />;
default:
return <File className="w-8 h-8 text-slate-400" />;
}
};
return (
<div className="bg-white rounded-2xl p-3 flex flex-col justify-between group relative border border-slate-200/90 shadow-sm hover:shadow-md hover:border-emerald-300 transition-all">
{/* Thumbnail or Icon Box */}
<div
onClick={() => onPreview(file)}
className="relative w-full aspect-video rounded-xl bg-slate-100 overflow-hidden flex items-center justify-center cursor-pointer border border-slate-200/60"
>
{thumbnailUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={thumbnailUrl}
alt={file.originalFilename}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
/>
) : (
<div className="flex flex-col items-center justify-center p-4">
{getCategoryIcon()}
</div>
)}
{/* Video duration badge */}
{file.fileCategory === FileCategory.VIDEO && file.durationSeconds && (
<span className="absolute bottom-2 right-2 px-1.5 py-0.5 rounded-md bg-black/75 backdrop-blur-sm text-[10px] font-mono text-white">
{formatDuration(file.durationSeconds)}
</span>
)}
{/* Processing State Overlay */}
{file.status === FileStatus.PROCESSING && (
<div className="absolute inset-0 bg-white/80 backdrop-blur-sm flex flex-col items-center justify-center gap-1.5">
<Loader2 className="w-5 h-5 text-emerald-600 animate-spin" />
<span className="text-[10px] font-semibold text-emerald-700">Transcoding...</span>
</div>
)}
{/* Failed State Overlay */}
{file.status === FileStatus.FAILED && (
<div className="absolute inset-0 bg-rose-50/90 backdrop-blur-sm flex flex-col items-center justify-center gap-1 p-2 text-center">
<ShieldAlert className="w-5 h-5 text-rose-500" />
<span className="text-[10px] font-semibold text-rose-700">Processing Failed</span>
</div>
)}
</div>
{/* File Info */}
<div className="mt-3 space-y-1">
<div className="flex items-start justify-between gap-2">
<p
onClick={() => onPreview(file)}
title={file.originalFilename}
className="text-xs font-bold text-slate-800 truncate cursor-pointer hover:text-emerald-600 transition-colors flex-1"
>
{file.originalFilename}
</p>
{/* Action dropdown button */}
<div className="relative">
<button
onClick={() => setShowMenu(!showMenu)}
className="p-1 rounded-md text-slate-400 hover:text-slate-700 hover:bg-slate-100"
>
<MoreVertical className="w-3.5 h-3.5" />
</button>
{showMenu && (
<div
onMouseLeave={() => setShowMenu(false)}
className="absolute right-0 top-6 w-36 py-1 bg-white border border-slate-200 rounded-xl shadow-xl z-30"
>
{canPreview && (
<button
onClick={() => {
setShowMenu(false);
onPreview(file);
}}
className="w-full text-left px-3 py-1.5 text-xs text-slate-700 hover:bg-slate-50 flex items-center gap-2"
>
<Eye className="w-3.5 h-3.5 text-slate-400" /> Preview
</button>
)}
{canDownload && (
<a
href={downloadUrl}
download={file.originalFilename}
onClick={() => setShowMenu(false)}
className="w-full text-left px-3 py-1.5 text-xs text-slate-700 hover:bg-slate-50 flex items-center gap-2"
>
<Download className="w-3.5 h-3.5 text-slate-400" /> Download
</a>
)}
{isOwner && onShare && (
<button
onClick={() => {
setShowMenu(false);
if (canShare) onShare(file);
else alert('Share link creation has been disabled by Administrator for your account.');
}}
className={`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 ${
canShare ? 'text-emerald-700 hover:bg-emerald-50 font-medium' : 'text-slate-400 cursor-not-allowed'
}`}
>
<Share2 className="w-3.5 h-3.5" />
<span>Share Link {canShare ? '' : '(Disabled)'}</span>
</button>
)}
{isOwner && (
<>
<button
onClick={() => {
setShowMenu(false);
onRename(file);
}}
className="w-full text-left px-3 py-1.5 text-xs text-slate-700 hover:bg-slate-50 flex items-center gap-2"
>
<Edit2 className="w-3.5 h-3.5 text-slate-400" /> Rename
</button>
<button
onClick={() => {
setShowMenu(false);
onMove(file);
}}
className="w-full text-left px-3 py-1.5 text-xs text-slate-700 hover:bg-slate-50 flex items-center gap-2"
>
<FolderInput className="w-3.5 h-3.5 text-slate-400" /> Move
</button>
{canDelete ? (
<button
onClick={() => {
setShowMenu(false);
onDelete(file);
}}
className="w-full text-left px-3 py-1.5 text-xs text-rose-600 hover:bg-rose-50 flex items-center gap-2 font-medium"
>
<Trash2 className="w-3.5 h-3.5" /> Delete
</button>
) : (
<button
disabled
className="w-full text-left px-3 py-1.5 text-xs text-slate-400 flex items-center gap-2 cursor-not-allowed"
title="Deletion disabled by Administrator"
>
<Lock className="w-3.5 h-3.5" /> Delete (Disabled)
</button>
)}
</>
)}
</div>
)}
</div>
</div>
<div className="flex items-center justify-between text-[11px] text-slate-500">
<span>{formatBytes(file.fileSizeBytes)}</span>
{file.ownerCompanyName ? (
<span className="text-[10px] text-emerald-700 font-semibold truncate max-w-[110px] flex items-center gap-0.5">
<Building2 className="w-2.5 h-2.5 flex-shrink-0" />
{file.ownerCompanyName}
</span>
) : (
<span>{formatDate(file.createdAt)}</span>
)}
</div>
{/* Quick Actions Footer */}
<div className="pt-2 flex items-center justify-between border-t border-slate-100 mt-2">
<div className="flex items-center gap-2">
{file.fileCategory === FileCategory.VIDEO && canPlay ? (
<Link
href={`/video/${file.id}`}
className="flex items-center gap-1.5 text-[11px] font-bold text-emerald-600 hover:text-emerald-700"
>
<Play className="w-3 h-3 fill-current" /> Play Video
</Link>
) : (
<button
onClick={() => onPreview(file)}
className="flex items-center gap-1 text-[11px] font-medium text-slate-500 hover:text-slate-800"
>
<Eye className="w-3 h-3" /> View
</button>
)}
{isOwner && onShare && (
<button
onClick={() => {
if (canShare) onShare(file);
else alert('Share link creation is disabled by Administrator for your account.');
}}
className={`p-1 rounded transition-colors ${
canShare ? 'text-slate-400 hover:text-emerald-600' : 'text-slate-300 cursor-not-allowed'
}`}
title={canShare ? 'Create Google Drive share link' : 'Share link disabled by Administrator'}
>
<Share2 className="w-3.5 h-3.5" />
</button>
)}
</div>
{canDownload ? (
<a
href={downloadUrl}
download={file.originalFilename}
className="p-1 text-slate-400 hover:text-emerald-600"
title="Download file"
>
<Download className="w-3.5 h-3.5" />
</a>
) : (
<span
title="Download permission not granted by administrator"
className="text-[10px] text-slate-400 cursor-not-allowed"
>
No download
</span>
)}
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,148 @@
'use client';
import React from 'react';
import { api } from '@/lib/api-client';
import { formatBytes } from '@/lib/utils';
import { HlsVideoPlayer } from '../video-player/HlsVideoPlayer';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
import { FileCategory } from '@fileshare/shared';
import { X, Download, FileText, Building2 } from 'lucide-react';
interface FilePreviewModalProps {
isOpen: boolean;
onClose: () => void;
file: any | null;
}
export const FilePreviewModal: React.FC<FilePreviewModalProps> = ({
isOpen,
onClose,
file,
}) => {
if (!isOpen || !file) return null;
const previewUrl = api.getPreviewUrl(file.id);
const downloadUrl = api.getDownloadUrl(file.id);
const canDownload = file.permissions ? file.permissions.canDownload : true;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
<div className="w-full max-w-4xl bg-white border border-slate-200 rounded-3xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 bg-slate-50/70">
<div className="min-w-0 pr-4">
<h3 className="text-base font-bold text-slate-900 truncate">
{file.originalFilename}
</h3>
<div className="flex items-center gap-2 text-xs text-slate-500 mt-0.5">
<span>{formatBytes(file.fileSizeBytes)}</span>
<span>•</span>
<span className="uppercase font-semibold text-slate-600">{file.fileCategory}</span>
{file.ownerCompanyName && (
<>
<span>•</span>
<span className="text-emerald-700 font-semibold flex items-center gap-1">
<Building2 className="w-3 h-3" />
{file.ownerCompanyName}
</span>
</>
)}
</div>
</div>
<div className="flex items-center gap-2">
{canDownload ? (
<a
href={downloadUrl}
download={file.originalFilename}
className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold shadow-sm transition-colors"
>
<Download className="w-4 h-4" />
<span>Download</span>
</a>
) : file.fileCategory === FileCategory.VIDEO ? (
<span className="px-3 py-1.5 rounded-xl bg-slate-100 border border-slate-200 text-slate-500 text-xs font-medium">
View Only Video
</span>
) : null}
<button
onClick={onClose}
className="p-1.5 rounded-xl text-slate-400 hover:text-slate-700 hover:bg-slate-200/60 transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
</div>
{/* Content Viewer */}
<div className="flex-1 p-6 overflow-y-auto flex items-center justify-center min-h-[400px] bg-slate-100/40 relative">
{file.fileCategory === FileCategory.IMAGE && (
<div className="relative flex items-center justify-center">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={previewUrl}
alt={file.originalFilename}
className="max-h-[70vh] max-w-full rounded-2xl object-contain shadow-md"
/>
<EcohubWatermark variant="player" className="absolute bottom-4 right-4" />
</div>
)}
{file.fileCategory === FileCategory.VIDEO && (
<div className="w-full max-w-3xl">
<HlsVideoPlayer
fileId={file.id}
hasHlsStream={file.hasHlsStream}
title={file.originalFilename}
durationSeconds={file.durationSeconds}
width={file.width}
height={file.height}
videoCodec={file.videoCodec}
/>
</div>
)}
{file.fileCategory === FileCategory.AUDIO && (
<div className="p-8 rounded-2xl bg-white border border-slate-200 w-full max-w-md text-center shadow-sm">
<audio controls src={previewUrl} className="w-full mt-4" />
<div className="mt-4 flex justify-center">
<EcohubWatermark variant="subtle" />
</div>
</div>
)}
{file.fileCategory === FileCategory.DOCUMENT && (
<div className="w-full h-full relative">
<iframe
src={previewUrl}
className="w-full h-[65vh] rounded-2xl border border-slate-200 bg-white"
/>
</div>
)}
{file.fileCategory === FileCategory.ARCHIVE || file.fileCategory === FileCategory.OTHER ? (
<div className="text-center p-8">
<FileText className="w-16 h-16 text-slate-400 mx-auto mb-3" />
<p className="text-sm font-semibold text-slate-700">
Direct inline preview not available for this file type.
</p>
{canDownload ? (
<a
href={downloadUrl}
className="inline-flex items-center gap-2 mt-4 px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold shadow-sm"
>
<Download className="w-4 h-4" />
<span>Download Original</span>
</a>
) : (
<p className="text-xs text-rose-500 mt-2 font-medium">
Download permission is not granted by administrator.
</p>
)}
</div>
) : null}
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,221 @@
'use client';
import React from 'react';
import Link from 'next/link';
import { api } from '@/lib/api-client';
import { formatBytes, formatDuration, formatDate } from '@/lib/utils';
import { FileCategory, FileStatus } from '@fileshare/shared';
import {
FileVideo,
FileImage,
FileText,
FileArchive,
FileAudio,
File,
Play,
Eye,
Download,
Trash2,
Edit2,
FolderInput,
Loader2,
Share2,
Lock,
Building2,
} from 'lucide-react';
interface FileRowProps {
file: any;
onPreview: (file: any) => void;
onRename: (file: any) => void;
onMove: (file: any) => void;
onDelete: (file: any) => void;
onShare?: (file: any) => void;
canShare?: boolean;
canDelete?: boolean;
isOwner?: boolean;
}
export const FileRow: React.FC<FileRowProps> = ({
file,
onPreview,
onRename,
onMove,
onDelete,
onShare,
canShare = false,
canDelete = true,
isOwner = true,
}) => {
const canPlay = file.permissions ? file.permissions.canPlay : true;
const canDownload = file.permissions ? file.permissions.canDownload : true;
const canPreview = file.permissions ? file.permissions.canPreview : true;
const downloadUrl = api.getDownloadUrl(file.id);
const getCategoryIcon = () => {
switch (file.fileCategory) {
case FileCategory.VIDEO:
return <FileVideo className="w-4 h-4 text-rose-500" />;
case FileCategory.IMAGE:
return <FileImage className="w-4 h-4 text-emerald-500" />;
case FileCategory.DOCUMENT:
return <FileText className="w-4 h-4 text-sky-500" />;
case FileCategory.ARCHIVE:
return <FileArchive className="w-4 h-4 text-amber-500" />;
case FileCategory.AUDIO:
return <FileAudio className="w-4 h-4 text-pink-500" />;
default:
return <File className="w-4 h-4 text-slate-400" />;
}
};
return (
<tr className="border-b border-slate-100 hover:bg-slate-50/80 transition-colors text-xs">
{/* Name and Icon */}
<td className="py-3 px-4">
<div className="flex items-center gap-3">
<div className="p-1.5 rounded-lg bg-slate-100 border border-slate-200 flex-shrink-0">
{getCategoryIcon()}
</div>
<div className="min-w-0">
<span
onClick={() => onPreview(file)}
className="font-semibold text-slate-800 hover:text-emerald-600 cursor-pointer truncate block max-w-xs sm:max-w-md"
>
{file.originalFilename}
</span>
<div className="flex items-center gap-2 mt-0.5">
{file.ownerCompanyName && (
<span className="text-[10px] text-emerald-700 font-semibold flex items-center gap-0.5">
<Building2 className="w-2.5 h-2.5" />
{file.ownerCompanyName}
</span>
)}
{file.fileCategory === FileCategory.VIDEO && file.durationSeconds && (
<span className="text-[10px] text-slate-400 font-mono">
Duration: {formatDuration(file.durationSeconds)}
</span>
)}
</div>
</div>
</div>
</td>
{/* Category */}
<td className="py-3 px-4 hidden md:table-cell text-slate-500 font-mono text-[11px] uppercase">
{file.fileCategory}
</td>
{/* Size */}
<td className="py-3 px-4 text-slate-600 font-mono text-[11px]">
{formatBytes(file.fileSizeBytes)}
</td>
{/* Date */}
<td className="py-3 px-4 hidden sm:table-cell text-slate-500">
{formatDate(file.createdAt)}
</td>
{/* Status */}
<td className="py-3 px-4">
{file.status === FileStatus.PROCESSING ? (
<span className="inline-flex items-center gap-1 text-[11px] text-emerald-600 font-medium">
<Loader2 className="w-3 h-3 animate-spin" /> Processing
</span>
) : file.status === FileStatus.FAILED ? (
<span className="text-[11px] text-rose-600 font-semibold">Failed</span>
) : (
<span className="text-[11px] text-emerald-600 font-medium">Ready</span>
)}
</td>
{/* Actions */}
<td className="py-3 px-4 text-right">
<div className="flex items-center justify-end gap-1.5">
{file.fileCategory === FileCategory.VIDEO && canPlay ? (
<Link
href={`/video/${file.id}`}
className="p-1.5 rounded-lg hover:bg-emerald-50 text-emerald-600 hover:text-emerald-700 transition-colors"
title="Play Video"
>
<Play className="w-3.5 h-3.5 fill-current" />
</Link>
) : (
canPreview && (
<button
onClick={() => onPreview(file)}
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500 hover:text-slate-800"
title="Preview"
>
<Eye className="w-3.5 h-3.5" />
</button>
)
)}
{canDownload && (
<a
href={downloadUrl}
download={file.originalFilename}
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500 hover:text-emerald-600"
title="Download"
>
<Download className="w-3.5 h-3.5" />
</a>
)}
{isOwner && (
<>
{onShare && (
<button
onClick={() => {
if (canShare) onShare(file);
else alert('Share link creation is disabled by Administrator for your account.');
}}
className={`p-1.5 rounded-lg transition-colors ${
canShare
? 'hover:bg-emerald-50 text-slate-500 hover:text-emerald-600'
: 'text-slate-300 cursor-not-allowed'
}`}
title={canShare ? 'Create Google Drive share link' : 'Share link disabled by Administrator'}
>
<Share2 className="w-3.5 h-3.5" />
</button>
)}
<button
onClick={() => onRename(file)}
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500 hover:text-slate-800"
title="Rename"
>
<Edit2 className="w-3.5 h-3.5" />
</button>
<button
onClick={() => onMove(file)}
className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500 hover:text-slate-800"
title="Move"
>
<FolderInput className="w-3.5 h-3.5" />
</button>
{canDelete ? (
<button
onClick={() => onDelete(file)}
className="p-1.5 rounded-lg hover:bg-rose-50 text-rose-500 hover:text-rose-700"
title="Delete"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
) : (
<button
disabled
className="p-1.5 rounded-lg text-slate-300 cursor-not-allowed"
title="Deletion disabled by Administrator"
>
<Lock className="w-3.5 h-3.5" />
</button>
)}
</>
)}
</div>
</td>
</tr>
);
};

View File

@@ -0,0 +1,342 @@
'use client';
import React, { useState, useEffect } from 'react';
import { api } from '@/lib/api-client';
import { formatDate, copyTextToClipboard } from '@/lib/utils';
import {
X,
Share2,
Copy,
Check,
Globe,
Lock,
Trash2,
Loader2,
ExternalLink,
ShieldAlert,
} from 'lucide-react';
interface CreateShareLinkModalProps {
isOpen: boolean;
onClose: () => void;
target: {
type: 'FILE' | 'FOLDER';
id: string;
name: string;
} | null;
}
export const CreateShareLinkModal: React.FC<CreateShareLinkModalProps> = ({
isOpen,
onClose,
target,
}) => {
const [title, setTitle] = useState('');
const [allowDownload, setAllowDownload] = useState(true);
const [password, setPassword] = useState('');
const [expiresInDays, setExpiresInDays] = useState(0); // 0 = never
const [isCreating, setIsCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [existingLinks, setExistingLinks] = useState<any[]>([]);
const [isLoadingLinks, setIsLoadingLinks] = useState(false);
const [copiedToken, setCopiedToken] = useState<string | null>(null);
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
const loadExistingLinks = async () => {
if (!target) return;
setIsLoadingLinks(true);
try {
const allLinks = await api.get<any[]>('/share-links');
const filtered = (allLinks || []).filter(
(l) =>
(target.type === 'FILE' && l.fileId === target.id) ||
(target.type === 'FOLDER' && l.folderId === target.id),
);
setExistingLinks(filtered);
} catch {
setExistingLinks([]);
} finally {
setIsLoadingLinks(false);
}
};
useEffect(() => {
if (target && isOpen) {
setTitle(target.name);
setAllowDownload(true);
setPassword('');
setExpiresInDays(0);
setError(null);
loadExistingLinks();
}
}, [target, isOpen]);
if (!isOpen || !target) return null;
const handleCreateLink = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setIsCreating(true);
try {
const payload: any = {
resourceType: target.type,
title: title.trim() || target.name,
allowDownload,
expiresInDays: expiresInDays > 0 ? expiresInDays : undefined,
password: password.trim() ? password.trim() : undefined,
};
if (target.type === 'FILE') {
payload.fileId = target.id;
} else {
payload.folderId = target.id;
}
await api.post('/share-links', payload);
setPassword('');
loadExistingLinks();
} catch (err: any) {
setError(err.message || 'Failed to create share link');
} finally {
setIsCreating(false);
}
};
const handleRevokeLink = async (linkId: string) => {
if (!confirm('Are you sure you want to revoke this share link? Anyone with this link will immediately lose access.')) {
return;
}
try {
await api.delete(`/share-links/${linkId}`);
loadExistingLinks();
} catch (err: any) {
alert(err.message || 'Failed to revoke link');
}
};
const copyToClipboard = async (token: string) => {
try {
const fullUrl = `${window.location.origin}/s/${token}`;
await copyTextToClipboard(fullUrl);
setCopiedToken(token);
setTimeout(() => setCopiedToken(null), 2500);
} catch (err) {
console.warn('Failed to copy share link', err);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
<div className="w-full max-w-lg bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
{/* Modal Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 shrink-0">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-xl bg-emerald-50 text-emerald-600">
<Share2 className="w-5 h-5" />
</div>
<div>
<h3 className="text-base font-semibold text-slate-900">
Share & Create Link (Google Drive style)
</h3>
<p className="text-[11px] text-slate-500 truncate max-w-xs">
Resource: <span className="font-semibold text-slate-700">{target.name}</span>
</p>
</div>
</div>
<button onClick={onClose} className="p-1 rounded-lg text-slate-400 hover:text-slate-600">
<X className="w-5 h-5" />
</button>
</div>
<div className="p-6 space-y-5 overflow-y-auto custom-scrollbar text-xs">
{error && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 flex items-center gap-2">
<ShieldAlert className="w-4 h-4 shrink-0" />
<span>{error}</span>
</div>
)}
{/* Active Links Section */}
<div>
<div className="flex items-center justify-between mb-2">
<span className="font-semibold text-slate-800">Active Share Links</span>
<span className="text-[11px] text-slate-500">
{existingLinks.length} active {existingLinks.length === 1 ? 'link' : 'links'}
</span>
</div>
{isLoadingLinks ? (
<div className="py-4 text-center text-slate-500 flex items-center justify-center gap-2">
<Loader2 className="w-4 h-4 animate-spin text-emerald-600" />
<span>Loading share links...</span>
</div>
) : existingLinks.length === 0 ? (
<div className="p-3.5 rounded-xl bg-slate-50 border border-slate-200 text-center text-slate-500 text-xs">
No active share links yet. Generate one below to share this {target.type.toLowerCase()}!
</div>
) : (
<div className="space-y-2.5">
{existingLinks.map((link) => {
const shareUrl = mounted
? `${window.location.origin}/s/${link.token}`
: `/s/${link.token}`;
const isCopied = copiedToken === link.token;
return (
<div
key={link.id}
className="p-3 rounded-xl bg-slate-50 border border-slate-200 space-y-2"
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5 flex-wrap">
<span className="font-semibold text-slate-900">{link.title || target.name}</span>
{link.allowDownload ? (
<span className="px-1.5 py-0.5 rounded text-[10px] bg-emerald-100 text-emerald-800 font-medium">
Download Allowed
</span>
) : (
<span className="px-1.5 py-0.5 rounded text-[10px] bg-amber-100 text-amber-800 font-medium">
View/Stream Only
</span>
)}
{link.hasPassword && (
<span className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-sky-100 text-sky-800 font-medium">
<Lock className="w-2.5 h-2.5" /> Password
</span>
)}
</div>
<button
onClick={() => handleRevokeLink(link.id)}
className="p-1 rounded text-slate-400 hover:text-rose-600 hover:bg-rose-50 transition-colors"
title="Revoke link"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
<div className="flex items-center gap-2">
<input
type="text"
readOnly
value={shareUrl}
className="flex-1 px-2.5 py-1.5 rounded-lg bg-white border border-slate-300 font-mono text-[11px] text-slate-800 select-all"
/>
<button
onClick={() => copyToClipboard(link.token)}
className={`flex items-center gap-1 px-3 py-1.5 rounded-lg font-medium text-xs transition-colors ${
isCopied
? 'bg-emerald-700 text-white'
: 'bg-emerald-600 hover:bg-emerald-700 text-white'
}`}
>
{isCopied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
<span>{isCopied ? 'Copied!' : 'Copy'}</span>
</button>
<a
href={shareUrl}
target="_blank"
rel="noopener noreferrer"
className="p-1.5 rounded-lg bg-white border border-slate-300 hover:bg-slate-100 text-slate-700"
title="Open link in new tab"
>
<ExternalLink className="w-3.5 h-3.5" />
</a>
</div>
<div className="flex items-center gap-4 text-[10px] text-slate-500 pt-0.5">
<span>Views: {link.viewCount}</span>
<span>Downloads: {link.downloadCount}</span>
<span>
Expires: {link.expiresAt ? formatDate(link.expiresAt) : 'Never'}
</span>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Create New Link Form */}
<form onSubmit={handleCreateLink} className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-3.5">
<div className="flex items-center gap-1.5 text-slate-800 font-semibold border-b border-slate-200 pb-2">
<Globe className="w-4 h-4 text-emerald-600" />
<span>Create New Share Link</span>
</div>
<div>
<label className="block text-slate-700 font-medium mb-1">Link Title (Optional)</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Give this link a memorable name"
className="w-full px-3 py-2 rounded-xl bg-white border border-slate-300 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-slate-700 font-medium mb-1">Expiration</label>
<select
value={expiresInDays}
onChange={(e) => setExpiresInDays(Number(e.target.value))}
className="w-full px-3 py-2 rounded-xl bg-white border border-slate-300 text-slate-900 focus:outline-none focus:border-emerald-600"
>
<option value={0}>Never Expires</option>
<option value={1}>1 Day</option>
<option value={7}>7 Days</option>
<option value={30}>30 Days</option>
</select>
</div>
<div>
<label className="block text-slate-700 font-medium mb-1">Password Protect (Optional)</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Leave blank for public"
className="w-full px-3 py-2 rounded-xl bg-white border border-slate-300 text-slate-900 focus:outline-none focus:border-emerald-600"
/>
</div>
</div>
<label className="flex items-center gap-2.5 cursor-pointer pt-1">
<input
type="checkbox"
checked={allowDownload}
onChange={(e) => setAllowDownload(e.target.checked)}
className="w-4 h-4 rounded border-slate-300 text-emerald-600 focus:ring-emerald-500"
/>
<div>
<span className="font-semibold text-slate-800 block">Allow File Download</span>
<span className="text-[10px] text-slate-500">
When enabled, visitors can download the file. If disabled, they can only view or stream in-browser.
</span>
</div>
</label>
<div className="pt-2 flex justify-end">
<button
type="submit"
disabled={isCreating}
className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-medium flex items-center gap-2 shadow-sm"
>
{isCreating && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
<span>Generate Share Link</span>
</button>
</div>
</form>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,194 @@
'use client';
import React, { useState } from 'react';
import { api } from '@/lib/api-client';
import { KeyRound, Lock, Eye, EyeOff, CheckCircle2, AlertCircle, X, ShieldCheck } from 'lucide-react';
interface ChangePasswordModalProps {
isOpen: boolean;
onClose: () => void;
username: string;
}
export const ChangePasswordModal: React.FC<ChangePasswordModalProps> = ({
isOpen,
onClose,
username,
}) => {
const [currentPassword, setCurrentPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [showCurrent, setShowCurrent] = useState(false);
const [showNew, setShowNew] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
if (!isOpen) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
if (!currentPassword) {
setError('Please enter your current password');
return;
}
if (!newPassword || newPassword.length < 1) {
setError('Please enter your new password');
return;
}
if (newPassword !== confirmPassword) {
setError('New passwords do not match');
return;
}
setIsLoading(true);
try {
await api.post('/auth/change-password', {
currentPassword,
newPassword,
});
setSuccess('Password updated successfully!');
setCurrentPassword('');
setNewPassword('');
setConfirmPassword('');
setTimeout(() => {
onClose();
setSuccess(null);
}, 1500);
} catch (err: any) {
setError(err.message || 'Failed to change password');
} finally {
setIsLoading(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm animate-in fade-in">
<div className="relative w-full max-w-md rounded-2xl bg-slate-900 border border-slate-800 p-6 shadow-2xl shadow-indigo-950/40">
<button
onClick={onClose}
className="absolute top-4 right-4 p-1.5 text-slate-400 hover:text-white rounded-lg hover:bg-slate-800 transition-colors"
>
<X className="w-5 h-5" />
</button>
<div className="flex items-center gap-3 mb-5">
<div className="w-10 h-10 rounded-xl bg-indigo-600/20 border border-indigo-500/30 flex items-center justify-center text-indigo-400">
<KeyRound className="w-5 h-5" />
</div>
<div>
<h2 className="text-lg font-bold text-white">Change Password</h2>
<p className="text-xs text-slate-400">Update login password for {username}</p>
</div>
</div>
{error && (
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-xs text-rose-400">
<AlertCircle className="w-4 h-4 shrink-0" />
<span>{error}</span>
</div>
)}
{success && (
<div className="mb-4 flex items-center gap-2 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-xs text-emerald-400">
<CheckCircle2 className="w-4 h-4 shrink-0" />
<span>{success}</span>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1.5">
Current Password
</label>
<div className="relative">
<input
type={showCurrent ? 'text' : 'password'}
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
placeholder="Enter your current password"
required
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-sm text-white focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors pr-10"
/>
<button
type="button"
onClick={() => setShowCurrent(!showCurrent)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-200"
>
{showCurrent ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1.5">
New Password
</label>
<div className="relative">
<input
type={showNew ? 'text' : 'password'}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="Enter new password"
required
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-sm text-white focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors pr-10"
/>
<button
type="button"
onClick={() => setShowNew(!showNew)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-200"
>
{showNew ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1.5">
Confirm New Password
</label>
<input
type={showNew ? 'text' : 'password'}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="Confirm new password"
required
className="w-full px-3.5 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-sm text-white focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors"
/>
</div>
<div className="flex items-center justify-end gap-3 pt-3">
<button
type="button"
onClick={onClose}
disabled={isLoading}
className="px-4 py-2 rounded-xl text-xs font-semibold text-slate-400 hover:text-white hover:bg-slate-800 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={isLoading}
className="flex items-center gap-2 px-5 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 active:scale-95 text-white font-medium text-xs shadow-md shadow-indigo-600/30 transition-all disabled:opacity-50"
>
{isLoading ? (
<>Updating...</>
) : (
<>
<ShieldCheck className="w-4 h-4" />
<span>Update Password</span>
</>
)}
</button>
</div>
</form>
</div>
</div>
);
};

View File

@@ -0,0 +1,141 @@
'use client';
import React, { useState } from 'react';
import Link from 'next/link';
import { useAuth } from '@/context/auth-context';
import { formatBytes } from '@/lib/utils';
import { ChangePasswordModal } from '@/components/layout/ChangePasswordModal';
import { EcohubLogo } from '@/components/common/EcohubLogo';
import {
UploadCloud,
LogOut,
User,
HardDrive,
Menu,
KeyRound,
Building2,
} from 'lucide-react';
interface NavbarProps {
onOpenUpload?: () => void;
onToggleSidebar?: () => void;
}
export const Navbar: React.FC<NavbarProps> = ({ onOpenUpload, onToggleSidebar }) => {
const { user, logout, isSuperAdmin, isAdmin } = useAuth();
const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);
const quota = user ? Number(user.storageQuotaBytes) : 0;
const used = user ? Number(user.storageUsedBytes) : 0;
const percent = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
return (
<header className="sticky top-0 z-40 w-full bg-white/95 backdrop-blur-md border-b border-slate-200/80 shadow-sm">
<div className="flex h-16 items-center justify-between px-4 sm:px-6">
{/* Left: Mobile hamburger & Ecohub Logo */}
<div className="flex items-center gap-3">
{onToggleSidebar && (
<button
onClick={onToggleSidebar}
className="lg:hidden p-2 rounded-xl text-slate-500 hover:text-slate-800 hover:bg-slate-100 transition-colors"
>
<Menu className="w-5 h-5" />
</button>
)}
<Link href="/dashboard" className="flex items-center gap-2 group">
<EcohubLogo size="sm" />
</Link>
</div>
{/* Right actions */}
<div className="flex items-center gap-3 sm:gap-4">
{/* Storage mini-meter */}
{user && (
<div className="hidden md:flex items-center gap-2.5 px-3 py-1.5 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-700">
<HardDrive className="w-3.5 h-3.5 text-emerald-600" />
<span>
{formatBytes(used)} / {formatBytes(quota)}
</span>
<div className="w-16 h-1.5 bg-slate-200 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all ${
percent > 90 ? 'bg-rose-500' : percent > 75 ? 'bg-amber-500' : 'bg-emerald-600'
}`}
style={{ width: `${percent}%` }}
/>
</div>
</div>
)}
{/* Upload Button */}
{onOpenUpload && (
<button
onClick={onOpenUpload}
className="flex items-center gap-2 px-3.5 py-1.5 sm:px-4 sm:py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-xs sm:text-sm shadow-md shadow-emerald-600/20 hover:shadow-emerald-600/30 transition-all active:scale-95"
>
<UploadCloud className="w-4 h-4" />
<span>Upload</span>
</button>
)}
{/* User Badge */}
{user && (
<div className="flex items-center gap-2 pl-2 border-l border-slate-200">
<div className="flex flex-col text-right hidden sm:block">
<div className="flex items-center justify-end gap-1.5">
<span className="text-xs font-bold text-slate-800">{user.fullName}</span>
</div>
<div className="flex items-center justify-end gap-1.5 text-[10px]">
{user.companyName && (
<span className="text-emerald-700 font-medium flex items-center gap-0.5">
<Building2 className="w-2.5 h-2.5" />
{user.companyName}
</span>
)}
<span className="font-mono uppercase font-bold text-slate-400">
{isSuperAdmin ? (
<span className="text-rose-600">SUPER ADMIN</span>
) : isAdmin ? (
<span className="text-amber-600">ADMIN</span>
) : (
user.role
)}
</span>
</div>
</div>
<div className="w-8 h-8 rounded-full bg-emerald-50 border border-emerald-200 flex items-center justify-center text-emerald-700 font-bold text-xs">
{user.fullName ? user.fullName[0].toUpperCase() : <User className="w-4 h-4" />}
</div>
<button
onClick={() => setIsPasswordModalOpen(true)}
title="Change My Password"
className="p-1.5 text-slate-400 hover:text-amber-600 hover:bg-slate-100 rounded-lg transition-colors"
>
<KeyRound className="w-4 h-4" />
</button>
<button
onClick={logout}
title="Log out"
className="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-slate-100 rounded-lg transition-colors"
>
<LogOut className="w-4 h-4" />
</button>
</div>
)}
</div>
</div>
{user && (
<ChangePasswordModal
isOpen={isPasswordModalOpen}
onClose={() => setIsPasswordModalOpen(false)}
username={user.username}
/>
)}
</header>
);
};

View File

@@ -0,0 +1,175 @@
'use client';
import React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { formatBytes } from '@/lib/utils';
import {
LayoutDashboard,
FolderOpen,
Share2,
Users,
Files,
KeyRound,
PieChart,
History,
HardDrive,
Building2,
Smartphone,
} from 'lucide-react';
interface SidebarProps {
isOpen?: boolean;
onClose?: () => void;
}
export const Sidebar: React.FC<SidebarProps> = ({ isOpen, onClose }) => {
const pathname = usePathname();
const { user, isAdmin, isSuperAdmin, canViewOtherUsers } = useAuth();
const quota = user ? Number(user.storageQuotaBytes) : 0;
const used = user ? Number(user.storageUsedBytes) : 0;
const percent = quota > 0 ? Math.min(Math.round((used / quota) * 100), 100) : 0;
const mainLinks = [
{ label: 'Dashboard', href: '/dashboard', icon: LayoutDashboard },
{ label: 'File Explorer', href: '/files', icon: FolderOpen },
{ label: 'Shared With Me', href: '/shared', icon: Share2 },
];
const adminLinks = [
{ label: 'User Directory', href: '/admin/users', icon: Users },
{ label: 'Company Files', href: '/admin/files', icon: Files },
{ label: 'Access Permissions', href: '/admin/permissions', icon: KeyRound },
{ label: 'Storage Overview', href: '/admin/storage', icon: PieChart },
{ label: 'Security Audit Logs', href: '/admin/audit', icon: History },
{ label: 'Android App API', href: '/admin/android-api', icon: Smartphone },
];
return (
<>
{/* Mobile backdrop */}
{isOpen && (
<div
onClick={onClose}
className="fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-sm lg:hidden"
/>
)}
<aside
className={`fixed top-16 bottom-0 left-0 z-50 w-64 bg-white border-r border-slate-200/80 flex flex-col justify-between p-4 transition-transform duration-200 lg:translate-x-0 ${
isOpen ? 'translate-x-0' : '-translate-x-full'
}`}
>
<div className="space-y-6">
{/* Main User Navigation */}
<div className="space-y-1">
<span className="px-3 text-[11px] font-bold uppercase tracking-wider text-slate-400">
Workspace
</span>
<div className="mt-2 space-y-1">
{mainLinks.map((item) => {
const isActive = pathname === item.href;
const Icon = item.icon;
return (
<Link
key={item.href}
href={item.href}
onClick={onClose}
className={`flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-sm font-medium transition-all ${
isActive
? 'bg-emerald-50 text-emerald-800 font-semibold border border-emerald-200/70 shadow-sm'
: 'text-slate-600 hover:text-slate-900 hover:bg-slate-50'
}`}
>
<Icon className={`w-4 h-4 ${isActive ? 'text-emerald-600' : 'text-slate-400'}`} />
<span>{item.label}</span>
</Link>
);
})}
</div>
</div>
{/* Administrator Navigation */}
{isAdmin && canViewOtherUsers && (
<div className="space-y-1 pt-4 border-t border-slate-100">
<div className="flex items-center justify-between px-3">
<span className="text-[11px] font-bold uppercase tracking-wider text-slate-400">
Administration
</span>
<span className="text-[9px] px-1.5 py-0.5 rounded-full bg-emerald-100 text-emerald-800 font-bold font-mono">
{isSuperAdmin ? 'SUPER ADMIN' : 'ADMIN'}
</span>
</div>
<div className="mt-2 space-y-1">
{adminLinks.map((item) => {
const isActive = pathname === item.href;
const Icon = item.icon;
return (
<Link
key={item.href}
href={item.href}
onClick={onClose}
className={`flex items-center gap-3 px-3.5 py-2.5 rounded-xl text-sm font-medium transition-all ${
isActive
? 'bg-emerald-50 text-emerald-800 font-semibold border border-emerald-200/70 shadow-sm'
: 'text-slate-600 hover:text-slate-900 hover:bg-slate-50'
}`}
>
<Icon className={`w-4 h-4 ${isActive ? 'text-emerald-600' : 'text-slate-400'}`} />
<span>{item.label}</span>
</Link>
);
})}
</div>
</div>
)}
</div>
{/* Bottom Section: Storage Quota & Ecohub Branding */}
<div className="space-y-3">
{user && (
<div className="p-3.5 rounded-2xl bg-slate-50 border border-slate-200/80 space-y-2">
<div className="flex items-center justify-between text-xs">
<span className="flex items-center gap-1.5 font-semibold text-slate-700">
<HardDrive className="w-3.5 h-3.5 text-emerald-600" />
Storage Space
</span>
<span className="text-[11px] font-mono font-bold text-slate-500">{percent}%</span>
</div>
<div className="w-full h-2 bg-slate-200 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all duration-300 ${
percent > 90
? 'bg-rose-500'
: percent > 75
? 'bg-amber-500'
: 'bg-emerald-600'
}`}
style={{ width: `${percent}%` }}
/>
</div>
<div className="flex items-center justify-between text-[11px] text-slate-500 font-medium">
<span>{formatBytes(used)} used</span>
<span>{formatBytes(quota)} total</span>
</div>
</div>
)}
{/* Ecohub subtle watermark footer */}
<div className="flex items-center justify-between px-2 pt-1 border-t border-slate-100 text-[10px] text-slate-400">
<div className="flex items-center gap-1.5">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/logo.png" alt="Ecohub" className="w-3.5 h-3.5 object-contain opacity-70" />
<span className="font-bold text-slate-600">Ecohub Cloud</span>
</div>
<span>v2.4</span>
</div>
</div>
</aside>
</>
);
};

View File

@@ -0,0 +1,242 @@
'use client';
import React, { useState, useRef } from 'react';
import { api } from '@/lib/api-client';
import { formatBytes } from '@/lib/utils';
import {
X,
UploadCloud,
File,
CheckCircle,
AlertCircle,
RefreshCw,
} from 'lucide-react';
interface UploadItem {
id: string;
file: File;
progress: number;
status: 'PENDING' | 'UPLOADING' | 'COMPLETED' | 'FAILED';
errorMessage?: string;
}
interface FileUploaderModalProps {
isOpen: boolean;
onClose: () => void;
currentFolderId?: string;
onUploadComplete?: () => void;
}
export const FileUploaderModal: React.FC<FileUploaderModalProps> = ({
isOpen,
onClose,
currentFolderId,
onUploadComplete,
}) => {
const [items, setItems] = useState<UploadItem[]>([]);
const [isDragging, setIsDragging] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
if (!isOpen) return null;
const handleFilesSelected = (files: FileList | null) => {
if (!files) return;
const newItems: UploadItem[] = Array.from(files).map((file) => ({
id: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
file,
progress: 0,
status: 'PENDING',
}));
setItems((prev) => [...prev, ...newItems]);
// Start uploading newly added files
newItems.forEach((item) => startUpload(item));
};
const startUpload = async (item: UploadItem) => {
setItems((prev) =>
prev.map((i) => (i.id === item.id ? { ...i, status: 'UPLOADING', progress: 0 } : i)),
);
const formData = new FormData();
formData.append('file', item.file);
if (currentFolderId && currentFolderId !== 'root') {
formData.append('folderId', currentFolderId);
}
try {
await api.uploadWithProgress('/files/direct-upload', formData, (percent) => {
setItems((prev) =>
prev.map((i) => (i.id === item.id ? { ...i, progress: percent } : i)),
);
});
setItems((prev) =>
prev.map((i) => (i.id === item.id ? { ...i, status: 'COMPLETED', progress: 100 } : i)),
);
if (onUploadComplete) {
onUploadComplete();
}
} catch (err: any) {
setItems((prev) =>
prev.map((i) =>
i.id === item.id
? { ...i, status: 'FAILED', errorMessage: err.message || 'Upload failed' }
: i,
),
);
}
};
const removeItem = (id: string) => {
setItems((prev) => prev.filter((i) => i.id !== id));
};
const onDragOver = (e: React.DragEvent) => {
e.preventDefault();
setIsDragging(true);
};
const onDragLeave = () => {
setIsDragging(false);
};
const onDrop = (e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
handleFilesSelected(e.dataTransfer.files);
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
<div className="w-full max-w-xl bg-white border border-slate-200 rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-200">
<div>
<h3 className="text-base font-semibold text-slate-900">Upload Files & Videos</h3>
<p className="text-xs text-slate-500">
Drag & drop files or browse your device (Adaptive HLS & watermarking enabled)
</p>
</div>
<button
onClick={onClose}
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Drag & Drop Zone */}
<div className="p-6 overflow-y-auto space-y-4">
<div
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onClick={() => fileInputRef.current?.click()}
className={`border-2 border-dashed rounded-2xl p-8 flex flex-col items-center justify-center cursor-pointer transition-colors ${
isDragging
? 'border-emerald-600 bg-emerald-50'
: 'border-slate-300 hover:border-emerald-500 bg-slate-50'
}`}
>
<input
ref={fileInputRef}
type="file"
multiple
className="hidden"
onChange={(e) => handleFilesSelected(e.target.files)}
/>
<div className="w-12 h-12 rounded-2xl bg-emerald-100 text-emerald-600 flex items-center justify-center mb-3">
<UploadCloud className="w-6 h-6" />
</div>
<p className="text-sm font-medium text-slate-900">
Click to browse or drag and drop files here
</p>
<p className="text-xs text-slate-500 mt-1">
Supports MP4, WebM, MOV, PNG, JPG, PDF, ZIP, and other documents
</p>
</div>
{/* Upload Queue List */}
{items.length > 0 && (
<div className="space-y-2 mt-4">
<span className="text-xs font-semibold text-slate-600 uppercase tracking-wider">
Upload Queue ({items.length})
</span>
<div className="space-y-2 max-h-48 overflow-y-auto pr-1">
{items.map((item) => (
<div
key={item.id}
className="p-3 rounded-xl bg-slate-50 border border-slate-200 flex items-center justify-between gap-3"
>
<div className="flex items-center gap-3 min-w-0 flex-1">
<File className="w-5 h-5 text-emerald-600 flex-shrink-0" />
<div className="min-w-0 flex-1">
<p className="text-xs font-medium text-slate-800 truncate">
{item.file.name}
</p>
<p className="text-[10px] text-slate-500">{formatBytes(item.file.size)}</p>
{/* Progress bar */}
{item.status === 'UPLOADING' && (
<div className="w-full h-1.5 bg-slate-200 rounded-full mt-1.5 overflow-hidden">
<div
className="h-full bg-emerald-600 transition-all duration-150"
style={{ width: `${item.progress}%` }}
/>
</div>
)}
{item.status === 'FAILED' && (
<p className="text-[10px] text-rose-600 mt-0.5 truncate">
{item.errorMessage}
</p>
)}
</div>
</div>
<div className="flex items-center gap-2">
{item.status === 'UPLOADING' && (
<span className="text-xs font-mono text-emerald-600">{item.progress}%</span>
)}
{item.status === 'COMPLETED' && (
<CheckCircle className="w-5 h-5 text-emerald-600" />
)}
{item.status === 'FAILED' && (
<button
onClick={() => startUpload(item)}
title="Retry"
className="p-1 text-slate-400 hover:text-emerald-600"
>
<RefreshCw className="w-4 h-4" />
</button>
)}
<button
onClick={() => removeItem(item.id)}
className="p-1 text-slate-400 hover:text-slate-600"
>
<X className="w-4 h-4" />
</button>
</div>
</div>
))}
</div>
</div>
)}
</div>
{/* Footer */}
<div className="px-6 py-3.5 bg-slate-50 border-t border-slate-200 flex justify-end">
<button
onClick={onClose}
className="px-4 py-2 rounded-xl bg-slate-200 hover:bg-slate-300 text-slate-700 text-xs font-medium transition-colors"
>
Close
</button>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,337 @@
'use client';
import React, { useEffect, useRef, useState } from 'react';
import Hls from 'hls.js';
import { api } from '@/lib/api-client';
import { formatDuration } from '@/lib/utils';
import {
Play,
Pause,
Volume2,
VolumeX,
Maximize,
Minimize,
RotateCcw,
Settings,
Loader2,
AlertTriangle,
} from 'lucide-react';
import { EcohubWatermark } from '@/components/common/EcohubWatermark';
interface HlsVideoPlayerProps {
fileId: string;
hasHlsStream?: boolean;
title?: string;
durationSeconds?: number | null;
width?: number | null;
height?: number | null;
videoCodec?: string | null;
}
export const HlsVideoPlayer: React.FC<HlsVideoPlayerProps> = ({
fileId,
hasHlsStream,
title,
durationSeconds,
width,
height,
videoCodec,
}) => {
const videoRef = useRef<HTMLVideoElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(durationSeconds || 0);
const [volume, setVolume] = useState(1);
const [isMuted, setIsMuted] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const [playbackRate, setPlaybackRate] = useState(1);
const [isLoading, setIsLoading] = useState(true);
const [hasError, setHasError] = useState(false);
const [showControls, setShowControls] = useState(true);
const [showSpeedMenu, setShowSpeedMenu] = useState(false);
const controlsTimeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
const video = videoRef.current;
if (!video) return;
let hls: Hls | null = null;
const hlsUrl = api.getHlsStreamUrl(fileId);
const directUrl = api.getPlaybackUrl(fileId);
setIsLoading(true);
setHasError(false);
if (hasHlsStream && Hls.isSupported()) {
hls = new Hls({
xhrSetup: (xhr) => {
xhr.withCredentials = true;
},
});
hls.loadSource(hlsUrl);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
setIsLoading(false);
});
hls.on(Hls.Events.ERROR, (event, data) => {
if (data.fatal) {
console.warn('Fatal HLS error, falling back to direct video URL', data);
hls?.destroy();
video.src = directUrl;
}
});
} else {
// Native MP4 / WebM / iOS native HLS
video.src = directUrl;
}
const onTimeUpdate = () => setCurrentTime(video.currentTime);
const onLoadedMetadata = () => {
setDuration(video.duration || durationSeconds || 0);
setIsLoading(false);
};
const onWaiting = () => setIsLoading(true);
const onPlaying = () => {
setIsLoading(false);
setIsPlaying(true);
};
const onPause = () => setIsPlaying(false);
const onError = () => {
setIsLoading(false);
setHasError(true);
};
video.addEventListener('timeupdate', onTimeUpdate);
video.addEventListener('loadedmetadata', onLoadedMetadata);
video.addEventListener('waiting', onWaiting);
video.addEventListener('playing', onPlaying);
video.addEventListener('pause', onPause);
video.addEventListener('error', onError);
return () => {
if (hls) hls.destroy();
video.removeEventListener('timeupdate', onTimeUpdate);
video.removeEventListener('loadedmetadata', onLoadedMetadata);
video.removeEventListener('waiting', onWaiting);
video.removeEventListener('playing', onPlaying);
video.removeEventListener('pause', onPause);
video.removeEventListener('error', onError);
};
}, [fileId, hasHlsStream, durationSeconds]);
const togglePlay = () => {
const video = videoRef.current;
if (!video) return;
if (isPlaying) {
video.pause();
} else {
video.play().catch(() => setHasError(true));
}
};
const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
const video = videoRef.current;
if (!video) return;
const targetTime = Number(e.target.value);
video.currentTime = targetTime;
setCurrentTime(targetTime);
};
const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const video = videoRef.current;
if (!video) return;
const val = Number(e.target.value);
video.volume = val;
setVolume(val);
setIsMuted(val === 0);
};
const toggleMute = () => {
const video = videoRef.current;
if (!video) return;
if (isMuted) {
video.muted = false;
video.volume = volume || 0.5;
setIsMuted(false);
} else {
video.muted = true;
setIsMuted(true);
}
};
const toggleFullscreen = () => {
const container = containerRef.current;
if (!container) return;
if (!document.fullscreenElement) {
container.requestFullscreen().then(() => setIsFullscreen(true)).catch(() => {});
} else {
document.exitFullscreen().then(() => setIsFullscreen(false)).catch(() => {});
}
};
const handleSpeedSelect = (speed: number) => {
const video = videoRef.current;
if (!video) return;
video.playbackRate = speed;
setPlaybackRate(speed);
setShowSpeedMenu(false);
};
const handleMouseMove = () => {
setShowControls(true);
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current);
controlsTimeoutRef.current = setTimeout(() => {
if (isPlaying) setShowControls(false);
}, 2500);
};
return (
<div
ref={containerRef}
onMouseMove={handleMouseMove}
className="relative w-full aspect-video bg-black rounded-2xl overflow-hidden shadow-2xl group select-none border border-slate-800"
>
{/* Video Element */}
<video
ref={videoRef}
onClick={togglePlay}
playsInline
className="w-full h-full object-contain cursor-pointer"
/>
{/* Loading Overlay */}
{isLoading && !hasError && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 backdrop-blur-sm pointer-events-none">
<Loader2 className="w-10 h-10 text-indigo-400 animate-spin" />
</div>
)}
{/* Error Overlay */}
{hasError && (
<div className="absolute inset-0 flex flex-col items-center justify-center bg-slate-950/90 p-6 text-center">
<AlertTriangle className="w-12 h-12 text-rose-500 mb-2" />
<h4 className="text-base font-semibold text-slate-100">Playback Failed</h4>
<p className="text-xs text-slate-400 mt-1 max-w-sm">
Could not stream or decode this video format. Make sure you have authorized PLAY permissions.
</p>
</div>
)}
{/* Ecohub Watermark (Top left) */}
<EcohubWatermark variant="player" className="absolute top-4 left-4" />
{/* Resolution & Codec Badge (Top right) */}
<div className="absolute top-4 right-4 flex items-center gap-2 pointer-events-none">
{width && height && (
<span className="px-2.5 py-1 rounded-md bg-black/60 backdrop-blur-md border border-white/10 text-[11px] font-mono text-slate-200">
{width}x{height}
</span>
)}
{hasHlsStream && (
<span className="px-2 py-1 rounded-md bg-indigo-500/80 text-[10px] font-bold text-white uppercase tracking-wider">
HLS
</span>
)}
</div>
{/* Controls Bar */}
<div
className={`absolute bottom-0 inset-x-0 p-4 bg-gradient-to-t from-black/90 via-black/50 to-transparent transition-opacity duration-300 ${
showControls || !isPlaying ? 'opacity-100' : 'opacity-0 pointer-events-none'
}`}
>
{/* Timeline Scrubber */}
<div className="relative mb-3 flex items-center group/scrub">
<input
type="range"
min={0}
max={duration || 100}
step={0.1}
value={currentTime}
onChange={handleSeek}
className="w-full h-1.5 bg-slate-700/60 rounded-lg appearance-none cursor-pointer accent-indigo-500 hover:h-2.5 transition-all"
/>
</div>
<div className="flex items-center justify-between text-slate-200">
{/* Left: Play/Pause, Volume, Time */}
<div className="flex items-center gap-3">
<button
onClick={togglePlay}
className="p-2 rounded-xl bg-white/10 hover:bg-white/20 text-white transition-colors"
>
{isPlaying ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5 fill-current" />}
</button>
<div className="flex items-center gap-1.5 group/vol">
<button onClick={toggleMute} className="p-1.5 text-slate-300 hover:text-white">
{isMuted || volume === 0 ? (
<VolumeX className="w-5 h-5 text-rose-400" />
) : (
<Volume2 className="w-5 h-5" />
)}
</button>
<input
type="range"
min={0}
max={1}
step={0.05}
value={isMuted ? 0 : volume}
onChange={handleVolumeChange}
className="w-16 h-1 bg-slate-700 rounded appearance-none cursor-pointer accent-indigo-400"
/>
</div>
<span className="text-xs font-mono text-slate-300">
{formatDuration(currentTime)} / {formatDuration(duration)}
</span>
</div>
{/* Right: Playback Speed, Fullscreen */}
<div className="flex items-center gap-2 relative">
{/* Speed Button & Menu */}
<div className="relative">
<button
onClick={() => setShowSpeedMenu(!showSpeedMenu)}
className="px-2 py-1 rounded-md text-xs font-medium text-slate-300 hover:text-white hover:bg-white/10 transition-colors"
>
{playbackRate}x
</button>
{showSpeedMenu && (
<div className="absolute bottom-8 right-0 bg-slate-900 border border-slate-700 rounded-xl py-1 shadow-xl z-20 w-24">
{[0.5, 0.75, 1, 1.25, 1.5, 2].map((s) => (
<button
key={s}
onClick={() => handleSpeedSelect(s)}
className={`w-full text-left px-3 py-1 text-xs hover:bg-indigo-600/30 ${
playbackRate === s ? 'text-indigo-400 font-bold' : 'text-slate-300'
}`}
>
{s}x
</button>
))}
</div>
)}
</div>
{/* Fullscreen Button */}
<button
onClick={toggleFullscreen}
className="p-1.5 text-slate-300 hover:text-white transition-colors"
>
{isFullscreen ? <Minimize className="w-5 h-5" /> : <Maximize className="w-5 h-5" />}
</button>
</div>
</div>
</div>
</div>
);
};

View File

@@ -0,0 +1,111 @@
'use client';
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { api } from '@/lib/api-client';
import { UserRole, UserStatus } from '@fileshare/shared';
export interface UserProfile {
id: string;
email: string;
username: string;
fullName: string;
companyName?: string;
role: UserRole;
status: UserStatus;
storageQuotaBytes: string;
storageUsedBytes: string;
canCreateShareLinks?: boolean;
canDeleteFiles?: boolean;
canViewOtherUsers?: boolean;
}
interface AuthContextType {
user: UserProfile | null;
isLoading: boolean;
login: (identifier: string, password: string) => Promise<void>;
register: (data: { email: string; username: string; fullName: string; password: string; companyName?: string }) => Promise<void>;
logout: () => Promise<void>;
refreshProfile: () => Promise<void>;
isAdmin: boolean;
isSuperAdmin: boolean;
canViewOtherUsers: boolean;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<UserProfile | null>(null);
const [isLoading, setIsLoading] = useState(true);
const refreshProfile = useCallback(async () => {
try {
const profile = await api.get<UserProfile>('/auth/me');
setUser(profile);
} catch {
setUser(null);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
refreshProfile();
}, [refreshProfile]);
const login = async (identifier: string, password: string) => {
const res: any = await api.post('/auth/login', { identifier, password });
if (res.accessToken) {
api.setToken(res.accessToken);
}
setUser(res.user);
};
const register = async (data: { email: string; username: string; fullName: string; password: string; companyName?: string }) => {
const res: any = await api.post('/auth/register', data);
if (res.accessToken) {
api.setToken(res.accessToken);
setUser(res.user);
}
return res;
};
const logout = async () => {
try {
await api.post('/auth/logout', {});
} finally {
api.setToken(null);
setUser(null);
window.location.href = '/login';
}
};
const isSuperAdmin = user?.role === UserRole.SUPER_ADMIN;
const isAdmin = user?.role === UserRole.ADMIN || isSuperAdmin;
const canViewOtherUsers = isAdmin || !!user?.canViewOtherUsers;
return (
<AuthContext.Provider
value={{
user,
isLoading,
login,
register,
logout,
refreshProfile,
isAdmin,
isSuperAdmin,
canViewOtherUsers,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}

View File

@@ -0,0 +1,303 @@
export function getApiBaseUrl(): string {
if (process.env.NEXT_PUBLIC_API_URL) {
return process.env.NEXT_PUBLIC_API_URL.replace(/\/+$/, '');
}
if (typeof window !== 'undefined') {
const hostname = window.location.hostname;
const isLocalhost = hostname === 'localhost' || hostname === '127.0.0.1';
// Only connect directly to port 4000 if running locally on localhost/127.0.0.1
if (isLocalhost && window.location.port === '3000') {
return `${window.location.protocol}//${hostname}:4000/api/v1`;
}
// For all domain names (e.g. nas.ecohub.cc), external LAN/WAN, or reverse proxy/tunnel,
// always use same-origin /api/v1 (which Next.js proxies to backend via rewrites).
return `${window.location.origin}/api/v1`;
}
return process.env.BACKEND_INTERNAL_URL
? `${process.env.BACKEND_INTERNAL_URL.replace(/\/+$/, '')}/api/v1`
: 'http://127.0.0.1:4000/api/v1';
}
class ApiClient {
private token: string | null = null;
getBaseUrl(): string {
return getApiBaseUrl();
}
setToken(token: string | null) {
this.token = token;
if (typeof window !== 'undefined') {
if (token) {
localStorage.setItem('fileshare_token', token);
} else {
localStorage.removeItem('fileshare_token');
}
}
}
getToken(): string | null {
if (this.token) return this.token;
if (typeof window !== 'undefined') {
this.token = localStorage.getItem('fileshare_token');
}
return this.token;
}
private async request<T>(
endpoint: string,
options: RequestInit = {},
): Promise<T> {
const baseUrl = this.getBaseUrl();
const url = endpoint.startsWith('http') ? endpoint : `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
const token = this.getToken();
const headers: Record<string, string> = {
...(options.headers as Record<string, string>),
};
if (token && !headers['Authorization']) {
headers['Authorization'] = `Bearer ${token}`;
}
if (!(options.body instanceof FormData) && !headers['Content-Type']) {
headers['Content-Type'] = 'application/json';
}
let res: Response;
try {
res = await fetch(url, {
...options,
headers,
credentials: 'include',
});
} catch (fetchErr: any) {
// If direct request failed (e.g. port 4000 connection refused or not exposed on domain/NAS),
// automatically fall back to same-origin /api/v1 (Next.js proxy)
if (
typeof window !== 'undefined' &&
!endpoint.startsWith('http') &&
url !== `${window.location.origin}/api/v1${endpoint.startsWith('/') ? '' : '/'}${endpoint}`
) {
const fallbackUrl = `${window.location.origin}/api/v1${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
res = await fetch(fallbackUrl, {
...options,
headers,
credentials: 'include',
});
} else {
throw fetchErr;
}
}
if (res.status === 401 && !endpoint.includes('/auth/login') && !endpoint.includes('/auth/refresh')) {
// Attempt token refresh
try {
const refreshRes = await fetch(`${baseUrl}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
});
if (refreshRes.ok) {
const data = await refreshRes.json();
this.setToken(data.accessToken);
headers['Authorization'] = `Bearer ${data.accessToken}`;
const retryRes = await fetch(url, { ...options, headers, credentials: 'include' });
if (!retryRes.ok) {
const errData = await retryRes.json().catch(() => ({}));
throw new Error(errData.message || 'Request failed after token refresh');
}
return retryRes.json();
}
} catch {
this.setToken(null);
if (typeof window !== 'undefined') {
window.location.href = '/login';
}
}
}
if (!res.ok) {
const errData = await res.json().catch(() => ({ message: res.statusText }));
throw new Error(errData.message || `Request failed with status ${res.status}`);
}
// Handle empty or void responses
const contentType = res.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return res.json();
}
return res.text() as unknown as T;
}
async get<T>(endpoint: string, headers?: Record<string, string>): Promise<T> {
return this.request<T>(endpoint, { method: 'GET', headers });
}
async post<T>(endpoint: string, body?: any, headers?: Record<string, string>): Promise<T> {
const isFormData = body instanceof FormData;
return this.request<T>(endpoint, {
method: 'POST',
headers,
body: isFormData ? body : JSON.stringify(body),
});
}
async patch<T>(endpoint: string, body?: any, headers?: Record<string, string>): Promise<T> {
return this.request<T>(endpoint, {
method: 'PATCH',
headers,
body: JSON.stringify(body),
});
}
async delete<T>(endpoint: string, headers?: Record<string, string>): Promise<T> {
return this.request<T>(endpoint, { method: 'DELETE', headers });
}
/**
* Direct Upload with XMLHttpRequest for real progress tracking
*/
uploadWithProgress(
endpoint: string,
formData: FormData,
onProgress: (percent: number) => void,
): Promise<any> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const baseUrl = this.getBaseUrl();
const url = `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;
xhr.open('POST', url, true);
xhr.withCredentials = true;
const token = this.getToken();
if (token) {
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
}
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
onProgress(percent);
}
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
resolve(JSON.parse(xhr.responseText));
} catch {
resolve(xhr.responseText);
}
} else {
try {
const err = JSON.parse(xhr.responseText);
reject(new Error(err.message || 'Upload failed'));
} catch {
reject(new Error(`Upload failed with status ${xhr.status}`));
}
}
};
xhr.onerror = () => reject(new Error('Network error during file upload'));
xhr.send(formData);
});
}
getDownloadUrl(fileId: string): string {
const token = this.getToken();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/files/${fileId}/download${token ? `?token=${encodeURIComponent(token)}` : ''}`;
}
getPreviewUrl(fileId: string): string {
const token = this.getToken();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/files/${fileId}/preview${token ? `?token=${encodeURIComponent(token)}` : ''}`;
}
getThumbnailUrl(fileId: string): string {
const token = this.getToken();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/files/${fileId}/thumbnail${token ? `?token=${encodeURIComponent(token)}` : ''}`;
}
getPlaybackUrl(fileId: string): string {
const token = this.getToken();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/files/${fileId}/playback${token ? `?token=${encodeURIComponent(token)}` : ''}`;
}
getHlsStreamUrl(fileId: string): string {
const token = this.getToken();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/files/${fileId}/stream/master.m3u8${token ? `?token=${encodeURIComponent(token)}` : ''}`;
}
getPublicShareResource(token: string, password?: string, subfolderId?: string): Promise<any> {
const params = new URLSearchParams();
if (password) params.set('password', password);
if (subfolderId) params.set('subfolderId', subfolderId);
const qs = params.toString();
return this.get(`/share-links/public/${token}${qs ? `?${qs}` : ''}`);
}
getPublicSharePlaybackUrl(token: string, password?: string, fileId?: string): string {
const params = new URLSearchParams();
if (password) params.set('password', password);
if (fileId) params.set('fileId', fileId);
const qs = params.toString();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/share-links/public/${token}/playback${qs ? `?${qs}` : ''}`;
}
getPublicShareDownloadUrl(token: string, password?: string, fileId?: string): string {
const params = new URLSearchParams();
if (password) params.set('password', password);
if (fileId) params.set('fileId', fileId);
const qs = params.toString();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/share-links/public/${token}/download${qs ? `?${qs}` : ''}`;
}
getPublicShareThumbnailUrl(token: string, password?: string, fileId?: string): string {
const params = new URLSearchParams();
if (password) params.set('password', password);
if (fileId) params.set('fileId', fileId);
const qs = params.toString();
const baseUrl = this.getBaseUrl();
return `${baseUrl}/share-links/public/${token}/thumbnail${qs ? `?${qs}` : ''}`;
}
getCompanyExplorer(companyName?: string, folderId?: string): Promise<any> {
const params = new URLSearchParams();
if (companyName) params.set('companyName', companyName);
if (folderId) params.set('folderId', folderId);
const qs = params.toString();
return this.get(`/folders/explorer${qs ? `?${qs}` : ''}`);
}
deleteUser(id: string): Promise<any> {
return this.delete(`/admin/users/${id}`);
}
getCompanies(): Promise<string[]> {
return this.get('/admin/companies');
}
createCompany(name: string): Promise<string[]> {
return this.post('/admin/companies', { name });
}
deleteCompany(companyName: string): Promise<any> {
return this.delete(`/admin/companies/${encodeURIComponent(companyName)}`);
}
updateCompanyName(companyName: string, newCompanyName: string): Promise<any> {
return this.patch(`/admin/companies/${encodeURIComponent(companyName)}`, { newCompanyName });
}
}
export const api = new ApiClient();

View File

@@ -0,0 +1,92 @@
export function cn(...inputs: any[]): string {
return inputs
.flat(Infinity)
.filter(Boolean)
.join(' ');
}
export function formatBytes(bytes: number | string, decimals = 2): string {
const b = typeof bytes === 'string' ? Number(bytes) : bytes;
if (!b || b === 0) return '0 B';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(b) / Math.log(k));
return `${parseFloat((b / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}
export function formatDuration(seconds?: number | null): string {
if (!seconds || seconds <= 0) return '0:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
}
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
export function formatDate(dateString: string): string {
if (!dateString) return '';
const d = new Date(dateString);
if (isNaN(d.getTime())) return '';
const day = d.getDate();
const month = MONTHS[d.getMonth()];
const year = d.getFullYear();
return `${month} ${day}, ${year}`;
}
/**
* Universal clipboard copy with fallback for non-secure HTTP contexts (LAN IP access)
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
if (!text) return false;
// 1. Try modern navigator.clipboard if available (secure context / localhost / HTTPS)
if (
typeof navigator !== 'undefined' &&
navigator.clipboard &&
typeof navigator.clipboard.writeText === 'function'
) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// Fall through to fallback
}
}
// 2. Fallback to hidden textarea with document.execCommand('copy')
if (typeof document !== 'undefined') {
try {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = '0';
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.style.opacity = '0';
textArea.setAttribute('readonly', '');
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
return successful;
} catch (err) {
console.warn('Fallback copy failed:', err);
return false;
}
}
return false;
}

View File

@@ -0,0 +1,53 @@
import type { Config } from "tailwindcss";
const config: Config = {
darkMode: ["class"],
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
card: {
DEFAULT: "var(--card)",
foreground: "var(--card-foreground)",
},
primary: {
DEFAULT: "var(--primary)",
foreground: "var(--primary-foreground)",
},
secondary: {
DEFAULT: "var(--secondary)",
foreground: "var(--secondary-foreground)",
},
muted: {
DEFAULT: "var(--muted)",
foreground: "var(--muted-foreground)",
},
accent: {
DEFAULT: "var(--accent)",
foreground: "var(--accent-foreground)",
},
destructive: {
DEFAULT: "var(--destructive)",
foreground: "var(--destructive-foreground)",
},
border: "var(--border)",
input: "var(--input)",
ring: "var(--ring)",
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
},
},
plugins: [],
};
export default config;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"],
"@fileshare/shared": ["../../packages/shared/src/index.ts"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}