unit template
This commit is contained in:
1 parent
bd850adcf5
commit
e284fae7b4
7 files changed
+299
-3
No files matched your search
@@ -0,0 +1,15 @@
|
||||
import { ComponentCreateDto } from './components';
|
||||
import { UnitTypeDto } from './units';
|
||||
import { TemplateSignal } from 'src/_schemas/anlagen/unit-template';
|
||||
|
||||
export class UnitTemplateDto {
|
||||
name!: string;
|
||||
type!: UnitTypeDto;
|
||||
info?: string;
|
||||
prefix?: string;
|
||||
bmk?: string;
|
||||
postfix?: string;
|
||||
components!: ComponentCreateDto[];
|
||||
signals!: TemplateSignal[];
|
||||
}
|
||||
export class SaveUnitTemplateDto { name!: string; }
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
|
||||
import { Types } from 'mongoose';
|
||||
import { Component, ComponentSchema } from './component';
|
||||
import { SignalType } from './singnals';
|
||||
import { UnitTypeDto } from 'src/_dto/anlagen/units';
|
||||
|
||||
@Schema({ _id: false })
|
||||
export class TemplateSignal {
|
||||
@Prop({ required: true }) componentIndex!: number;
|
||||
@Prop({ required: true }) name!: string;
|
||||
@Prop({ type: String, required: true, enum: Object.values(SignalType) }) type!: SignalType;
|
||||
@Prop() description?: string;
|
||||
}
|
||||
|
||||
@Schema({ timestamps: true, collection: 'unit_templates' })
|
||||
export class UnitTemplate {
|
||||
_id!: Types.ObjectId;
|
||||
@Prop({ required: true }) name!: string;
|
||||
@Prop({ type: String, required: true, enum: Object.values(UnitTypeDto) }) type!: UnitTypeDto;
|
||||
@Prop() info?: string;
|
||||
@Prop() prefix?: string;
|
||||
@Prop() bmk?: string;
|
||||
@Prop() postfix?: string;
|
||||
@Prop({ type: [ComponentSchema], default: [] }) components!: Component[];
|
||||
@Prop({ type: [SchemaFactory.createForClass(TemplateSignal)], default: [] }) signals!: TemplateSignal[];
|
||||
}
|
||||
export const UnitTemplateSchema = SchemaFactory.createForClass(UnitTemplate);
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
|
||||
import { UnitTemplatesService } from './unit-templates.service';
|
||||
import { SaveUnitTemplateDto, UnitTemplateDto } from 'src/_dto/anlagen/unit-templates';
|
||||
import { UnitCopyDto } from 'src/_dto/anlagen/units';
|
||||
|
||||
@Controller('rk2/unit-templates')
|
||||
export class UnitTemplatesController {
|
||||
constructor(private service: UnitTemplatesService) {}
|
||||
@Get() list() { return this.service.list(); }
|
||||
@Post() create(@Body() dto: UnitTemplateDto) { return this.service.save(dto); }
|
||||
@Post('from-unit/:id') fromUnit(@Param('id') id: string, @Body() dto: SaveUnitTemplateDto) { return this.service.fromUnit(id, dto?.name); }
|
||||
@Put(':id') update(@Param('id') id: string, @Body() dto: UnitTemplateDto) { return this.service.save(dto, id); }
|
||||
@Delete(':id') remove(@Param('id') id: string) { return this.service.remove(id); }
|
||||
@Post(':id/instantiate') instantiate(@Param('id') id: string, @Body() dto: UnitCopyDto) { return this.service.instantiate(id, dto); }
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { Types } from 'mongoose';
|
||||
import { UnitTemplatesService } from './unit-templates.service';
|
||||
import { UnitTypeDto } from '../../_dto/anlagen/units';
|
||||
import { SignalType } from '../../_schemas/anlagen/singnals';
|
||||
import { ComponentTypes } from '../../_dto/anlagen/components';
|
||||
import { model } from 'mongoose';
|
||||
import { UnitTemplateSchema } from '../../_schemas/anlagen/unit-template';
|
||||
|
||||
describe('UnitTemplatesService', () => {
|
||||
const anlageId = new Types.ObjectId();
|
||||
const sourceComponentId = new Types.ObjectId();
|
||||
const templateId = new Types.ObjectId();
|
||||
const template = {
|
||||
name: 'Standardband', type: UnitTypeDto.BAND, info: 'Vorlage', prefix: 'V',
|
||||
components: [{ _id: sourceComponentId, name: 'Motor', type: ComponentTypes.ANTRIEB, properties: { power: 5 } }],
|
||||
signals: [{ componentIndex: 0, name: 'Start', type: SignalType.DIGITAL_OUTPUT }],
|
||||
};
|
||||
let service: UnitTemplatesService;
|
||||
let templates: any;
|
||||
let units: any;
|
||||
let signals: any;
|
||||
let groups: any;
|
||||
let createdUnits: any[];
|
||||
let createdSignals: any[];
|
||||
const query = (value: unknown) => ({ exec: jest.fn().mockResolvedValue(value) });
|
||||
|
||||
beforeEach(() => {
|
||||
createdUnits = []; createdSignals = [];
|
||||
templates = { findById: jest.fn(() => query(template)), create: jest.fn(async data => ({ ...data, _id: templateId, toObject: () => data })) };
|
||||
units = jest.fn().mockImplementation(data => {
|
||||
const doc = { ...data, _id: new Types.ObjectId(), validate: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined) };
|
||||
createdUnits.push(doc); return doc;
|
||||
});
|
||||
units.deleteOne = jest.fn(() => query({}));
|
||||
signals = jest.fn().mockImplementation(data => {
|
||||
const doc = { ...data, _id: new Types.ObjectId(), validate: jest.fn().mockResolvedValue(undefined) };
|
||||
createdSignals.push(doc); return doc;
|
||||
});
|
||||
signals.insertMany = jest.fn().mockResolvedValue([]);
|
||||
signals.deleteMany = jest.fn(() => query({}));
|
||||
groups = { findOne: jest.fn(() => query(null)) };
|
||||
service = new UnitTemplatesService(templates, units, signals, groups,
|
||||
{ getSelected: jest.fn().mockResolvedValue({ id: anlageId.toString() }) } as any,
|
||||
{ toDto: (doc: any) => ({ id: doc._id.toString(), ...doc }) } as any);
|
||||
});
|
||||
|
||||
it('creates independent units with fresh component/signal IDs and empty IO assignments', async () => {
|
||||
await service.instantiate(templateId.toString(), { name: 'Band 01', bmk: 'B01' });
|
||||
await service.instantiate(templateId.toString(), { name: 'Band 02', bmk: 'B02' });
|
||||
expect(createdUnits[0].anlageId.equals(anlageId)).toBe(true);
|
||||
expect(createdUnits[0].name).toBe('Band 01');
|
||||
expect(createdUnits[0].bmk).toBe('B01');
|
||||
expect(createdUnits[0].prefix).toBe('V');
|
||||
expect(createdUnits[0].groupId).toBeUndefined();
|
||||
expect(createdUnits[0]._id.equals(createdUnits[1]._id)).toBe(false);
|
||||
expect(createdUnits[0].components[0]._id.equals(sourceComponentId)).toBe(false);
|
||||
expect(createdUnits[0].components[0]._id.equals(createdUnits[1].components[0]._id)).toBe(false);
|
||||
expect(createdSignals[0].componentId.equals(createdUnits[0].components[0]._id)).toBe(true);
|
||||
expect(createdSignals[0].anlageId.equals(anlageId)).toBe(true);
|
||||
expect(createdSignals[0].ioId).toBeNull();
|
||||
expect(createdSignals[0]._id.equals(createdSignals[1]._id)).toBe(false);
|
||||
expect(template.components[0]._id).toBe(sourceComponentId);
|
||||
});
|
||||
|
||||
it('rejects groups outside the selected plant before writing', async () => {
|
||||
await expect(service.instantiate(templateId.toString(), { name: 'Band', groupId: new Types.ObjectId().toString() })).rejects.toThrow(BadRequestException);
|
||||
expect(units).not.toHaveBeenCalled();
|
||||
expect(signals.insertMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cleans up only newly created records after partial signal insertion fails', async () => {
|
||||
signals.insertMany.mockRejectedValue(new Error('Insert failed'));
|
||||
await expect(service.instantiate(templateId.toString(), { name: 'Band' })).rejects.toThrow('Insert failed');
|
||||
expect(signals.deleteMany).toHaveBeenCalledWith({ _id: { $in: [createdSignals[0]._id] } });
|
||||
expect(units.deleteOne).toHaveBeenCalledWith({ _id: createdUnits[0]._id });
|
||||
});
|
||||
|
||||
it('rejects signal references to absent components', async () => {
|
||||
await expect(service.save({ ...template, signals: [{ componentIndex: 4, name: 'Start', type: SignalType.DIGITAL_OUTPUT }] })).rejects.toThrow(BadRequestException);
|
||||
expect(templates.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stores reusable data without source IDs, plant, group or IO references', async () => {
|
||||
await service.save({ ...template, anlageId, groupId: new Types.ObjectId(),
|
||||
signals: [{ ...template.signals[0], ioId: new Types.ObjectId() }],
|
||||
} as any);
|
||||
const data = templates.create.mock.calls[0][0];
|
||||
expect(data.anlageId).toBeUndefined();
|
||||
expect(data.groupId).toBeUndefined();
|
||||
expect(data.components[0]._id).toBeUndefined();
|
||||
expect(data.signals[0].ioId).toBeUndefined();
|
||||
expect(data.components[0].properties).toEqual({ power: 5 });
|
||||
});
|
||||
|
||||
it('snapshots saved units and maps signals to component positions', async () => {
|
||||
const unit = { ...template, _id: new Types.ObjectId(), anlageId, groupId: new Types.ObjectId() };
|
||||
units.findById = jest.fn(() => query(unit));
|
||||
signals.find = jest.fn(() => query([{ componentId: sourceComponentId, name: 'Start', type: SignalType.DIGITAL_OUTPUT, ioId: new Types.ObjectId() }]));
|
||||
await service.fromUnit(unit._id.toString(), 'Meine Vorlage');
|
||||
const data = templates.create.mock.calls[0][0];
|
||||
expect(data.name).toBe('Meine Vorlage');
|
||||
expect(data.signals).toEqual([{ componentIndex: 0, name: 'Start', type: SignalType.DIGITAL_OUTPUT, description: undefined }]);
|
||||
});
|
||||
|
||||
it('validates the actual template schema without a plant and rejects invalid signal types', async () => {
|
||||
const TemplateModel = model('UnitTemplateValidationTest', UnitTemplateSchema);
|
||||
await expect(new TemplateModel(template).validate()).resolves.toBeUndefined();
|
||||
await expect(new TemplateModel({ ...template, signals: [{ componentIndex: 0, name: 'Start', type: 'invalid' }] }).validate()).rejects.toThrow();
|
||||
expect(TemplateModel.collection.name).toBe('unit_templates');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { BadRequestException, Injectable, InternalServerErrorException, NotFoundException } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model, Types } from 'mongoose';
|
||||
import { UnitTemplate } from 'src/_schemas/anlagen/unit-template';
|
||||
import { Unit } from 'src/_schemas/anlagen/units';
|
||||
import { Signal } from 'src/_schemas/anlagen/singnals';
|
||||
import { Group } from 'src/_schemas/anlagen/groups';
|
||||
import { UnitTemplateDto } from 'src/_dto/anlagen/unit-templates';
|
||||
import { UnitCopyDto } from 'src/_dto/anlagen/units';
|
||||
import { AnlageService } from 'src/rk-anlagen/anlage/anlage.service';
|
||||
import { UnitsService } from './units.service';
|
||||
|
||||
@Injectable()
|
||||
export class UnitTemplatesService {
|
||||
constructor(
|
||||
@InjectModel(UnitTemplate.name, 'anlagen') private templates: Model<UnitTemplate>,
|
||||
@InjectModel(Unit.name, 'anlagen') private units: Model<Unit>,
|
||||
@InjectModel(Signal.name, 'anlagen') private signals: Model<Signal>,
|
||||
@InjectModel(Group.name, 'anlagen') private groups: Model<Group>,
|
||||
private anlagen: AnlageService, private unitService: UnitsService,
|
||||
) {}
|
||||
|
||||
private validId(id: string) {
|
||||
if (!Types.ObjectId.isValid(id)) throw new BadRequestException('Ungültige ID');
|
||||
}
|
||||
private validate(dto: UnitTemplateDto) {
|
||||
if (!dto || typeof dto.name !== 'string' || !dto.name.trim()) throw new BadRequestException('Name ist erforderlich');
|
||||
if (!Array.isArray(dto.components) || !Array.isArray(dto.signals)) throw new BadRequestException('Komponenten und Signale sind erforderlich');
|
||||
for (const key of ['info', 'prefix', 'bmk', 'postfix'] as const) {
|
||||
if (dto[key] !== undefined && typeof dto[key] !== 'string') throw new BadRequestException(`${key} muss Text sein`);
|
||||
}
|
||||
for (const signal of dto.signals) {
|
||||
if (!signal || !Number.isInteger(signal.componentIndex) || signal.componentIndex < 0 || signal.componentIndex >= dto.components.length) {
|
||||
throw new BadRequestException('Signal muss einer vorhandenen Komponente zugeordnet sein');
|
||||
}
|
||||
}
|
||||
// Nur Vorlagendaten übernehmen; übermittelte IDs und Anlagenzuordnungen ignorieren.
|
||||
return {
|
||||
name: dto.name.trim(), type: dto.type, info: dto.info, prefix: dto.prefix, bmk: dto.bmk, postfix: dto.postfix,
|
||||
components: dto.components.map(c => ({ name: c.name, type: c.type, prefix: c.prefix, postfix: c.postfix, index: c.index, properties: c.properties })),
|
||||
signals: dto.signals.map(s => ({ componentIndex: s.componentIndex, name: s.name, type: s.type, description: s.description })),
|
||||
};
|
||||
}
|
||||
async list() {
|
||||
return (await this.templates.find().sort({ name: 1 }).exec()).map(t => ({ ...t.toObject(), id: t._id.toString() }));
|
||||
}
|
||||
async save(dto: UnitTemplateDto, id?: string) {
|
||||
const data = this.validate(dto);
|
||||
if (id) {
|
||||
this.validId(id);
|
||||
const result = await this.templates.findByIdAndUpdate(id, { $set: data }, { returnDocument: 'after', runValidators: true }).exec();
|
||||
if (!result) throw new NotFoundException('Vorlage nicht gefunden');
|
||||
return { ...result.toObject(), id: result._id.toString() };
|
||||
}
|
||||
const result = await this.templates.create(data);
|
||||
return { ...result.toObject(), id: result._id.toString() };
|
||||
}
|
||||
async fromUnit(id: string, name: string) {
|
||||
this.validId(id);
|
||||
const unit = await this.units.findById(id).exec();
|
||||
if (!unit) throw new NotFoundException('Unit nicht gefunden');
|
||||
const anlage = await this.anlagen.getSelected();
|
||||
if (unit.anlageId.toString() !== anlage.id) throw new BadRequestException('Unit gehört nicht zur ausgewählten Anlage');
|
||||
const signals = await this.signals.find({ anlageId: unit.anlageId, componentId: { $in: unit.components.map(c => c._id!) } }).exec();
|
||||
return this.save({ ...this.unitService.toDto(unit), name,
|
||||
signals: signals.map(s => ({ componentIndex: unit.components.findIndex(c => c._id!.toString() === s.componentId!.toString()), name: s.name, type: s.type, description: s.description })),
|
||||
});
|
||||
}
|
||||
async remove(id: string) {
|
||||
this.validId(id);
|
||||
if (!await this.templates.findByIdAndDelete(id).exec()) throw new NotFoundException('Vorlage nicht gefunden');
|
||||
return { success: true };
|
||||
}
|
||||
async instantiate(id: string, dto: UnitCopyDto) {
|
||||
this.validId(id);
|
||||
if (!dto || typeof dto.name !== 'string' || !dto.name.trim()) throw new BadRequestException('Name ist erforderlich');
|
||||
for (const key of ['prefix', 'bmk', 'postfix'] as const) {
|
||||
if (dto[key] !== undefined && typeof dto[key] !== 'string') throw new BadRequestException(`${key} muss Text sein`);
|
||||
}
|
||||
const template = await this.templates.findById(id).exec();
|
||||
if (!template) throw new NotFoundException('Vorlage nicht gefunden');
|
||||
const anlageId = new Types.ObjectId((await this.anlagen.getSelected()).id);
|
||||
let groupId: Types.ObjectId | undefined;
|
||||
if (dto.groupId !== undefined && dto.groupId !== null && dto.groupId !== '') {
|
||||
if (typeof dto.groupId !== 'string') throw new BadRequestException('Ungültige Gruppe');
|
||||
this.validId(dto.groupId);
|
||||
const group = await this.groups.findOne({ _id: dto.groupId, anlageId }).exec();
|
||||
if (!group) throw new BadRequestException('Gruppe gehört nicht zur ausgewählten Anlage');
|
||||
groupId = group._id;
|
||||
}
|
||||
const components = template.components.map(c => ({
|
||||
_id: new Types.ObjectId(), name: c.name, type: c.type, prefix: c.prefix, postfix: c.postfix, index: c.index, properties: c.properties,
|
||||
}));
|
||||
const unit = new this.units({ anlageId, groupId, name: dto.name.trim(), type: template.type, info: template.info,
|
||||
prefix: dto.prefix ?? template.prefix, bmk: dto.bmk ?? template.bmk, postfix: dto.postfix ?? template.postfix, components });
|
||||
const signals = template.signals.map(s => {
|
||||
if (!components[s.componentIndex]) throw new BadRequestException('Ungültige Signalzuordnung in der Vorlage');
|
||||
return new this.signals({ anlageId, componentId: components[s.componentIndex]._id, name: s.name, type: s.type, description: s.description, ioId: null });
|
||||
});
|
||||
await unit.validate();
|
||||
for (const signal of signals) await signal.validate();
|
||||
try {
|
||||
await unit.save();
|
||||
if (signals.length) await this.signals.insertMany(signals, { ordered: true });
|
||||
return this.unitService.toDto(unit);
|
||||
} catch (error) {
|
||||
try {
|
||||
await this.signals.deleteMany({ _id: { $in: signals.map(s => s._id) } }).exec();
|
||||
await this.units.deleteOne({ _id: unit._id }).exec();
|
||||
} catch {
|
||||
throw new InternalServerErrorException(`Einfügen fehlgeschlagen; Bereinigung der Unit ${unit._id} unvollständig. Bitte prüfen.`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,14 @@ import { Unit, UnitSchema } from 'src/_schemas/anlagen/units';
|
||||
import { AnlageModule } from 'src/rk-anlagen/anlage/anlage.module';
|
||||
import { Signal, SignalSchema } from 'src/_schemas/anlagen/singnals';
|
||||
import { Group, GroupSchema } from 'src/_schemas/anlagen/groups';
|
||||
import { UnitTemplate, UnitTemplateSchema } from 'src/_schemas/anlagen/unit-template';
|
||||
import { UnitTemplatesService } from './unit-templates.service';
|
||||
import { UnitTemplatesController } from './unit-templates.controller';
|
||||
|
||||
@Module({
|
||||
imports: [MongooseModule.forFeature([{ name: Unit.name, schema: UnitSchema }, { name: Signal.name, schema: SignalSchema }, { name: Group.name, schema: GroupSchema }], "anlagen"), AnlageModule],
|
||||
imports: [MongooseModule.forFeature([{ name: Unit.name, schema: UnitSchema }, { name: Signal.name, schema: SignalSchema }, { name: Group.name, schema: GroupSchema }, { name: UnitTemplate.name, schema: UnitTemplateSchema }], "anlagen"), AnlageModule],
|
||||
|
||||
providers: [UnitsService],
|
||||
controllers: [UnitsController]
|
||||
providers: [UnitsService, UnitTemplatesService],
|
||||
controllers: [UnitsController, UnitTemplatesController]
|
||||
})
|
||||
export class UnitsModule { }
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"rootDir": "../src",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": "unit-templates\\.service\\.spec\\.ts$",
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"moduleNameMapper": { "^src/(.*)$": "<rootDir>/$1" },
|
||||
"transform": { "^.+\\.(t|j)s$": ["ts-jest", { "tsconfig": { "module": "commonjs", "moduleResolution": "node", "isolatedModules": false, "resolvePackageJsonExports": false, "types": ["node", "express", "multer", "jest"] } }] }
|
||||
}
|
||||
Reference in new issue
Block a user