2026_10_08_ki
This commit is contained in:
1 parent
d6d9133f4b
commit
d27f00a398
12 files changed
+497
-99
No files matched your search
+35
-22
@@ -10,47 +10,60 @@ export class IoResponseDto {
|
|||||||
id!:string;
|
id!:string;
|
||||||
anlageId!: string;
|
anlageId!: string;
|
||||||
|
|
||||||
type!: IOType;
|
adrType!: string;
|
||||||
address!: number;
|
adrByte!: number;
|
||||||
adrBit?: number;
|
adrBit?: number;
|
||||||
plcId?: string;
|
|
||||||
moduleId?: string;
|
functionText?: string;
|
||||||
channel?: number;
|
|
||||||
text?: string;
|
|
||||||
seite?: number;
|
seite?: number;
|
||||||
seiteName?: string;
|
seiteName?: string;
|
||||||
|
|
||||||
excelData?: string;
|
excelData?: string;
|
||||||
plcData?: string;
|
|
||||||
|
plcId?: string;
|
||||||
|
moduleId?: string;
|
||||||
|
channel?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IoCreateDto {
|
export class IoCreateDto {
|
||||||
//anlageId!: string;
|
|
||||||
type!: IOType;
|
|
||||||
address!: number;
|
adrType!: string;
|
||||||
|
adrByte!: number;
|
||||||
adrBit?: number;
|
adrBit?: number;
|
||||||
plcId?: string;
|
|
||||||
moduleId?: string;
|
functionText?: string;
|
||||||
channel?: number;
|
|
||||||
text?: string;
|
|
||||||
seite?: number;
|
seite?: number;
|
||||||
seiteName?: string;
|
seiteName?: string;
|
||||||
|
|
||||||
excelData?: string;
|
excelData?: string;
|
||||||
plcData?: string;
|
|
||||||
|
plcId?: string;
|
||||||
|
moduleId?: string;
|
||||||
|
channel?: number;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class IoUpdateDto {
|
export class IoUpdateDto {
|
||||||
anlageId?: string;
|
anlageId?: string;
|
||||||
type?: IOType;
|
|
||||||
address?: number;
|
adrType?: string;
|
||||||
|
adrByte?: number;
|
||||||
adrBit?: number;
|
adrBit?: number;
|
||||||
plcId?: string;
|
|
||||||
moduleId?: string;
|
functionText?: string;
|
||||||
channel?: number;
|
|
||||||
text?: string;
|
|
||||||
seite?: number;
|
seite?: number;
|
||||||
seiteName?: string;
|
seiteName?: string;
|
||||||
|
|
||||||
excelData?: string;
|
excelData?: string;
|
||||||
plcData?: string;
|
|
||||||
|
plcId?: string | null;
|
||||||
|
moduleId?: string | null;
|
||||||
|
channel?: number;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//--- n.v.
|
//--- n.v.
|
||||||
|
|||||||
@@ -32,6 +32,15 @@ export class SignalUpdateDto {
|
|||||||
name!: string;
|
name!: string;
|
||||||
type!: SignalType;
|
type!: SignalType;
|
||||||
description?: string;
|
description?: string;
|
||||||
ioId?: string;
|
ioId?: string | null;
|
||||||
componentId?: string;
|
componentId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class SignalIoAssignmentDto {
|
||||||
|
ioId!: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SignalBulkIoAssignmentDto extends SignalIoAssignmentDto {
|
||||||
|
signalId!: string;
|
||||||
|
previousIoId!: string | null;
|
||||||
|
}
|
||||||
+15
-17
@@ -10,6 +10,7 @@ export enum IOType {
|
|||||||
}
|
}
|
||||||
export type IoDocument = HydratedDocument<IO>;
|
export type IoDocument = HydratedDocument<IO>;
|
||||||
|
|
||||||
|
|
||||||
@Schema({ timestamps: true })
|
@Schema({ timestamps: true })
|
||||||
export class IO {
|
export class IO {
|
||||||
|
|
||||||
@@ -17,14 +18,26 @@ export class IO {
|
|||||||
anlageId!: Types.ObjectId;
|
anlageId!: Types.ObjectId;
|
||||||
|
|
||||||
@Prop({ required: true, enum: Object.values(IOType), })
|
@Prop({ required: true, enum: Object.values(IOType), })
|
||||||
type!: IOType;
|
adrType!: string;
|
||||||
|
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
address!: number;
|
adrByte!: number;
|
||||||
|
|
||||||
@Prop()
|
@Prop()
|
||||||
adrBit!: number;
|
adrBit!: number;
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
functionText?: string;
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
seite?: number;
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
seiteName?: string;
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
excelData?: string;
|
||||||
|
|
||||||
@Prop()
|
@Prop()
|
||||||
plcId?: Types.ObjectId;
|
plcId?: Types.ObjectId;
|
||||||
|
|
||||||
@@ -33,21 +46,6 @@ export class IO {
|
|||||||
|
|
||||||
@Prop()
|
@Prop()
|
||||||
channel?: number;
|
channel?: number;
|
||||||
|
|
||||||
@Prop()
|
|
||||||
text?: string;
|
|
||||||
|
|
||||||
@Prop()
|
|
||||||
seite?: number;
|
|
||||||
|
|
||||||
@Prop()
|
|
||||||
seiteName?: string;
|
|
||||||
|
|
||||||
@Prop()
|
|
||||||
excelData?: string;
|
|
||||||
|
|
||||||
@Prop()
|
|
||||||
plcData?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const IOSchema = SchemaFactory.createForClass(IO);
|
export const IOSchema = SchemaFactory.createForClass(IO);
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export class Signal {
|
|||||||
description?: string;
|
description?: string;
|
||||||
|
|
||||||
@Prop({ type: Types.ObjectId, ref: 'IO', default: null, })
|
@Prop({ type: Types.ObjectId, ref: 'IO', default: null, })
|
||||||
ioId?: Types.ObjectId;
|
ioId?: Types.ObjectId | null;
|
||||||
|
|
||||||
@Prop({ type: Types.ObjectId, ref: 'Component', required: false })
|
@Prop({ type: Types.ObjectId, ref: 'Component', required: false })
|
||||||
componentId?: Types.ObjectId;
|
componentId?: Types.ObjectId;
|
||||||
|
|||||||
@@ -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 { IosService } from './ios.service';
|
||||||
import { IoCreateDto, IoUpdateDto } from 'src/_dto/anlagen/ios';
|
import { IoCreateDto, IoResponseDto, IoUpdateDto } from 'src/_dto/anlagen/ios';
|
||||||
|
|
||||||
@Controller('rk2/ios')
|
@Controller('rk2/ios')
|
||||||
export class IosController {
|
export class IosController {
|
||||||
constructor(private readonly service: IosService) { }
|
constructor(private readonly service: IosService) { }
|
||||||
|
|
||||||
|
@Post('import')
|
||||||
|
bulkCreate(@Body() dtos: IoCreateDto[]): Promise<IoResponseDto[]> {
|
||||||
|
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()
|
@Get()
|
||||||
getAll() {
|
getAll() {
|
||||||
|
|||||||
+183
-36
@@ -1,6 +1,6 @@
|
|||||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
import { InjectModel } from '@nestjs/mongoose';
|
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 { IoCreateDto, IoResponseDto, IoUpdateDto } from 'src/_dto/anlagen/ios';
|
||||||
import { IO, IoDocument } from 'src/_schemas/anlagen/ios';
|
import { IO, IoDocument } from 'src/_schemas/anlagen/ios';
|
||||||
import { AnlageService } from 'src/rk-anlagen/anlage/anlage.service';
|
import { AnlageService } from 'src/rk-anlagen/anlage/anlage.service';
|
||||||
@@ -12,6 +12,16 @@ export class IosService {
|
|||||||
private readonly anlageService: AnlageService
|
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<IoResponseDto[]> {
|
async findAll(): Promise<IoResponseDto[]> {
|
||||||
const responsData = await this.model.find().exec();
|
const responsData = await this.model.find().exec();
|
||||||
|
|
||||||
@@ -19,45 +29,162 @@ export class IosService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findOne(id: string): Promise<IoResponseDto> {
|
async findOne(id: string): Promise<IoResponseDto> {
|
||||||
const item = await this.model.findById(id).exec();
|
const objectId = this.parseObjectId(id, 'id');
|
||||||
if (!item) throw new NotFoundException(`Signal ${id} nicht gefunden`)
|
const item = await this.model.findById(objectId).exec();
|
||||||
|
if (!item) throw new NotFoundException(`IO ${id} nicht gefunden`)
|
||||||
return this.toDto(item);
|
return this.toDto(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async create(dto: IoCreateDto): Promise<IoResponseDto> {
|
async create(dto: IoCreateDto): Promise<IoResponseDto> {
|
||||||
let currentAnlage = await this.anlageService.getSelected();
|
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 newItem = new this.model(this.toDocument(dto, currentAnlage.id));
|
||||||
const result = await newItem.save();
|
const result = await newItem.save();
|
||||||
return this.toDto(result);
|
return this.toDto(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ioAddressKey(io: Pick<IO, 'adrType' | 'adrByte' | 'adrBit'>): 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<string>();
|
||||||
|
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<IoResponseDto[]> {
|
||||||
|
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<string, IoDocument>();
|
||||||
|
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<Model<IO>['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<IO> = {};
|
||||||
|
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) {
|
async update(id: string, dto: IoUpdateDto) {
|
||||||
let currentAnlage = await this.anlageService.getSelected();
|
const objectId = this.parseObjectId(id, 'id');
|
||||||
let anlage = dto.anlageId ? dto.anlageId : currentAnlage.id;
|
const set = this.toUpdateDocument(dto);
|
||||||
if (!anlage) throw new NotFoundException('Anlage Id muss gesetzt sein')
|
const unset: Record<string, 1> = {};
|
||||||
|
|
||||||
let update = this.toDocument(dto, anlage);
|
|
||||||
console.log(update);
|
|
||||||
const changedItem = await this.model.findByIdAndUpdate(id, {
|
|
||||||
$set: {
|
|
||||||
...update
|
|
||||||
|
|
||||||
|
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) {
|
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);
|
return this.toDto(removedItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,34 +194,54 @@ export class IosService {
|
|||||||
return {
|
return {
|
||||||
id: dbData._id.toString(),
|
id: dbData._id.toString(),
|
||||||
anlageId: dbData.anlageId.toString(),
|
anlageId: dbData.anlageId.toString(),
|
||||||
type: dbData.type,
|
adrType: dbData.adrType,
|
||||||
address: dbData.address,
|
adrByte: dbData.adrByte,
|
||||||
adrBit: dbData.adrBit,
|
adrBit: dbData.adrBit,
|
||||||
plcId: dbData.plcId?.toString(),
|
functionText: dbData.functionText,
|
||||||
moduleId: dbData.moduleId?.toString(),
|
|
||||||
channel: dbData.channel,
|
|
||||||
text: dbData.text,
|
|
||||||
seite: dbData.seite,
|
seite: dbData.seite,
|
||||||
seiteName: dbData.seiteName,
|
seiteName: dbData.seiteName,
|
||||||
excelData: dbData.excelData,
|
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 {
|
return {
|
||||||
anlageId: new Types.ObjectId(anlage),
|
anlageId: this.parseObjectId(anlage, 'anlageId'),
|
||||||
type: dto.type,
|
adrType: dto.adrType,
|
||||||
address: dto.address,
|
adrByte: dto.adrByte,
|
||||||
adrBit: dto.adrBit,
|
adrBit: dto.adrBit,
|
||||||
plcId: dto.plcId ? new Types.ObjectId(dto.plcId) : null,
|
functionText: dto.functionText,
|
||||||
moduleId: dto.moduleId ? new Types.ObjectId(dto.moduleId) : null,
|
|
||||||
channel: dto.channel,
|
|
||||||
text: dto.text,
|
|
||||||
seite: dto.seite,
|
seite: dto.seite,
|
||||||
seiteName: dto.seiteName,
|
seiteName: dto.seiteName,
|
||||||
excelData: dto.excelData,
|
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<IO> = {};
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -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<ExcelImportDataDto[] | undefined> {
|
||||||
|
try {
|
||||||
|
|
||||||
|
const data: Array<ExcelImportDataDto> = []
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Body, Controller, Delete, Get, HttpStatus, Param, ParseFilePipeBuilder, Patch, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
|
import { Body, Controller, Delete, Get, HttpStatus, Param, ParseFilePipeBuilder, Patch, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
|
||||||
import { SignalsService } from './signals.service';
|
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 { FileInterceptor } from '@nestjs/platform-express';
|
||||||
import type { Express } from 'express';
|
import type { Express } from 'express';
|
||||||
|
|
||||||
@@ -29,6 +29,16 @@ export class SignalsController {
|
|||||||
return this.service.create(dto);
|
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')
|
@Patch(':id')
|
||||||
update(@Param('id') id: string, @Body() dto: SignalUpdateDto) {
|
update(@Param('id') id: string, @Body() dto: SignalUpdateDto) {
|
||||||
return this.service.update(id, dto);
|
return this.service.update(id, dto);
|
||||||
@@ -44,7 +54,7 @@ export class SignalsController {
|
|||||||
|
|
||||||
@Post('upload')
|
@Post('upload')
|
||||||
@UseInterceptors(FileInterceptor('file'))
|
@UseInterceptors(FileInterceptor('file'))
|
||||||
uploadExcel(
|
async uploadExcel(
|
||||||
@UploadedFile(
|
@UploadedFile(
|
||||||
new ParseFilePipeBuilder().build({
|
new ParseFilePipeBuilder().build({
|
||||||
errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
|
errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
|
||||||
@@ -52,10 +62,12 @@ export class SignalsController {
|
|||||||
)
|
)
|
||||||
file: Express.Multer.File,
|
file: Express.Multer.File,
|
||||||
) {
|
) {
|
||||||
|
const data = await this.service.uploadExcel(file)
|
||||||
return {
|
return {
|
||||||
message: 'Excel erfolgreich empfangen',
|
message: 'Excel erfolgreich empfangen',
|
||||||
filename: file.originalname,
|
filename: file.originalname,
|
||||||
size: file.size,
|
size: file.size,
|
||||||
|
data
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,14 +5,16 @@ import { MongooseModule } from '@nestjs/mongoose';
|
|||||||
import { Signal, SignalSchema } from 'src/_schemas/anlagen/singnals';
|
import { Signal, SignalSchema } from 'src/_schemas/anlagen/singnals';
|
||||||
import { AnlageModule } from 'src/rk-anlagen/anlage/anlage.module';
|
import { AnlageModule } from 'src/rk-anlagen/anlage/anlage.module';
|
||||||
import { ComponentsModule } from '../components/components.module';
|
import { ComponentsModule } from '../components/components.module';
|
||||||
|
import { ExcelRepo } from './signal.excel.repo';
|
||||||
|
import { IO, IOSchema } from 'src/_schemas/anlagen/ios';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
MongooseModule.forFeature([{ name: Signal.name, schema: SignalSchema }], "anlagen"),
|
MongooseModule.forFeature([{ name: Signal.name, schema: SignalSchema }, { name: IO.name, schema: IOSchema }], "anlagen"),
|
||||||
AnlageModule,
|
AnlageModule,
|
||||||
forwardRef(() =>ComponentsModule)
|
forwardRef(() =>ComponentsModule)
|
||||||
],
|
],
|
||||||
providers: [SignalsService],
|
providers: [SignalsService,ExcelRepo],
|
||||||
controllers: [SignalsController],
|
controllers: [SignalsController],
|
||||||
exports:[SignalsService]
|
exports:[SignalsService]
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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 { InjectModel } from '@nestjs/mongoose';
|
||||||
import { Model, Types } from 'mongoose';
|
import { isObjectIdOrHexString, Model, Types } from 'mongoose';
|
||||||
import { SignalCreateDto, SignalResponseDto, SignalUpdateDto } from 'src/_dto/anlagen/signals';
|
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 { Signal, SignalDocument } from 'src/_schemas/anlagen/singnals';
|
||||||
import { AnlageService } from 'src/rk-anlagen/anlage/anlage.service';
|
import { AnlageService } from 'src/rk-anlagen/anlage/anlage.service';
|
||||||
import { ComponentsService } from '../components/components.service';
|
import { ComponentsService } from '../components/components.service';
|
||||||
|
import { ExcelRepo } from './signal.excel.repo';
|
||||||
|
import type { Express } from 'express';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SignalsService {
|
export class SignalsService {
|
||||||
@@ -13,6 +16,8 @@ export class SignalsService {
|
|||||||
private readonly anlageService: AnlageService,
|
private readonly anlageService: AnlageService,
|
||||||
@Inject(forwardRef(() => ComponentsService))
|
@Inject(forwardRef(() => ComponentsService))
|
||||||
private readonly componentService: ComponentsService,
|
private readonly componentService: ComponentsService,
|
||||||
|
private readonly excel: ExcelRepo,
|
||||||
|
@InjectModel(IO.name, 'anlagen') private readonly ioModel: Model<IO>,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
async findAll(): Promise<SignalResponseDto[]> {
|
async findAll(): Promise<SignalResponseDto[]> {
|
||||||
@@ -40,6 +45,7 @@ export class SignalsService {
|
|||||||
if (!currentAnlage) throw new NotFoundException('Es ist keine Anlage ausgewählt');
|
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 newItem = new this.model(this.toDocument(dto, currentAnlage.id));
|
||||||
const result = await newItem.save();
|
const result = await newItem.save();
|
||||||
|
|
||||||
@@ -51,11 +57,15 @@ export class SignalsService {
|
|||||||
|
|
||||||
|
|
||||||
async update(id: string, dto: SignalUpdateDto) {
|
async update(id: string, dto: SignalUpdateDto) {
|
||||||
let currentAnlage = await this.anlageService.getSelected();
|
const signal = await this.model.findById(this.objectId(id)).exec();
|
||||||
let anlage = dto.anlageId ? dto.anlageId : currentAnlage.id;
|
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')
|
if (!anlage) throw new NotFoundException('Anlage Id muss gesetzt sein')
|
||||||
|
|
||||||
let update = this.toDocument(dto, anlage);
|
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);
|
console.log(update);
|
||||||
const changedItem = await this.model.findByIdAndUpdate(id, {
|
const changedItem = await this.model.findByIdAndUpdate(id, {
|
||||||
$set: {
|
$set: {
|
||||||
@@ -69,6 +79,80 @@ export class SignalsService {
|
|||||||
return this.toDto(changedItem);
|
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<SignalResponseDto[]> {
|
||||||
|
if (!Array.isArray(dtos) || dtos.length === 0) throw new BadRequestException('Keine Zuordnungen übergeben');
|
||||||
|
const signalIds = new Set<string>();
|
||||||
|
const ioIds = new Set<string>();
|
||||||
|
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<SignalResponseDto> {
|
||||||
|
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) {
|
async remove(id: string) {
|
||||||
const removedItem = await this.model.findByIdAndDelete(id, { returnDocument: 'after', runValidators: true });
|
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 {
|
toDto(dbData: SignalDocument): SignalResponseDto {
|
||||||
return {
|
return {
|
||||||
|
|||||||
+3
-1
@@ -1,8 +1,10 @@
|
|||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import type { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||||
|
app.useBodyParser('json', { limit: '10mb' });
|
||||||
await app.listen(process.env.PORT ?? 3000);
|
await app.listen(process.env.PORT ?? 3000);
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
@@ -18,14 +18,20 @@ export class AnlageService {
|
|||||||
return item;
|
return item;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getSelected():Promise<AnlageDto> {
|
async getSelected(): Promise<AnlageDto> {
|
||||||
console.log('GetSelected Anlage')
|
console.log('GetSelected Anlage')
|
||||||
const item = await this.model.findOne({ selected: true }) as Anlage;
|
|
||||||
let ret:AnlageDto = {
|
const item = await this.model.findOne({ selected: true }).exec();
|
||||||
id:item._id.toString(),
|
|
||||||
anlageNr:item.anlageNr,
|
if (!item) {
|
||||||
name:item.name,
|
throw new NotFoundException('Es ist keine Anlage ausgewählt');
|
||||||
selected:item.selected
|
}
|
||||||
|
|
||||||
|
let ret: AnlageDto = {
|
||||||
|
id: item._id.toString(),
|
||||||
|
anlageNr: item.anlageNr,
|
||||||
|
name: item.name,
|
||||||
|
selected: item.selected
|
||||||
}
|
}
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
@@ -53,12 +59,12 @@ export class AnlageService {
|
|||||||
|
|
||||||
async setSelected(id: string) {
|
async setSelected(id: string) {
|
||||||
await this.model.updateMany(
|
await this.model.updateMany(
|
||||||
{ },
|
{},
|
||||||
{ $set: { selected: false } },
|
{ $set: { selected: false } },
|
||||||
).exec();
|
).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;
|
return anlage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user