diff --git a/src/_dto/anlagen/ios.ts b/src/_dto/anlagen/ios.ts index 6a98401..17b06e3 100644 --- a/src/_dto/anlagen/ios.ts +++ b/src/_dto/anlagen/ios.ts @@ -10,47 +10,60 @@ export class IoResponseDto { id!:string; anlageId!: string; - type!: IOType; - address!: number; + adrType!: string; + adrByte!: number; adrBit?: number; - plcId?: string; - moduleId?: string; - channel?: number; - text?: string; + + functionText?: string; + seite?: number; seiteName?: string; + excelData?: string; - plcData?: string; + + plcId?: string; + moduleId?: string; + channel?: number; } export class IoCreateDto { - //anlageId!: string; - type!: IOType; - address!: number; + + + adrType!: string; + adrByte!: number; adrBit?: number; - plcId?: string; - moduleId?: string; - channel?: number; - text?: string; + + functionText?: string; + seite?: number; seiteName?: string; + excelData?: string; - plcData?: string; + + plcId?: string; + moduleId?: string; + channel?: number; + } export class IoUpdateDto { anlageId?: string; - type?: IOType; - address?: number; + + adrType?: string; + adrByte?: number; adrBit?: number; - plcId?: string; - moduleId?: string; - channel?: number; - text?: string; + + functionText?: string; + seite?: number; seiteName?: string; + excelData?: string; - plcData?: string; + + plcId?: string | null; + moduleId?: string | null; + channel?: number; + } //--- n.v. diff --git a/src/_dto/anlagen/signals.ts b/src/_dto/anlagen/signals.ts index 94dca80..523d7ab 100644 --- a/src/_dto/anlagen/signals.ts +++ b/src/_dto/anlagen/signals.ts @@ -32,6 +32,15 @@ export class SignalUpdateDto { name!: string; type!: SignalType; description?: string; - ioId?: string; + ioId?: string | null; componentId?: string; } + +export class SignalIoAssignmentDto { + ioId!: string | null; +} + +export class SignalBulkIoAssignmentDto extends SignalIoAssignmentDto { + signalId!: string; + previousIoId!: string | null; +} diff --git a/src/_schemas/anlagen/ios.ts b/src/_schemas/anlagen/ios.ts index 1f65fbf..2e5ef6d 100644 --- a/src/_schemas/anlagen/ios.ts +++ b/src/_schemas/anlagen/ios.ts @@ -10,6 +10,7 @@ export enum IOType { } export type IoDocument = HydratedDocument; + @Schema({ timestamps: true }) export class IO { @@ -17,14 +18,26 @@ export class IO { anlageId!: Types.ObjectId; @Prop({ required: true, enum: Object.values(IOType), }) - type!: IOType; + adrType!: string; @Prop({ required: true }) - address!: number; + adrByte!: number; @Prop() adrBit!: number; + @Prop() + functionText?: string; + + @Prop() + seite?: number; + + @Prop() + seiteName?: string; + + @Prop() + excelData?: string; + @Prop() plcId?: Types.ObjectId; @@ -33,21 +46,6 @@ export class IO { @Prop() channel?: number; - - @Prop() - text?: string; - - @Prop() - seite?: number; - - @Prop() - seiteName?: string; - - @Prop() - excelData?: string; - - @Prop() - plcData?: string; } export const IOSchema = SchemaFactory.createForClass(IO); diff --git a/src/_schemas/anlagen/singnals.ts b/src/_schemas/anlagen/singnals.ts index 48c3b41..bce5288 100644 --- a/src/_schemas/anlagen/singnals.ts +++ b/src/_schemas/anlagen/singnals.ts @@ -25,7 +25,7 @@ export class Signal { description?: string; @Prop({ type: Types.ObjectId, ref: 'IO', default: null, }) - ioId?: Types.ObjectId; + ioId?: Types.ObjectId | null; @Prop({ type: Types.ObjectId, ref: 'Component', required: false }) componentId?: Types.ObjectId; diff --git a/src/anlagen/ios/ios.controller.ts b/src/anlagen/ios/ios.controller.ts index b0ff1f2..135c4f9 100644 --- a/src/anlagen/ios/ios.controller.ts +++ b/src/anlagen/ios/ios.controller.ts @@ -1,10 +1,23 @@ -import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common'; +import { Body, Controller, DefaultValuePipe, Delete, Get, Param, ParseBoolPipe, Patch, Post, Query } from '@nestjs/common'; import { IosService } from './ios.service'; -import { IoCreateDto, IoUpdateDto } from 'src/_dto/anlagen/ios'; +import { IoCreateDto, IoResponseDto, IoUpdateDto } from 'src/_dto/anlagen/ios'; @Controller('rk2/ios') export class IosController { constructor(private readonly service: IosService) { } + + @Post('import') + bulkCreate(@Body() dtos: IoCreateDto[]): Promise { + return this.service.bulkCreate(dtos); + } + + @Patch('import') + bulkUpdate( + @Body() dtos: IoCreateDto[], + @Query('onlyChanged', new DefaultValuePipe(true), ParseBoolPipe) onlyChanged: boolean, + ) { + return this.service.bulkUpdate(dtos, onlyChanged); + } @Get() getAll() { diff --git a/src/anlagen/ios/ios.service.ts b/src/anlagen/ios/ios.service.ts index 5a549d3..e560a97 100644 --- a/src/anlagen/ios/ios.service.ts +++ b/src/anlagen/ios/ios.service.ts @@ -1,6 +1,6 @@ -import { Injectable, NotFoundException } from '@nestjs/common'; +import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; +import { Error as MongooseError, isObjectIdOrHexString, Model, Types } from 'mongoose'; import { IoCreateDto, IoResponseDto, IoUpdateDto } from 'src/_dto/anlagen/ios'; import { IO, IoDocument } from 'src/_schemas/anlagen/ios'; import { AnlageService } from 'src/rk-anlagen/anlage/anlage.service'; @@ -12,6 +12,16 @@ export class IosService { private readonly anlageService: AnlageService ) { } + private parseObjectId(value: string, field: string): Types.ObjectId { + if (!isObjectIdOrHexString(value)) { + throw new BadRequestException( + `${field} ist keine gültige ObjectId`, + ); + } + + return new Types.ObjectId(value); + } + async findAll(): Promise { const responsData = await this.model.find().exec(); @@ -19,45 +29,162 @@ export class IosService { } async findOne(id: string): Promise { - const item = await this.model.findById(id).exec(); - if (!item) throw new NotFoundException(`Signal ${id} nicht gefunden`) + const objectId = this.parseObjectId(id, 'id'); + const item = await this.model.findById(objectId).exec(); + if (!item) throw new NotFoundException(`IO ${id} nicht gefunden`) return this.toDto(item); } async create(dto: IoCreateDto): Promise { let currentAnlage = await this.anlageService.getSelected(); - console.log(currentAnlage); - if (!currentAnlage) throw new NotFoundException('Es ist keine Anlage ausgewählt'); + + const newItem = new this.model(this.toDocument(dto, currentAnlage.id)); const result = await newItem.save(); return this.toDto(result); } + private ioAddressKey(io: Pick): string { + return JSON.stringify([io.adrType, io.adrByte, io.adrBit ?? null]); + } + + private async prepareBulk(dtos: IoCreateDto[]) { + if (!Array.isArray(dtos) || dtos.length === 0) { + throw new BadRequestException('Es wurden keine IO-Datensätze übergeben'); + } + for (const [index, dto] of dtos.entries()) { + if (typeof dto !== 'object' || dto === null || Array.isArray(dto)) { + throw new BadRequestException(`Datensatz ${index + 1} ist ungültig: Ein IO-Objekt wird erwartet`); + } + } + const anlage = await this.anlageService.getSelected(); + const documents: IoDocument[] = []; + const seen = new Set(); + for (const [index, dto] of dtos.entries()) { + try { + const document = new this.model(this.toDocument(dto, anlage.id)); + await document.validate(); + const key = this.ioAddressKey(document); + // Bei mehrfachen Adressen im Import gilt der erste Datensatz. + if (!seen.has(key)) { + seen.add(key); + documents.push(document); + } + } catch (error: unknown) { + if (error instanceof BadRequestException || error instanceof MongooseError.ValidationError) { + throw new BadRequestException(`Datensatz ${index + 1} ist ungültig: ${error.message}`); + } + throw error; + } + } + const existing = await this.model.find({ + anlageId: this.parseObjectId(anlage.id, 'anlageId'), + $or: documents.map((document) => ({ + adrType: document.adrType, + adrByte: document.adrByte, + adrBit: document.adrBit ?? null, + })), + }).exec(); + return { documents, existing }; + } + + async bulkCreate(dtos: IoCreateDto[]): Promise { + const { documents, existing } = await this.prepareBulk(dtos); + const existingKeys = new Set(existing.map((item) => this.ioAddressKey(item))); + const newDocuments = documents.filter((item) => !existingKeys.has(this.ioAddressKey(item))); + if (newDocuments.length === 0) return []; + const createdItems = await this.model.insertMany(newDocuments, { ordered: true }); + return createdItems.map((item) => this.toDto(item)); + } + + async bulkUpdate(dtos: IoCreateDto[], onlyChanged = true) { + const { documents, existing } = await this.prepareBulk(dtos); + const existingByKey = new Map(); + for (const item of existing) { + const key = this.ioAddressKey(item); + if (existingByKey.has(key)) { + throw new ConflictException('Mehrere vorhandene IOs haben dieselbe Adresse. Bitte zuerst bereinigen.'); + } + existingByKey.set(key, item); + } + + const operations: Parameters['bulkWrite']>[0] = []; + let missing = 0; + let unchanged = 0; + for (const document of documents) { + const item = existingByKey.get(this.ioAddressKey(document)); + if (!item) { + missing++; + continue; + } + // Nur gelieferte Nutzdaten ändern; Adresse, Anlage und fehlende Referenzen erhalten. + const set: Partial = {}; + for (const field of ['functionText', 'seite', 'seiteName', 'excelData', 'plcId', 'moduleId', 'channel'] as const) { + const value = document[field]; + if (value !== undefined) Object.assign(set, { [field]: value }); + } + const changed = Object.entries(set).some(([field, value]) => { + const previous = item.get(field) as unknown; + return String(previous ?? '') !== String(value ?? '') || (previous == null) !== (value == null); + }); + if (onlyChanged && !changed) { + unchanged++; + continue; + } + operations.push({ updateOne: { filter: { _id: item._id, anlageId: item.anlageId }, update: { $set: set } } }); + } + const result = operations.length > 0 + ? await this.model.bulkWrite(operations, { ordered: true }) : undefined; + return { + matched: result?.matchedCount ?? 0, + modified: result?.modifiedCount ?? 0, + unchanged, + missing, + duplicates: dtos.length - documents.length, + }; + } async update(id: string, dto: IoUpdateDto) { - let currentAnlage = await this.anlageService.getSelected(); - let anlage = dto.anlageId ? dto.anlageId : currentAnlage.id; - if (!anlage) throw new NotFoundException('Anlage Id muss gesetzt sein') - - let update = this.toDocument(dto, anlage); - console.log(update); - const changedItem = await this.model.findByIdAndUpdate(id, { - $set: { - ...update + const objectId = this.parseObjectId(id, 'id'); + const set = this.toUpdateDocument(dto); + const unset: Record = {}; + if (dto.plcId !== undefined) { + if (dto.plcId === null) { + unset.plcId = 1; + } else { + set.plcId = this.parseObjectId(dto.plcId, 'plcId'); } - }, { returnDocument: 'after', runValidators: true }); + } - if (!changedItem) throw new NotFoundException(`Signal ${id} nicht gefunden`); + if (dto.moduleId !== undefined) { + if (dto.moduleId === null) { + unset.moduleId = 1; + } else { + set.moduleId = this.parseObjectId(dto.moduleId, 'moduleId'); + } + } - return this.toDto(changedItem); + const item = await this.model.findByIdAndUpdate( + objectId, + { $set: set, $unset: unset }, + { returnDocument: 'after', runValidators: true }, + ).exec(); + + if (!item) { + throw new NotFoundException(`IO ${id} nicht gefunden`); + } + + + return this.toDto(item); } async remove(id: string) { - const removedItem = await this.model.findByIdAndDelete(id, { returnDocument: 'after', runValidators: true }); + const objectId = this.parseObjectId(id, 'id'); + const removedItem = await this.model.findByIdAndDelete(objectId, { returnDocument: 'after', runValidators: true }); - if (!removedItem) throw new NotFoundException(`Signal ${id} nicht gefunden`); + if (!removedItem) throw new NotFoundException(`IO ${id} nicht gefunden`); return this.toDto(removedItem); } @@ -67,34 +194,54 @@ export class IosService { return { id: dbData._id.toString(), anlageId: dbData.anlageId.toString(), - type: dbData.type, - address: dbData.address, + adrType: dbData.adrType, + adrByte: dbData.adrByte, adrBit: dbData.adrBit, - plcId: dbData.plcId?.toString(), - moduleId: dbData.moduleId?.toString(), - channel: dbData.channel, - text: dbData.text, + functionText: dbData.functionText, seite: dbData.seite, seiteName: dbData.seiteName, excelData: dbData.excelData, - plcData: dbData.plcData + plcId: dbData.plcId?.toString(), + moduleId: dbData.moduleId?.toString(), + channel: dbData.channel, } } - toDocument(dto: IoCreateDto | IoUpdateDto, anlage: string) { + toDocument(dto: IoCreateDto, anlage: string) { + return { - anlageId: new Types.ObjectId(anlage), - type: dto.type, - address: dto.address, + anlageId: this.parseObjectId(anlage, 'anlageId'), + adrType: dto.adrType, + adrByte: dto.adrByte, adrBit: dto.adrBit, - plcId: dto.plcId ? new Types.ObjectId(dto.plcId) : null, - moduleId: dto.moduleId ? new Types.ObjectId(dto.moduleId) : null, - channel: dto.channel, - text: dto.text, + functionText: dto.functionText, seite: dto.seite, seiteName: dto.seiteName, excelData: dto.excelData, - plcData: dto.plcData + plcId: dto.plcId !== undefined ? this.parseObjectId(dto.plcId, 'plcId') : undefined, + moduleId: dto.moduleId !== undefined ? this.parseObjectId(dto.moduleId, 'moduleId') : undefined, + channel: dto.channel, }; } + + private toUpdateDocument(dto: IoUpdateDto) { + const update: Partial = {}; + + if (dto.anlageId !== undefined) { + update.anlageId = this.parseObjectId(dto.anlageId, 'anlageId'); + } + + if (dto.adrType !== undefined) update.adrType = dto.adrType; + if (dto.adrByte !== undefined) update.adrByte = dto.adrByte; + if (dto.adrBit !== undefined) update.adrBit = dto.adrBit; + if (dto.functionText !== undefined) update.functionText = dto.functionText; + if (dto.seite !== undefined) update.seite = dto.seite; + if (dto.seiteName !== undefined) update.seiteName = dto.seiteName; + if (dto.excelData !== undefined) update.excelData = dto.excelData; + if (dto.channel !== undefined) update.channel = dto.channel; + + return update; + } + + } diff --git a/src/anlagen/signals/signal.excel.repo.ts b/src/anlagen/signals/signal.excel.repo.ts new file mode 100644 index 0000000..c93db6f --- /dev/null +++ b/src/anlagen/signals/signal.excel.repo.ts @@ -0,0 +1,98 @@ +import * as XLSX from "xlsx"; +import { ExcelImportDataDto } from "src/_dto/peripherie.dto"; +import { Injectable } from "@nestjs/common"; +import type { Express } from 'express'; + + +@Injectable() +export class ExcelRepo { + constructor() { } + + async getExcelData(file: Express.Multer.File): Promise { + try { + + const data: Array = [] + + const workbook = XLSX.read(file.buffer, { type: 'buffer' }); + const firstSheetName = workbook.SheetNames[0]; + const worksheet = workbook.Sheets[firstSheetName]; + + // In JSON konvertieren + const jsonData = XLSX.utils.sheet_to_json(worksheet, { defval: null, blankrows: false, header: 10 }) as any[]; + const d0 = jsonData[4]; + + jsonData.forEach((d, index) => { + if (index < 4) return; + + const spsKarte = d['__EMPTY']; + const spsAdr = d['__EMPTY_1']; + const functionTxt = d['__EMPTY_3']; + const seite = typeof d['__EMPTY_4'] === 'number' ? Number.parseInt(d['__EMPTY_4'].toString()) : -1; + const seiteName = d['__EMPTY_5']; + + const result: ExcelImportDataDto = { + functionText: functionTxt, + seite: seite, + seiteName: seiteName, + spsAdr: spsAdr, + spsKarte: spsKarte + } + if (spsKarte !== "" && spsKarte != undefined && spsKarte != null) + data.push(result) + }) + + return data; + } catch (error: any) { + console.log(error); + } + } + + + plcAdr_String_To_Obj = (adr: string) => { + let adrTypString = ''; + let adrString = ''; + + const res_match = adr.match(/^([A-Za-z]+)(.*)$/); + if (res_match) { + const [mText, mAdr] = res_match; + adrTypString = res_match[1]; + adrString = res_match[2]; + } + //console.log(res_match) + // Adresse aufteilen in Byte und Bit + + let [partByte, partBit] = adrString.split('.') + + let inputType = "unknown"; + let adrBit = 0; + let adrByte = Number(partByte); + + if (partBit && adrTypString === 'A') { + adrBit = Number(partBit); + inputType = 'Q'; + } + + if (!partBit && adrTypString === 'A') { + inputType = 'QW'; + } + + if (partBit && adrTypString === 'E') { + adrBit = Number(partBit); + inputType = 'I'; + } + + if (!partBit && adrTypString === 'E') { + inputType = 'IW'; + } + + return { + adrType: inputType, + adrByte, + adrBit + } + } + +} + + + diff --git a/src/anlagen/signals/signals.controller.ts b/src/anlagen/signals/signals.controller.ts index 2827e45..4ba0565 100644 --- a/src/anlagen/signals/signals.controller.ts +++ b/src/anlagen/signals/signals.controller.ts @@ -1,6 +1,6 @@ import { Body, Controller, Delete, Get, HttpStatus, Param, ParseFilePipeBuilder, Patch, Post, UploadedFile, UseInterceptors } from '@nestjs/common'; import { SignalsService } from './signals.service'; -import { SignalCreateDto, SignalUpdateDto } from 'src/_dto/anlagen/signals'; +import { SignalBulkIoAssignmentDto, SignalCreateDto, SignalIoAssignmentDto, SignalUpdateDto } from 'src/_dto/anlagen/signals'; import { FileInterceptor } from '@nestjs/platform-express'; import type { Express } from 'express'; @@ -29,6 +29,16 @@ export class SignalsController { return this.service.create(dto); } + @Patch('io-assignments') + assignIos(@Body() dtos: SignalBulkIoAssignmentDto[]) { + return this.service.assignIos(dtos); + } + + @Patch(':id/io') + assignIo(@Param('id') id: string, @Body() dto: SignalIoAssignmentDto) { + return this.service.assignIo(id, dto?.ioId); + } + @Patch(':id') update(@Param('id') id: string, @Body() dto: SignalUpdateDto) { return this.service.update(id, dto); @@ -44,7 +54,7 @@ export class SignalsController { @Post('upload') @UseInterceptors(FileInterceptor('file')) - uploadExcel( + async uploadExcel( @UploadedFile( new ParseFilePipeBuilder().build({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY, @@ -52,10 +62,12 @@ export class SignalsController { ) file: Express.Multer.File, ) { + const data = await this.service.uploadExcel(file) return { message: 'Excel erfolgreich empfangen', filename: file.originalname, size: file.size, + data }; } } diff --git a/src/anlagen/signals/signals.module.ts b/src/anlagen/signals/signals.module.ts index 98aec21..4e471cd 100644 --- a/src/anlagen/signals/signals.module.ts +++ b/src/anlagen/signals/signals.module.ts @@ -5,14 +5,16 @@ import { MongooseModule } from '@nestjs/mongoose'; import { Signal, SignalSchema } from 'src/_schemas/anlagen/singnals'; import { AnlageModule } from 'src/rk-anlagen/anlage/anlage.module'; import { ComponentsModule } from '../components/components.module'; +import { ExcelRepo } from './signal.excel.repo'; +import { IO, IOSchema } from 'src/_schemas/anlagen/ios'; @Module({ imports: [ - MongooseModule.forFeature([{ name: Signal.name, schema: SignalSchema }], "anlagen"), + MongooseModule.forFeature([{ name: Signal.name, schema: SignalSchema }, { name: IO.name, schema: IOSchema }], "anlagen"), AnlageModule, forwardRef(() =>ComponentsModule) ], - providers: [SignalsService], + providers: [SignalsService,ExcelRepo], controllers: [SignalsController], exports:[SignalsService] }) diff --git a/src/anlagen/signals/signals.service.ts b/src/anlagen/signals/signals.service.ts index 05ac2ed..cd70122 100644 --- a/src/anlagen/signals/signals.service.ts +++ b/src/anlagen/signals/signals.service.ts @@ -1,10 +1,13 @@ -import { forwardRef, Inject, Injectable, NotFoundException } from '@nestjs/common'; +import { BadRequestException, ConflictException, forwardRef, Inject, Injectable, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; -import { SignalCreateDto, SignalResponseDto, SignalUpdateDto } from 'src/_dto/anlagen/signals'; +import { isObjectIdOrHexString, Model, Types } from 'mongoose'; +import { IO } from 'src/_schemas/anlagen/ios'; +import { SignalBulkIoAssignmentDto, SignalCreateDto, SignalResponseDto, SignalUpdateDto } from 'src/_dto/anlagen/signals'; import { Signal, SignalDocument } from 'src/_schemas/anlagen/singnals'; import { AnlageService } from 'src/rk-anlagen/anlage/anlage.service'; import { ComponentsService } from '../components/components.service'; +import { ExcelRepo } from './signal.excel.repo'; +import type { Express } from 'express'; @Injectable() export class SignalsService { @@ -13,6 +16,8 @@ export class SignalsService { private readonly anlageService: AnlageService, @Inject(forwardRef(() => ComponentsService)) private readonly componentService: ComponentsService, + private readonly excel: ExcelRepo, + @InjectModel(IO.name, 'anlagen') private readonly ioModel: Model, ) { } async findAll(): Promise { @@ -40,6 +45,7 @@ export class SignalsService { if (!currentAnlage) throw new NotFoundException('Es ist keine Anlage ausgewählt'); + if (dto.ioId != null) await this.checkIo(dto.ioId, currentAnlage.id); const newItem = new this.model(this.toDocument(dto, currentAnlage.id)); const result = await newItem.save(); @@ -51,11 +57,15 @@ export class SignalsService { async update(id: string, dto: SignalUpdateDto) { - let currentAnlage = await this.anlageService.getSelected(); - let anlage = dto.anlageId ? dto.anlageId : currentAnlage.id; + const signal = await this.model.findById(this.objectId(id)).exec(); + if (!signal) throw new NotFoundException(`Signal ${id} nicht gefunden`); + let anlage = dto.anlageId ? dto.anlageId : signal.anlageId.toString(); if (!anlage) throw new NotFoundException('Anlage Id muss gesetzt sein') let update = this.toDocument(dto, anlage); + if (dto.ioId === undefined) update.ioId = signal.ioId ?? null; + if (dto.componentId === undefined) update.componentId = signal.componentId ?? null; + if (update.ioId) await this.checkIo(update.ioId.toString(), anlage, id); console.log(update); const changedItem = await this.model.findByIdAndUpdate(id, { $set: { @@ -69,6 +79,80 @@ export class SignalsService { return this.toDto(changedItem); } + private objectId(id: string): Types.ObjectId { + if (!isObjectIdOrHexString(id)) throw new BadRequestException('Ungültige ObjectId'); + return new Types.ObjectId(id); + } + + private async checkIo(ioId: string, anlageId: string, signalId?: string) { + const io = await this.ioModel.findById(this.objectId(ioId)).exec(); + if (!io) throw new NotFoundException('IO nicht gefunden'); + if (io.anlageId?.toString() !== anlageId) throw new BadRequestException('IO und Signal müssen zur selben Anlage gehören'); + const occupied = await this.model.findOne({ + ioId: io._id, + ...(signalId ? { _id: { $ne: this.objectId(signalId) } } : {}), + }).exec(); + if (occupied) throw new ConflictException(`IO ist bereits dem Signal ${occupied.name} zugeordnet`); + } + + async assignIos(dtos: SignalBulkIoAssignmentDto[]): Promise { + if (!Array.isArray(dtos) || dtos.length === 0) throw new BadRequestException('Keine Zuordnungen übergeben'); + const signalIds = new Set(); + const ioIds = new Set(); + for (const dto of dtos) { + if (!dto || typeof dto !== 'object' || Array.isArray(dto)) throw new BadRequestException('Ungültige Zuordnung'); + const id = this.objectId(dto.signalId).toString(); + if (signalIds.has(id)) throw new BadRequestException('Signal mehrfach übergeben'); + signalIds.add(id); + if (dto.previousIoId !== null) this.objectId(dto.previousIoId); + if (dto.ioId !== null) { + const ioId = this.objectId(dto.ioId).toString(); + if (ioIds.has(ioId)) throw new ConflictException('Ein IO darf nur einem Signal zugeordnet werden'); + ioIds.add(ioId); + } + } + const anlage = await this.anlageService.getSelected(); + const signals = await this.model.find({ _id: { $in: [...signalIds] } }).exec(); + const ios = await this.ioModel.find({ _id: { $in: [...ioIds] } }).exec(); + const owners = await this.model.find({ ioId: { $in: [...ioIds] } }).exec(); + for (const dto of dtos) { + const signal = signals.find((item) => item._id.toString() === dto.signalId); + if (!signal) throw new NotFoundException('Signal nicht gefunden'); + if (signal.anlageId.toString() !== anlage.id) throw new BadRequestException('Signal gehört nicht zur ausgewählten Anlage'); + const current = signal.ioId?.toString() ?? null; + if (current !== dto.previousIoId && current !== dto.ioId) throw new ConflictException(`Zuordnung für ${signal.name} wurde zwischenzeitlich geändert. Bitte neu laden.`); + if (dto.ioId === null) continue; + const io = ios.find((item) => item._id.toString() === dto.ioId); + if (!io) throw new NotFoundException('IO nicht gefunden'); + if (io.anlageId?.toString() !== anlage.id) throw new BadRequestException('IO gehört nicht zur ausgewählten Anlage'); + for (const owner of owners.filter((item) => item.ioId?.toString() === dto.ioId && item._id.toString() !== dto.signalId)) { + const change = dtos.find((item) => item.signalId === owner._id.toString()); + if (!change || change.ioId === dto.ioId) throw new ConflictException(`IO ist bereits dem Signal ${owner.name} zugeordnet`); + } + } + await this.model.bulkWrite(dtos.map((dto) => ({ updateOne: { + filter: { _id: this.objectId(dto.signalId), anlageId: this.objectId(anlage.id), ioId: { $in: [dto.previousIoId === null ? null : this.objectId(dto.previousIoId), dto.ioId === null ? null : this.objectId(dto.ioId)] } }, + update: { $set: { ioId: dto.ioId === null ? null : this.objectId(dto.ioId) } }, + } })), { ordered: true }); + const saved = await this.model.find({ _id: { $in: [...signalIds] } }).exec(); + if (saved.length !== dtos.length || dtos.some((dto) => (saved.find((item) => item._id.toString() === dto.signalId)?.ioId?.toString() ?? null) !== dto.ioId)) { + throw new ConflictException('Nicht alle Zuordnungen gespeichert. Zwischenzeitliche Änderungen erkannt; bitte Belegungen neu laden.'); + } + return saved.map((item) => this.toDto(item)); + } + + async assignIo(id: string, ioId: string | null): Promise { + if (ioId !== null && typeof ioId !== 'string') throw new BadRequestException('ioId muss eine ObjectId oder null sein'); + const signal = await this.model.findById(this.objectId(id)).exec(); + if (!signal) throw new NotFoundException(`Signal ${id} nicht gefunden`); + if (ioId !== null) await this.checkIo(ioId, signal.anlageId.toString(), id); + const item = await this.model.findByIdAndUpdate(signal._id, + { $set: { ioId: ioId === null ? null : this.objectId(ioId) } }, + { returnDocument: 'after', runValidators: true }).exec(); + if (!item) throw new NotFoundException(`Signal ${id} nicht gefunden`); + return this.toDto(item); + } + async remove(id: string) { const removedItem = await this.model.findByIdAndDelete(id, { returnDocument: 'after', runValidators: true }); @@ -84,6 +168,20 @@ export class SignalsService { } + async uploadExcel(file: Express.Multer.File) { + const excelDataRow = await this.excel.getExcelData(file); + if (!excelDataRow) throw new BadRequestException("Excel File konnte nicht gelesen werden") + const retValue = excelDataRow?.map((row) => ( + { + functionText: row.functionText, + seite: row.seite, + seiteName: row.seiteName, + spsKarte: row.spsKarte, + ... this.excel.plcAdr_String_To_Obj(row.spsAdr), + })) + return retValue; + } + toDto(dbData: SignalDocument): SignalResponseDto { return { diff --git a/src/main.ts b/src/main.ts index f76bc8d..b908df7 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,8 +1,10 @@ import { NestFactory } from '@nestjs/core'; +import type { NestExpressApplication } from '@nestjs/platform-express'; import { AppModule } from './app.module'; async function bootstrap() { - const app = await NestFactory.create(AppModule); + const app = await NestFactory.create(AppModule); + app.useBodyParser('json', { limit: '10mb' }); await app.listen(process.env.PORT ?? 3000); } bootstrap(); diff --git a/src/rk-anlagen/anlage/anlage.service.ts b/src/rk-anlagen/anlage/anlage.service.ts index 9160c4c..b267a46 100644 --- a/src/rk-anlagen/anlage/anlage.service.ts +++ b/src/rk-anlagen/anlage/anlage.service.ts @@ -18,14 +18,20 @@ export class AnlageService { return item; } - async getSelected():Promise { + async getSelected(): Promise { console.log('GetSelected Anlage') - const item = await this.model.findOne({ selected: true }) as Anlage; - let ret:AnlageDto = { - id:item._id.toString(), - anlageNr:item.anlageNr, - name:item.name, - selected:item.selected + + const item = await this.model.findOne({ selected: true }).exec(); + + if (!item) { + throw new NotFoundException('Es ist keine Anlage ausgewählt'); + } + + let ret: AnlageDto = { + id: item._id.toString(), + anlageNr: item.anlageNr, + name: item.name, + selected: item.selected } return ret; } @@ -53,12 +59,12 @@ export class AnlageService { async setSelected(id: string) { await this.model.updateMany( - { }, + {}, { $set: { selected: false } }, ).exec(); - const anlage = await this.model.findByIdAndUpdate(id, {selected:true}, { returnDocument: 'after', runValidators: true }); - + const anlage = await this.model.findByIdAndUpdate(id, { selected: true }, { returnDocument: 'after', runValidators: true }); + return anlage; }