feat(M06-B): 建立设备资产与拓扑管理
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import type { AuthRepository } from '../auth/auth-repository.js';
|
||||
import { authenticateAccessToken } from '../auth/authenticate.js';
|
||||
import type { AccessProfile } from '../auth/rbac-repository.js';
|
||||
import type { ManagementActor } from '../auth/user-management-repository.js';
|
||||
import { DeviceError, type DeviceRepository } from '../devices/device-repository.js';
|
||||
|
||||
const id = z.string().regex(/^[1-9]\d{0,19}$/);
|
||||
const optionalId = id.nullable().optional();
|
||||
const deviceIdentity = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/);
|
||||
const assetSchema = z.object({
|
||||
storeId: id,
|
||||
roomId: optionalId,
|
||||
deviceId: deviceIdentity,
|
||||
imei: z.string().trim().max(64).default(''),
|
||||
iccid: z.string().trim().max(32).nullable().optional(),
|
||||
deviceType: z.enum(['CONTROL_BOX', 'SUB_LOCK', 'SMART_SOCKET']),
|
||||
model: z.string().trim().min(1).max(64),
|
||||
firmwareVersion: z.string().trim().max(64).default(''),
|
||||
signalStrength: z.number().int().min(-200).max(200).nullable().optional(),
|
||||
capabilities: z.array(z.string().trim().regex(/^[A-Z0-9_]{1,64}$/)).max(64).default([])
|
||||
});
|
||||
const channelSchema = z.object({
|
||||
assetId: id,
|
||||
storeId: id,
|
||||
roomId: id,
|
||||
channelCode: z.enum(['SLOT1', 'SLOT2', 'SLOT3', 'MAIN', 'LOCK', 'LED', 'TTS']),
|
||||
purpose: z.enum([
|
||||
'ROOM_POWER', 'AIR_CONDITIONER', 'LIGHTING', 'DOOR_MAGNET',
|
||||
'STORE_DOOR', 'ROOM_DOOR', 'TTS', 'LED'
|
||||
])
|
||||
});
|
||||
const linkSchema = z.object({
|
||||
parentAssetId: id,
|
||||
childAssetId: id,
|
||||
storeId: id,
|
||||
roomId: id,
|
||||
subId: z.string().trim().min(1).max(64),
|
||||
subtype: z.string().trim().min(1).max(32)
|
||||
});
|
||||
const statusSchema = z.object({
|
||||
storeId: id,
|
||||
onlineStatus: z.enum(['ONLINE', 'OFFLINE', 'FAULT']),
|
||||
signalStrength: z.number().int().min(-200).max(200).nullable().optional(),
|
||||
firmwareVersion: z.string().trim().max(64).optional(),
|
||||
snapshot: z.record(z.unknown()).default({})
|
||||
});
|
||||
const maintenanceSchema = z.object({
|
||||
storeId: id,
|
||||
roomId: optionalId,
|
||||
recordType: z.enum(['INSPECTION', 'REPAIR', 'REPLACEMENT']),
|
||||
status: z.enum(['OPEN', 'RESOLVED']),
|
||||
description: z.string().trim().max(500).default('')
|
||||
});
|
||||
|
||||
export interface DeviceRouteOptions {
|
||||
repository: Pick<DeviceRepository,
|
||||
'createAsset' | 'listAssets' | 'getTopology' | 'bindChannel' | 'bindSubDevice'
|
||||
| 'recordStatus' | 'addMaintenance'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerDeviceRoutes(app: FastifyInstance, options: DeviceRouteOptions) {
|
||||
app.get('/admin-api/devices', async (request, reply) => {
|
||||
const actor = await requireDeviceOperator(request, reply, options);
|
||||
const query = z.object({ storeId: id.optional() }).safeParse(request.query);
|
||||
if (!actor || !query.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return mutate(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.listAssets(actor, query.data.storeId),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/admin-api/devices', async (request, reply) => {
|
||||
const actor = await requireDeviceOperator(request, reply, options);
|
||||
const body = assetSchema.safeParse(request.body);
|
||||
if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return mutate(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0, data: await options.repository.createAsset(actor, body.data),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.get('/admin-api/device-topology', async (request, reply) => {
|
||||
const actor = await requireDeviceOperator(request, reply, options);
|
||||
const query = z.object({ storeId: id }).safeParse(request.query);
|
||||
if (!actor || !query.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return mutate(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.getTopology(actor, query.data.storeId),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/admin-api/device-channels', async (request, reply) => {
|
||||
const actor = await requireDeviceOperator(request, reply, options);
|
||||
const body = channelSchema.safeParse(request.body);
|
||||
if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return mutate(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0, data: await options.repository.bindChannel(actor, body.data),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/admin-api/device-links', async (request, reply) => {
|
||||
const actor = await requireDeviceOperator(request, reply, options);
|
||||
const body = linkSchema.safeParse(request.body);
|
||||
if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return mutate(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0, data: await options.repository.bindSubDevice(actor, body.data),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/admin-api/devices/:id/status', async (request, reply) => {
|
||||
const actor = await requireDeviceOperator(request, reply, options);
|
||||
const params = z.object({ id }).safeParse(request.params);
|
||||
const body = statusSchema.safeParse(request.body);
|
||||
if (!actor || !params.success || !body.success) {
|
||||
return actor ? invalid(reply, request.traceId) : undefined;
|
||||
}
|
||||
return mutate(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.recordStatus(actor, {
|
||||
assetId: params.data.id, ...body.data
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/admin-api/devices/:id/maintenance', async (request, reply) => {
|
||||
const actor = await requireDeviceOperator(request, reply, options);
|
||||
const params = z.object({ id }).safeParse(request.params);
|
||||
const body = maintenanceSchema.safeParse(request.body);
|
||||
if (!actor || !params.success || !body.success) {
|
||||
return actor ? invalid(reply, request.traceId) : undefined;
|
||||
}
|
||||
return mutate(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0,
|
||||
data: await options.repository.addMaintenance(actor, {
|
||||
assetId: params.data.id, ...body.data
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function requireDeviceOperator(
|
||||
request: FastifyRequest, reply: FastifyReply, options: DeviceRouteOptions
|
||||
): Promise<ManagementActor | null> {
|
||||
const auth = await authenticateAccessToken(
|
||||
request.headers.authorization, options.authRepository, options.jwtSecret
|
||||
);
|
||||
if (!auth) {
|
||||
reply.status(401).send({
|
||||
code: 'AUTH_SESSION_INVALID', message: 'Authentication required.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const access = await options.accessControl.getAccessProfile(
|
||||
auth.session.tenantId, auth.session.user.id
|
||||
);
|
||||
if (!access.capabilities.some((code) =>
|
||||
code === 'device.read' || code === 'device.write' || code === 'tenant.manage'
|
||||
) && !access.roles.includes('PLATFORM_ADMIN')) {
|
||||
reply.status(403).send({
|
||||
code: 'DEVICE_OPERATION_FORBIDDEN',
|
||||
message: 'Device permission is required.', traceId: request.traceId
|
||||
});
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
tenantId: auth.session.tenantId, userId: auth.session.user.id, access,
|
||||
traceId: request.traceId, ip: request.ip, userAgent: request.headers['user-agent'] ?? ''
|
||||
};
|
||||
}
|
||||
|
||||
async function mutate(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (!(error instanceof DeviceError)) throw error;
|
||||
const forbidden = error.code.endsWith('_FORBIDDEN');
|
||||
const conflict = error.code.endsWith('_CONFLICT');
|
||||
return reply.status(forbidden ? 403 : conflict ? 409 : 400).send({
|
||||
code: error.code, message: 'The device operation is not allowed.', traceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_DEVICE_REQUEST', message: 'The device request is invalid.', traceId
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user