first commit

This commit is contained in:
2025-11-24 16:30:37 +00:00
commit 843e93a274
114 changed files with 25585 additions and 0 deletions

View File

@@ -0,0 +1,129 @@
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { deviceDb } from "@/lib/db";
// GET /api/devices/[id] - Get single device
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
const device = deviceDb.findById(id);
if (!device) {
return NextResponse.json({ error: "Device not found" }, { status: 404 });
}
return NextResponse.json({
device: {
id: device.id,
name: device.name,
color: device.color,
isActive: device.isActive === 1,
createdAt: device.createdAt,
updatedAt: device.updatedAt,
description: device.description,
icon: device.icon,
}
});
} catch (error) {
console.error("Error fetching device:", error);
return NextResponse.json(
{ error: "Failed to fetch device" },
{ status: 500 }
);
}
}
// PATCH /api/devices/[id] - Update device (ADMIN only)
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Only ADMIN can update devices
if ((session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { id } = await params;
const device = deviceDb.findById(id);
if (!device) {
return NextResponse.json({ error: "Device not found" }, { status: 404 });
}
const body = await request.json();
const { name, color, description, icon } = body;
const updated = deviceDb.update(id, {
name,
color,
description,
icon,
});
if (!updated) {
return NextResponse.json({ error: "Failed to update device" }, { status: 500 });
}
return NextResponse.json({ device: updated });
} catch (error) {
console.error("Error updating device:", error);
return NextResponse.json(
{ error: "Failed to update device" },
{ status: 500 }
);
}
}
// DELETE /api/devices/[id] - Soft delete device (ADMIN only)
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Only ADMIN can delete devices
if ((session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { id } = await params;
const device = deviceDb.findById(id);
if (!device) {
return NextResponse.json({ error: "Device not found" }, { status: 404 });
}
const success = deviceDb.delete(id);
if (!success) {
return NextResponse.json({ error: "Failed to delete device" }, { status: 500 });
}
return NextResponse.json({ message: "Device deleted successfully" });
} catch (error) {
console.error("Error deleting device:", error);
return NextResponse.json(
{ error: "Failed to delete device" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,44 @@
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { deviceDb, userDb } from "@/lib/db";
// GET /api/devices/public - Authenticated endpoint for device names and colors
export async function GET() {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const userId = (session.user as any).id;
const role = (session.user as any).role;
const username = session.user.name || '';
// Get list of device IDs the user is allowed to access
const allowedDeviceIds = userDb.getAllowedDeviceIds(userId, role, username);
// Fetch all active devices
const allDevices = deviceDb.findAll();
// Filter to only devices the user can access
const userDevices = allDevices.filter(device =>
allowedDeviceIds.includes(device.id)
);
// Return only public information (id, name, color)
const publicDevices = userDevices.map((device) => ({
id: device.id,
name: device.name,
color: device.color,
}));
return NextResponse.json({ devices: publicDevices });
} catch (error) {
console.error("Error fetching public devices:", error);
return NextResponse.json(
{ error: "Failed to fetch devices" },
{ status: 500 }
);
}
}

120
app/api/devices/route.ts Normal file
View File

@@ -0,0 +1,120 @@
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { deviceDb, locationDb, userDb } from "@/lib/db";
// GET /api/devices - List all devices (from database)
export async function GET() {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Get devices from database (filtered by user ownership)
const userId = (session.user as any).id;
let targetUserId = userId;
// If user is a VIEWER with a parent, show parent's devices instead
const currentUser = userDb.findById(userId);
if (currentUser && currentUser.role === 'VIEWER' && currentUser.parent_user_id) {
targetUserId = currentUser.parent_user_id;
console.log(`[Devices] VIEWER ${currentUser.username} accessing parent's devices (parent_id: ${targetUserId})`);
}
const devices = deviceDb.findAll({ userId: targetUserId });
// Fetch location data from local SQLite cache (24h history)
const allLocations = locationDb.findMany({
user_id: 0, // MQTT devices only
timeRangeHours: 24, // Last 24 hours
limit: 10000,
});
// Merge devices with latest location data
const devicesWithLocation = devices.map((device) => {
// Find all locations for this device
const deviceLocations = allLocations.filter((loc) => loc.username === device.id);
// Get latest location (first one, already sorted by timestamp DESC)
const latestLocation = deviceLocations[0] || null;
return {
id: device.id,
name: device.name,
color: device.color,
isActive: device.isActive === 1,
createdAt: device.createdAt,
updatedAt: device.updatedAt,
description: device.description,
icon: device.icon,
latestLocation: latestLocation,
_count: {
locations: deviceLocations.length,
},
};
});
return NextResponse.json({ devices: devicesWithLocation });
} catch (error) {
console.error("Error fetching devices:", error);
return NextResponse.json(
{ error: "Failed to fetch devices" },
{ status: 500 }
);
}
}
// POST /api/devices - Create new device (ADMIN only)
export async function POST(request: Request) {
try {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Only ADMIN can create devices
if ((session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await request.json();
const { id, name, color, description, icon } = body;
// Validation
if (!id || !name || !color) {
return NextResponse.json(
{ error: "Missing required fields: id, name, color" },
{ status: 400 }
);
}
// Check if device with this ID already exists
const existing = deviceDb.findById(id);
if (existing) {
return NextResponse.json(
{ error: "Device with this ID already exists" },
{ status: 409 }
);
}
// Create device
const device = deviceDb.create({
id,
name,
color,
ownerId: (session.user as any).id,
description,
icon,
});
return NextResponse.json({ device }, { status: 201 });
} catch (error) {
console.error("Error creating device:", error);
return NextResponse.json(
{ error: "Failed to create device" },
{ status: 500 }
);
}
}