import { BadRequestException, ConflictException, Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { randomUUID, createHash } from 'node:crypto'; import { BrowseDirection, NodeClass } from 'node-opcua'; import { OpcService } from '../opcua/opcua.service'; import { OpcConfigService } from '../opcua/opcua-config.service'; import { StructuresService } from './structures.service'; import type { OpcStructure } from './structures.types'; import type { StructureTemplate } from './structure-template.schema'; import type { ArrayImportInput, ArrayImportPreview, ArrayImportRow } from './structure-array.types'; import { validateArrayInput, arrayIndex, fieldSignature, templateFields } from './structure-array.helpers'; @Injectable() export class StructureArrayService { constructor(@InjectModel('OpcStructure', 'anlagen') private readonly model: Model, @InjectModel('OpcStructureTemplate', 'anlagen') private readonly templates: Model, private readonly structures: StructuresService, private readonly config: OpcConfigService, private readonly opc: OpcService) {} async preview(input: ArrayImportInput): Promise { validateArrayInput(input); await this.config.checkPlant(input.anlageId); const existing = await this.model.find({ anlageId: input.anlageId }).select('name').lean().exec(); const names = new Set(existing.map(r => r.name)); const template = await this.templates.findOne({ anlageId: input.anlageId, name: input.templateName }).lean().exec(); const connection = await this.opc.openStructureSession(input.anlageId, input.connectionId); try { const elements = new Map(); let page = await connection.session.browse({ nodeId: input.arrayNodeId.trim(), referenceTypeId: 'HierarchicalReferences', includeSubtypes: true, browseDirection: BrowseDirection.Forward, nodeClassMask: NodeClass.Object | NodeClass.Variable, resultMask: 63 }); let continuation: Buffer | undefined, count = 0; try { while (true) { continuation = page.continuationPoint?.length ? page.continuationPoint : undefined; if (!page.statusCode.isGood()) throw new BadRequestException('Array kann nicht durchsucht werden: ' + page.statusCode.toString()); for (const ref of page.references ?? []) { if (++count > 20000) throw new BadRequestException('Array hat zu viele direkte Knoten. Einen kleineren Teilbereich auswählen.'); const index = arrayIndex(ref.browseName.name ?? ''); if (index !== null && index >= input.start && index <= input.end) elements.set(index, [...(elements.get(index) ?? []), ref.nodeId.toString()]); } if (!continuation) break; page = await connection.session.browseNext(continuation, false); } } finally { if (continuation) await connection.session.browseNext(continuation, true).catch(() => undefined); } const rows: ArrayImportRow[] = []; let signature = template?.signature; for (let index = input.start; index <= input.end; index++) { const name = input.namePattern.replace('{index}', String(index)), targets = elements.get(index) ?? []; const row: ArrayImportRow = { index, name, rootNodeId: targets[0] ?? '', status: 'error', message: '', fields: [] }; if (names.has(name)) { row.status = 'exists'; row.message = 'Name bereits vorhanden; bleibt unverändert.'; } else if (targets.length !== 1) row.message = targets.length ? 'Array-Index mehrfach vorhanden.' : 'Array-Index nicht im OPC-Browser gefunden.'; else { try { row.fields = await this.structures.inspectFields(connection.session, targets[0]); if (row.fields.some(f => input.direction === 'read' ? !f.readable : !f.writable)) throw new Error('Zugriffsrichtung nicht für alle Felder erlaubt.'); const current = fieldSignature(row.fields); if (signature && current !== signature) throw new Error('Felder oder Datentypen passen nicht zur Vorlage.'); signature = current; row.status = 'ready'; row.message = 'Bereit'; } catch (cause) { row.message = cause instanceof Error ? cause.message : 'Struktur nicht lesbar'; } } rows.push(row); } await connection.assertCurrent(); const token = createHash('sha256').update(JSON.stringify({ input, templateId: template?.id, signature, rows })).digest('hex'); return { token, rows, ready: rows.filter(r => r.status === 'ready').length, existing: rows.filter(r => r.status === 'exists').length, errors: rows.filter(r => r.status === 'error').length, templateName: input.templateName }; } finally { await connection.close(); } } async apply(input: ArrayImportInput & { token: string }) { const { token, ...settings } = input; const preview = await this.preview(settings); if (!token || preview.token !== token) throw new ConflictException('Vorschau oder CPU-Daten geändert. Vorschau erneut laden.'); const ready = preview.rows.filter(r => r.status === 'ready'); if (!ready.length) throw new BadRequestException('Keine neuen gültigen Einträge zur Übernahme'); await this.config.checkPlant(input.anlageId); const signature = fieldSignature(ready[0].fields); let template = await this.templates.findOne({ anlageId: input.anlageId, name: input.templateName }).lean().exec(); if (!template) { try { template = (await this.templates.create({ anlageId: input.anlageId, name: input.templateName, id: randomUUID(), signature, fields: templateFields(ready[0].fields) })).toObject(); } catch (cause) { if ((cause as { code?: number }).code !== 11000) throw cause; template = await this.templates.findOne({ anlageId: input.anlageId, name: input.templateName }).lean().exec(); } } if (!template || template.signature !== signature) throw new ConflictException('Vorlage inzwischen geändert. Vorschau neu laden.'); let created = 0, skipped = preview.existing; const failures: { name: string; message: string }[] = []; for (const row of ready) { try { await this.config.checkPlant(input.anlageId); const result = await this.model.updateOne({ anlageId: input.anlageId, name: row.name }, { $setOnInsert: { anlageId: input.anlageId, name: row.name, id: randomUUID(), version: 1, connectionId: input.connectionId, rootNodeId: row.rootNodeId, direction: input.direction, templateId: template.id, bindings: row.fields.map(({ name, nodeId, readable, writable }) => ({ name, nodeId, readable, writable })), } }, { upsert: true, runValidators: true }); if (result.upsertedCount) created++; else skipped++; } catch (cause) { if ((cause as { code?: number }).code === 11000) skipped++; else { failures.push({ name: row.name, message: 'Nicht gespeichert. Verbindung zur Datenbank und ausgewählte Anlage prüfen.' }); break; } } } return { created, skipped, invalid: preview.errors, failures, notProcessed: ready.length - created - (skipped - preview.existing) - failures.length }; } }