Files
goodgo-platform/apps/web/app/[locale]/(admin)/layout.tsx
Ho Ngoc Hai 33a5ff407b
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 16s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 50s
Deploy / Build API Image (push) Failing after 25s
Deploy / Build Web Image (push) Failing after 11s
Deploy / Build AI Services Image (push) Failing after 10s
E2E Tests / Playwright E2E (push) Failing after 12s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 4s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m16s
Security Scanning / Trivy Scan — Web Image (push) Failing after 1m2s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 50s
Security Scanning / Trivy Filesystem Scan (push) Failing after 38s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 0s
Deploy / Rollback Production (push) Has been skipped
Deploy / Rollback Staging (push) Failing after 10m50s
feat(auth): add DEVELOPER + PARK_OPERATOR roles with owner scoping (B2B accounts)
Two new B2B roles for CĐT (project developers) and KCN operators, provisioned by
admin. Each account owns a subset of ProjectDevelopment / IndustrialPark records
and can CRUD them from the dashboard; admin retains full access.

Phase 1 — Schema
- Extend UserRole enum with DEVELOPER + PARK_OPERATOR (before ADMIN)
- ProjectDevelopment.ownerId FK (User, ON DELETE SET NULL) + index
- IndustrialPark.ownerId FK + index
- Migration 20260420030000

Phase 2a — Backend authorization
- CreateProjectCommand + CreateIndustrialParkCommand accept ownerId; controllers
  auto-set it to the caller's user id when role=DEVELOPER / PARK_OPERATOR
- Update + Delete commands gain (requesterUserId, requesterRole) and enforce
  ADMIN-or-owner via ForbiddenException; reassigning ownerId is admin-only
- Search params gain optional ownerId filter wired through Prisma repos
- New endpoints: GET /projects/mine/list, GET /industrial/parks/mine/list
- user-rate-limit guard: add DEVELOPER + PARK_OPERATOR entries (300/window)

Phase 2b — Admin provision
- ProvisionDeveloperCommand/Handler: create user (role=DEVELOPER), pre-validate
  target projects have no existing owner, batch-assign ownerId
- ProvisionParkOperatorCommand/Handler: same for PARK_OPERATOR + IndustrialPark
- POST /admin/accounts/developers, POST /admin/accounts/park-operators (admin-only)
- DTOs with phone/password/fullName/email + optional {project,park}Ids[]

Phase 2c — Project stats for developer dashboard
- GetProjectStatsQuery + handler: aggregates linkedListingCount, activeListingCount,
  totalInquiries, unreadInquiries, savedByUsers via Property → Listing → Inquiry chain
- GET /projects/:id/stats — admin sees all, DEVELOPER only their own (403 otherwise)

Phase 3 — Frontend
- Dashboard layout role-aware: DEVELOPER sees "Dự án của tôi" + CRM + Profile (hides
  listings/analytics/subscription); PARK_OPERATOR sees "KCN của tôi" equivalent
- /projects dashboard page switches to duAnApi.searchMine() when role=DEVELOPER
- /industrial-parks page switches to industrialApi.searchMine() when role=PARK_OPERATOR
- Admin nav gains "Tài khoản CĐT" + "Tài khoản KCN" entries
- New pages /admin/accounts/developers + /admin/accounts/park-operators with
  checkbox-based multi-select for linking entities
- adminApi.provisionDeveloper + provisionParkOperator + types
- duAnApi.searchMine + getStats; industrialApi.searchMine
- Login demo accounts list includes CĐT Vingroup + KCN VSIP

Phase 4 — Seed (prisma/seed-b2b-accounts.ts)
- DEVELOPER "CĐT Vingroup" (+84912000001) owns 4 projects
- DEVELOPER "CĐT Masterise Homes" (+84912000003) owns 2 projects
- PARK_OPERATOR "Vận hành KCN VSIP" (+84912000002) owns 2 seeded KCN
- Password Velik@2026 for all

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 22:12:16 +07:00

160 lines
5.6 KiB
TypeScript

