Files
Ho Ngoc Hai fba536406d feat(osm): foundation — admin boundaries, POI catalog, sync orchestrator
This is the Phase 0 + Phase 1 + Phase 4 foundation of the full OSM
integration plan. It backfills three things the rest of the platform
has been faking with hardcoded tables, and gives admins one dashboard
for every OSM-sourced layer.

Phase 0 — Vietnam administrative boundaries
* New columns on vn_provinces / vn_districts / vn_wards: PostGIS
  geometry (MultiPolygon), centroid (Point), areaKm2, osmId, population,
  lastSyncedAt + GIST indexes on geometry/centroid.
* `scripts/sync-osm-admin-boundaries.ts` pulls
  `boundary=administrative + admin_level=4|6|8` from Overpass per chunk,
  filters to mainland VN via the existing country polygon, resolves the
  GSO code (or generates `OSM_<id>`), and upserts via raw SQL because
  Prisma can't manage PostGIS columns.
* `GeoLookupService` (shared module) replaces the old
  `nearestProvince()` heuristic — `lookup(lng,lat)` returns
  province/district/ward via `ST_Contains` on the GIST-indexed polygons.
* The KCN sync now resolves province/district from the polygon table
  and falls back to the centroid heuristic only when polygons aren't
  loaded yet.
* `scripts/backfill-admin-codes.ts` rewrites province/district/ward on
  IndustrialPark, ProjectDevelopment and Property using the new lookup.

Phase 1 — POI catalog (15 categories, schema only here)
* New `Poi` table with `PoiCategory` enum, OSM provenance columns,
  GIST index on `location`. New `TransportLine` for metro/highway
  multilinestrings.
* `scripts/sync-osm-poi.ts` queries Overpass per category × chunk,
  resolves province/district codes from the boundary polygons, upserts
  with `osmLocked` / `lockedFields` honour same as KCN.
* New NestJS `PoiModule` exposes:
    GET /poi/by-bbox    — GeoJSON for map overlays
    GET /poi/nearby     — sidebar "tiện ích xung quanh" (HMAC distance ranks)
    GET /poi/coverage   — admin per-category counts
* New web component `<NearbyPoiSidebar />` ready to drop into listing /
  project / KCN detail pages.

Phase 4 — Sync orchestrator + admin dashboard
* New `OsmSyncRun` audit table tracks every sync invocation
  (RUNNING / SUCCESS / PARTIAL / FAILED + row stats + error message).
* `OsmSyncService` spawns the right tsx script for any (layer, category,
  chunk) tuple, parses stats out of stdout, updates the run row.
* `OsmSyncCronService` schedules:
    Daily 02:00  → POI category rotation (1/day, 20-day cycle)
    Mon  02:30  → admin-boundaries provinces
    Wed  02:30  → admin-boundaries districts
    Sat  02:30  → admin-boundaries wards
    1st of month 03:00 → industrial-parks (per chunk)
  All gated by `OSM_SYNC_ENABLED=true`.
* New admin endpoints under `/admin/osm/*` (layers / coverage / runs /
  trigger), guarded by JWT + ADMIN role.
* New `/admin/osm` Next.js page: stat cards, coverage table with
  per-row "Sync now", recent runs list with auto-refresh every 15s.

Run on dev so far: 33 provinces + 1100+ districts (still finishing) +
305 hospitals POI imported.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 12:01:19 +07:00

165 lines
5.9 KiB
TypeScript

'use client';
import {
LayoutDashboard,
Users,
ClipboardList,
ShieldCheck,
Building2,
Factory,
Globe,
LogOut,
Menu,
Sparkles,
X,
ScrollText,
} 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/audit-log' as const, label: 'Nhật ký kiểm toán', icon: ScrollText },
{ 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/industrial/osm-review' as const, label: 'Review OSM (KCN)', icon: Factory },
{ href: '/admin/osm' as const, label: 'OSM Sync Dashboard', icon: Globe },
{ 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>
);
}