1import { NextRequest, NextResponse } from 'next/server';
2import { getStoredAuth } from '@/lib/server/auth';
3import fs from 'fs/promises';
4import path from 'path';
7 * Department Hierarchy Configuration API
8 * Stores and retrieves the hierarchical relationship between departments
9 * This is frontend configuration - backend departments remain flat
12const CONFIG_DIR = path.join(process.cwd(), 'data', 'config');
13const HIERARCHY_FILE = path.join(CONFIG_DIR, 'department-hierarchy.json');
15interface DepartmentHierarchy {
16 [parentDeptId: number]: number[]; // Maps parent ID to array of valid child IDs
19// Ensure config directory exists
20async function ensureConfigDir() {
22 await fs.mkdir(CONFIG_DIR, { recursive: true });
24 console.error('Error creating config directory:', error);
28// GET - Retrieve department hierarchy configuration
29export async function GET(request: NextRequest) {
31 // Verify authentication
32 const authData = await getStoredAuth();
33 if (!authData || !authData.authenticated) {
34 return NextResponse.json(
35 { error: 'Authentication required' },
41 await ensureConfigDir();
42 const data = await fs.readFile(HIERARCHY_FILE, 'utf-8');
43 const hierarchy: DepartmentHierarchy = JSON.parse(data);
45 return NextResponse.json({
49 } catch (error: any) {
50 // File doesn't exist or is invalid - return empty hierarchy
51 if (error.code === 'ENOENT') {
52 return NextResponse.json({
61 console.error('Department hierarchy GET error:', error);
62 return NextResponse.json(
63 { error: 'Failed to retrieve department hierarchy' },
69// POST - Save department hierarchy configuration
70export async function POST(request: NextRequest) {
72 // Verify authentication
73 const authData = await getStoredAuth();
74 if (!authData || !authData.authenticated) {
75 return NextResponse.json(
76 { error: 'Authentication required' },
81 const body = await request.json();
82 const hierarchy: DepartmentHierarchy = body.hierarchy || {};
85 for (const [parentId, children] of Object.entries(hierarchy)) {
86 if (!Array.isArray(children)) {
87 return NextResponse.json(
88 { error: 'Invalid hierarchy structure - children must be arrays' },
95 await ensureConfigDir();
96 await fs.writeFile(HIERARCHY_FILE, JSON.stringify(hierarchy, null, 2), 'utf-8');
98 return NextResponse.json({
100 message: 'Department hierarchy saved successfully',
105 console.error('Department hierarchy POST error:', error);
106 return NextResponse.json(
107 { error: 'Failed to save department hierarchy' },