'use client';
import {
LayoutDashboard,
Users,
ClipboardList,
ShieldCheck,
Building2,
Factory,
LogOut,
Menu,
Sparkles,
X,
} from 'lucide-react';
import { usePathname, useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { LanguageSwitcher } from '@/components/ui/language-switcher';
import { Link } from '@/i18n/navigation';
import { useAuthStore } from '@/lib/auth-store';
import { cn } from '@/lib/utils';
export default function AdminLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const { user, isAuthenticated, isInitialized, logout } = useAuthStore();
const [sidebarOpen, setSidebarOpen] = useState(false);
const t = useTranslations();
const adminNavItems = [
{ href: '/admin' as const, label: t('adminNav.dashboard'), icon: LayoutDashboard },
{ href: '/admin/users' as const, label: t('adminNav.users'), icon: Users },
{ href: '/admin/moderation' as const, label: t('adminNav.moderation'), icon: ClipboardList },
{ href: '/admin/kyc' as const, label: t('adminNav.kyc'), icon: ShieldCheck },
{ href: '/admin/accounts/developers' as const, label: 'Tài khoản CĐT', icon: Building2 },
{ href: '/admin/accounts/park-operators' as const, label: 'Tài khoản KCN', icon: Factory },
{ href: '/admin/settings/ai' as const, label: t('adminNav.aiSettings'), icon: Sparkles },
];
useEffect(() => {
// Once the auth store finished its initial cookie→profile probe:
// - no session → push to /login (don't leave a spinner forever)
// - authenticated but not ADMIN → push to regular dashboard
if (!isInitialized) return;
if (!isAuthenticated) {
router.replace(`/login?next=${encodeURIComponent(pathname)}`);
return;
}
if (user && user.role !== 'ADMIN') {
router.replace('/dashboard');
}
}, [isInitialized, isAuthenticated, user, router, pathname]);
if (!isInitialized || !user) {
return (
<div className="flex min-h-screen items-center justify-center" role="status">
<div className="text-muted-foreground">{t('common.loading')}</div>
</div>
);
}
if (user.role !== 'ADMIN') {
return null;
}
return (
<div className="flex min-h-screen bg-background">
{/* Mobile overlay */}
{sidebarOpen && (
<div
className="fixed inset-0 z-40 bg-black/50 lg:hidden"
onClick={() => setSidebarOpen(false)}
aria-hidden="true"
/>
)}
{/* Sidebar */}
<aside
role="navigation"
aria-label={t('nav.adminNav')}
className={cn(
'fixed inset-y-0 left-0 z-50 w-64 border-r bg-card transition-transform lg:static lg:translate-x-0',
sidebarOpen ? 'translate-x-0' : '-translate-x-full',
)}
>
<div className="flex h-14 items-center border-b px-4">
<Link href="/admin" className="flex items-center gap-2">
<span className="text-lg font-bold text-primary">{t('common.goodgo')}</span>
<span className="rounded bg-primary/10 px-1.5 py-0.5 text-xs font-semibold text-primary">
{t('common.admin')}
</span>
</Link>
<button
aria-label={t('adminNav.closeMenu')}
className="ml-auto lg:hidden"
onClick={() => setSidebarOpen(false)}
>
<X className="h-5 w-5" />
</button>
</div>
<nav aria-label={t('nav.adminNav')} className="flex flex-col gap-1 p-3">
{adminNavItems.map((item) => {
const Icon = item.icon;
const isActive =
item.href === '/admin'
? pathname === '/admin' || pathname.match(/^\/(vi|en)\/admin$/)
: pathname.includes(item.href);
return (
<Link
key={item.href}
href={item.href}
onClick={() => setSidebarOpen(false)}
className={cn(
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
isActive
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
)}
>
<Icon className="h-4 w-4" aria-hidden="true" />
{item.label}
</Link>
);
})}
</nav>
<div className="mt-auto border-t p-3">
<div className="mb-2 flex items-center justify-between px-3">
<span className="text-xs text-muted-foreground truncate">{user.fullName}</span>
<LanguageSwitcher />
</div>
<Button
variant="ghost"
size="sm"
className="w-full justify-start gap-2"
onClick={() => logout()}
>
<LogOut className="h-4 w-4" aria-hidden="true" />
{t('common.logout')}
</Button>
</div>
</aside>
{/* Main content */}
<div className="flex flex-1 flex-col">
<header className="sticky top-0 z-30 flex h-14 items-center border-b bg-background/95 px-4 backdrop-blur lg:hidden">
<button aria-label={t('adminNav.openMenu')} onClick={() => setSidebarOpen(true)}>
<Menu className="h-5 w-5" />
</button>
<span className="ml-3 text-sm font-semibold">{t('common.goodgo')} {t('common.admin')}</span>
</header>
<main id="main-content" role="main" className="flex-1 p-4 md:p-6">{children}</main>
</div>
</div>
);
}