import { GraphicLibraryService } from '../../visualisierung/library/graphic-library.service'; import { mkdir, writeFile } from 'node:fs/promises'; import { resolve, join } from 'node:path'; import { BadRequestException, Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; import { AnlageService } from '../../rk-anlagen/anlage/anlage.service'; import { DrawService } from '../../draw/draw.service'; import { Unit } from '../../_schemas/anlagen/units'; import { prepareBinding } from '../../visualisierung/shared/graphics'; import { type DigitalTable, validateDigitalTable } from './sensoren-digital.dto'; import type { DigitalDocument } from './sensoren-digital.schema'; import { digitalFileName } from './sensoren-digital.excel'; @Injectable() export class DigitalService { constructor(@InjectModel('SensorenDigital', 'anlagen') private readonly model: Model, @InjectModel(Unit.name, 'anlagen') private readonly units: Model, private readonly anlagen: AnlageService, private readonly draw: DrawService, private readonly library?: GraphicLibraryService) {} async get(): Promise { const anlageId = (await this.anlagen.getSelected()).id; const doc = await this.model.findOne({ anlageId }).lean().exec(); const table = { anlageId, version: doc?.revision ?? 0, reservedCount: doc?.reservedCount ?? 40, rows: doc?.rows ?? [] }; return this.library ? this.library.resolveTable(table) : table; } async sources() { const anlageId = (await this.anlagen.getSelected()).id; const units = await this.units.find({ anlageId: new Types.ObjectId(anlageId) }).lean().exec(); return { anlageId, sources: units.flatMap(unit => unit.components.map(component => ({ componentId: component._id!.toString(), label: [unit.postfix, unit.prefix, unit.bmk, unit.name, component.postfix, component.name, component.index !== undefined && component.index > 0 ? component.index : undefined, component.prefix].filter(v => v !== undefined && v !== '').join('_'), type: component.type, unitType: unit.type }))) }; } async save(input: DigitalTable) { validateDigitalTable(input); if ((await this.anlagen.getSelected()).id !== input.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.'); const linked = input.rows.filter(row => row.componentId); if (linked.length) { const { anlageId, sources } = await this.sources(); if (anlageId !== input.anlageId || linked.some(row => !sources.some(source => source.componentId === row.componentId))) throw new BadRequestException('Unit-Komponente dieser Anlage nicht mehr vorhanden'); } if (input.rows.some(row => row.graphics.some(g => g.libraryId))) { if (!this.library) throw new BadRequestException('Grafikbibliothek nicht verfuegbar'); input = await this.library.resolveTable(input); } const rows = input.rows.map(row => ({ id: row.id, datenNr: row.datenNr, beschreibung: row.beschreibung, hinzugefuegtAm: row.hinzugefuegtAm, componentId: row.componentId, placements: row.placements.map(({ id, x, y, width, height, z, show }) => ({ id, x, y, width, height, z, show })), graphics: row.graphics.map(binding => prepareBinding(this.draw, binding)) })); try { const result = await this.model.updateOne({ anlageId: input.anlageId, revision: input.version }, { $set: { rows, reservedCount: input.reservedCount }, $inc: { revision: 1 } }, { upsert: input.version === 0, runValidators: true }); if (!result.matchedCount && !result.upsertedCount) throw new BadRequestException('Sensoren inzwischen geändert. Neu laden.'); } catch (error) { if ((error as { code?: number }).code === 11000) throw new BadRequestException('Sensoren inzwischen geändert. Neu laden.'); throw error; } return this.get(); } async xamlFiles() { const table = await this.get(); const unique = new Map(); for (const row of table.rows) for (const binding of row.graphics) { const graphic = prepareBinding(this.draw, binding); const file = { name: digitalFileName(row, graphic.slot, graphic.variant), data: graphic.generator.ergebnis!.varianten.find(v => v.state === graphic.variant)!.xaml }; const old = unique.get(file.name.toLowerCase()); if (old && old.data !== file.data) throw new BadRequestException('Unterschiedliche Grafiken verwenden denselben Dateinamen: ' + file.name); unique.set(file.name.toLowerCase(), file); } return [...unique.values()]; } async exportXaml(anlageId: string) { const anlage = await this.anlagen.getSelected(); if (anlageId !== anlage.id) throw new BadRequestException('Anlage geaendert. Neu laden.'); const files = await this.xamlFiles(); if ((await this.anlagen.getSelected()).id !== anlageId) throw new BadRequestException('Anlage geaendert. Neu laden.'); const safeName = anlage.name.trim().replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').replace(/[ .]+$/g, ''); if (!safeName || !Number.isSafeInteger(anlage.anlageNr)) throw new BadRequestException('Anlagenname oder Nummer ungueltig'); const directory = 'data/' + anlage.anlageNr + '_' + safeName + '/xaml'; await mkdir(resolve(directory), { recursive: true }); for (const file of files) await writeFile(join(resolve(directory), file.name), file.data, 'utf8'); return { count: files.length, directory }; } }