diff --git a/apps/backend/_test/unified-articles.http b/apps/backend/_test/unified-articles.http new file mode 100644 index 0000000..316f3d3 --- /dev/null +++ b/apps/backend/_test/unified-articles.http @@ -0,0 +1,51 @@ +@api = http://192.168.50.205/api + +### Banane ohne Hersteller und Varianten +POST {{api}}/articles +Content-Type: application/json + +{ + "articleNumber": "OBST-001", + "name": "Banane, frisch", + "baseUnit": "Stück", + "isConsumable": true, + "trackingMode": "quantity", + "tracksExpiryDate": false, + "attributes": { "Bio": true }, + "packaging": [] +} + +### Milch mit Verpackung und Ablaufverfolgung +POST {{api}}/articles +Content-Type: application/json + +{ + "articleNumber": "MILCH-001", + "name": "Vollmilch, 3,5 % Fett", + "baseUnit": "Liter", + "isConsumable": true, + "trackingMode": "batch", + "tracksExpiryDate": true, + "attributes": { "Fettgehalt": 3.5 }, + "packaging": [{ "name": "1-Liter-Packung", "quantityInBaseUnits": 1 }] +} + +### Raspberry Pi mit Einzelstückführung +POST {{api}}/articles +Content-Type: application/json + +{ + "articleNumber": "ELEK-001", + "name": "Raspberry Pi 5, 8 GB RAM", + "baseUnit": "Stück", + "isConsumable": false, + "trackingMode": "individual", + "tracksExpiryDate": false, + "attributes": { "Arbeitsspeicher GB": 8 } +} + +### Übersicht +GET {{api}}/articles + +### Migrationsstatus +GET {{api}}/articles/migration-status diff --git a/apps/backend/package.json b/apps/backend/package.json index afabe0b..4353752 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -18,7 +18,8 @@ "test:watch": "jest --watch", "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", - "test:e2e": "jest --config ./test/jest-e2e.json" + "test:e2e": "jest --config ./test/jest-e2e.json", + "articles:migration": "ts-node --project tsconfig.scripts.json scripts/migrate-articles.ts" }, "dependencies": { "@nestjs/common": "^11.0.1", diff --git a/apps/backend/scripts/article-migration-review.example.json b/apps/backend/scripts/article-migration-review.example.json new file mode 100644 index 0000000..a4269d3 --- /dev/null +++ b/apps/backend/scripts/article-migration-review.example.json @@ -0,0 +1,23 @@ +{ + "articles": { + "000000000000000000000001": { + "articleNumber": "FLEISCH-001", + "name": "Schweinehals, ohne Knochen", + "baseUnit": "kg", + "isConsumable": true, + "trackingMode": "batch", + "tracksExpiryDate": false, + "packaging": [] + }, + "000000000000000000000002": { + "articleNumber": "MILCH-001", + "name": "Vollmilch, 3,5 % Fett", + "baseUnit": "Liter", + "isConsumable": true, + "trackingMode": "batch", + "tracksExpiryDate": true, + "packaging": [{ "name": "1-Liter-Packung", "quantityInBaseUnits": 1 }] + } + }, + "movements": {} +} diff --git a/apps/backend/scripts/migrate-articles.ts b/apps/backend/scripts/migrate-articles.ts new file mode 100644 index 0000000..9183f4d --- /dev/null +++ b/apps/backend/scripts/migrate-articles.ts @@ -0,0 +1,468 @@ +/** Read-only unless --apply is explicitly passed. Never imported by the application. */ +import { readFileSync } from 'node:fs'; +import mongoose, { Types } from 'mongoose'; + +type TrackingMode = 'quantity' | 'batch' | 'individual'; +interface ArticleSettings { + articleNumber: string; + name?: string; + manufacturerArticleNumber?: string; + barcode?: string; + baseUnit: string; + isConsumable: boolean; + trackingMode: TrackingMode; + tracksExpiryDate: boolean; + packaging?: { name: string; quantityInBaseUnits: number; barcode?: string }[]; +} +interface Review { + articles: Record; + movements?: Record; +} +interface LegacyArticle { + _id: Types.ObjectId; + name: string; + categoryId?: Types.ObjectId; + attributes?: Record; + articleNumber?: string; +} +interface LegacyVariant { + _id: Types.ObjectId; + articleId: Types.ObjectId; + manufacturerId?: Types.ObjectId; + supplierArticleNumber?: string; + packagingUnit?: string; + extra?: Record; +} +interface LegacyContent { + _id: Types.ObjectId; + articleVariantId?: Types.ObjectId; + stockId: Types.ObjectId; + quantity: number; + batchNumber?: string; + expiryDate?: Date; + area?: string; + articleId?: Types.ObjectId; +} +interface LegacyMovement { + _id: Types.ObjectId; + articleVariantId?: Types.ObjectId; + stockId: Types.ObjectId; + type: string; + meta?: { fromLocationId?: Types.ObjectId; toLocationId?: Types.ObjectId }; + articleId?: Types.ObjectId; +} +interface ConcreteArticle extends ArticleSettings { + _id: Types.ObjectId; + categoryId?: Types.ObjectId; + groupId?: Types.ObjectId; + manufacturerId?: Types.ObjectId; + manufacturerArticleNumber?: string; + attributes: Record; + archivedAt: null; +} + +async function main() { + const uri = process.env.MONGODB_URI; + const reviewPath = process.argv + .find((argument) => argument.startsWith('--review=')) + ?.slice('--review='.length); + if (!uri || !reviewPath) + throw new Error( + 'MONGODB_URI und --review=/pfad/review.json sind erforderlich', + ); + const review = JSON.parse(readFileSync(reviewPath, 'utf8')) as Review; + if (!review.articles || typeof review.articles !== 'object') + throw new Error('review.articles fehlt'); + const apply = process.argv.includes('--apply'); + await mongoose.connect(uri, { autoIndex: false }); + try { + const connection = mongoose.connection; + const [articles, variants, contents, movements, stocks] = await Promise.all( + [ + connection.collection('articles').find().toArray(), + connection + .collection('articlevariants') + .find() + .toArray(), + connection.collection('stockcontents').find().toArray(), + connection + .collection('stockmovements') + .find() + .toArray(), + connection.collection('stocks').find().toArray(), + ], + ); + const articleMap = new Map( + articles.map((article) => [article._id.toString(), article]), + ); + const variantMap = new Map( + variants.map((variant) => [variant._id.toString(), variant]), + ); + const stockIds = new Set(stocks.map((stock) => stock._id.toString())); + const blockers: string[] = []; + const plannedArticles: ConcreteArticle[] = []; + const groups = new Map(); + const plan = ( + id: Types.ObjectId, + parent: LegacyArticle, + variant?: LegacyVariant, + ) => { + if (articleMap.get(id.toString())?.articleNumber) return; + const settings = review.articles[id.toString()]; + if (!settings) { + blockers.push( + `Artikel ${id}: Einheit und Bestandsregeln fehlen im Review (${parent.name})`, + ); + return; + } + if ( + !settings.articleNumber?.trim() || + !settings.baseUnit?.trim() || + typeof settings.isConsumable !== 'boolean' || + typeof settings.tracksExpiryDate !== 'boolean' || + !['quantity', 'batch', 'individual'].includes(settings.trackingMode) || + (settings.tracksExpiryDate && settings.trackingMode !== 'batch') + ) { + blockers.push(`Artikel ${id}: ungültige Einstellungen`); + return; + } + if (settings.trackingMode === 'individual') { + blockers.push( + `Artikel ${id}: bestehende Einzelstücke müssen zuerst separat mit Inventarnummern zugeordnet werden; zunächst quantity verwenden`, + ); + return; + } + const attributes = { + ...parent.attributes, + ...variant?.extra, + ...(variant?.supplierArticleNumber + ? { legacySupplierArticleNumber: variant.supplierArticleNumber } + : {}), + }; + if ( + Object.entries(attributes).some( + ([key, value]) => + key.includes('.') || + key.startsWith('$') || + ['__proto__', 'constructor', 'prototype'].includes(key) || + !['string', 'number', 'boolean'].includes(typeof value), + ) + ) { + blockers.push( + `Artikel ${id}: Eigenschaften müssen vor der Migration auf einfache Werte bereinigt werden`, + ); + } + if ( + settings.packaging?.some( + (item) => + !item.name?.trim() || + !Number.isFinite(item.quantityInBaseUnits) || + item.quantityInBaseUnits <= 0, + ) + ) { + blockers.push(`Artikel ${id}: Verpackungen sind ungültig`); + } + if ( + variant && + articleMap.has(id.toString()) && + !articleMap.get(id.toString())?.articleNumber + ) { + blockers.push( + `Artikel ${id}: Varianten-ID kollidiert mit einer bisherigen Artikel-ID`, + ); + } + if (variant) + groups.set(parent._id.toString(), { + _id: parent._id, + name: parent.name, + }); + plannedArticles.push({ + _id: id, + articleNumber: settings.articleNumber.trim(), + name: settings.name ?? parent.name, + baseUnit: settings.baseUnit.trim(), + isConsumable: settings.isConsumable, + trackingMode: settings.trackingMode, + tracksExpiryDate: settings.tracksExpiryDate, + packaging: settings.packaging ?? [], + categoryId: parent.categoryId, + manufacturerArticleNumber: settings.manufacturerArticleNumber, + barcode: settings.barcode, + ...(variant + ? { groupId: parent._id, manufacturerId: variant.manufacturerId } + : {}), + attributes, + archivedAt: null, + }); + if (variant?.packagingUnit && !settings.packaging) { + blockers.push( + `Artikel ${id}: bisherige Verpackung "${variant.packagingUnit}" muss im Review strukturiert angegeben werden`, + ); + } + }; + for (const variant of variants) { + const parent = articleMap.get(variant.articleId.toString()); + if (!parent) + blockers.push(`Variante ${variant._id}: übergeordneter Artikel fehlt`); + else plan(variant._id, parent, variant); + } + const parentIds = new Set( + variants.map((variant) => variant.articleId.toString()), + ); + for (const article of articles) { + if (!article.articleNumber && !parentIds.has(article._id.toString())) + plan(article._id, article); + } + const concrete = new Map([ + ...articles + .filter((article) => article.articleNumber) + .map( + (article) => + [ + article._id.toString(), + article as unknown as ArticleSettings, + ] as const, + ), + ...plannedArticles.map( + (article) => [article._id.toString(), article] as const, + ), + ]); + const numbers = new Set(); + for (const settings of concrete.values()) { + if (numbers.has(settings.articleNumber)) + blockers.push(`Doppelte Artikelnummer ${settings.articleNumber}`); + numbers.add(settings.articleNumber); + } + const batches = new Map< + string, + { + _id: Types.ObjectId; + articleId: Types.ObjectId; + batchNumber: string; + expiryDate?: Date; + } + >(); + const migratedContent: { + _id: Types.ObjectId; + articleId: Types.ObjectId; + batchId: Types.ObjectId | null; + area: string; + }[] = []; + const positionKeys = new Set( + contents + .filter((content) => content.articleId) + .map( + (content) => + `${content.articleId}:${content.stockId}:${(content as unknown as { batchId?: Types.ObjectId }).batchId ?? ''}:${content.area ?? ''}`, + ), + ); + for (const content of contents) { + if (content.articleId) continue; + const id = content.articleVariantId; + const settings = id && concrete.get(id.toString()); + if ( + !id || + !settings || + !stockIds.has(content.stockId.toString()) || + !Number.isFinite(content.quantity) || + content.quantity <= 0 + ) { + blockers.push( + `Bestand ${content._id}: Referenz, Lager oder Menge ist ungültig`, + ); + continue; + } + let batchId: Types.ObjectId | null = null; + if (settings.trackingMode === 'batch') { + if ( + !content.batchNumber?.trim() || + (settings.tracksExpiryDate && !content.expiryDate) + ) { + blockers.push( + `Bestand ${content._id}: Chargennummer oder Ablaufdatum fehlt`, + ); + continue; + } + if (content.expiryDate && !settings.tracksExpiryDate) { + blockers.push( + `Bestand ${content._id}: vorhandenes Ablaufdatum erfordert tracksExpiryDate=true`, + ); + continue; + } + const key = `${id}:${content.batchNumber.trim()}`; + let batch = batches.get(key); + if ( + batch && + batch.expiryDate?.getTime() !== content.expiryDate?.getTime() + ) { + blockers.push(`Charge ${key}: widersprüchliche Ablaufdaten`); + continue; + } + if (!batch) { + batch = { + _id: new Types.ObjectId(), + articleId: id, + batchNumber: content.batchNumber.trim(), + ...(settings.tracksExpiryDate + ? { expiryDate: content.expiryDate } + : {}), + }; + batches.set(key, batch); + } + batchId = batch._id; + } else if (content.batchNumber || content.expiryDate) { + blockers.push( + `Bestand ${content._id}: vorhandene Chargeninformationen erfordern Chargenführung`, + ); + continue; + } + const positionKey = `${id}:${content.stockId}:${batchId ?? ''}:${content.area ?? ''}`; + if (positionKeys.has(positionKey)) + blockers.push( + `Bestand ${content._id}: doppelte Bestandsposition; zuerst konsolidieren`, + ); + positionKeys.add(positionKey); + migratedContent.push({ + _id: content._id, + articleId: id, + batchId, + area: content.area ?? '', + }); + } + const migratedMovements: { + _id: Types.ObjectId; + articleId: Types.ObjectId; + stockId: Types.ObjectId; + toStockId?: Types.ObjectId; + }[] = []; + for (const movement of movements) { + if (movement.articleId) continue; + const override = review.movements?.[movement._id.toString()]; + const articleId = override + ? new Types.ObjectId(override.articleId) + : movement.articleVariantId; + const stockId = override + ? new Types.ObjectId(override.stockId) + : movement.stockId; + if ( + !articleId || + !concrete.has(articleId.toString()) || + !stockIds.has(stockId.toString()) || + (!variantMap.has(articleId.toString()) && !override) + ) { + blockers.push( + `Bewegung ${movement._id}: alte Referenzen sind ungültig; review.movements benötigt articleId und stockId`, + ); + continue; + } + const toStockId = + movement.type === 'TRANSFER' ? movement.meta?.toLocationId : undefined; + if ( + movement.type === 'TRANSFER' && + (!toStockId || !stockIds.has(toStockId.toString())) + ) { + blockers.push( + `Bewegung ${movement._id}: Ziellager fehlt oder ist ungültig`, + ); + continue; + } + migratedMovements.push({ + _id: movement._id, + articleId, + stockId, + ...(toStockId ? { toStockId } : {}), + }); + } + console.log( + JSON.stringify( + { + mode: apply ? 'apply' : 'preview', + articles: plannedArticles, + groups: [...groups.values()], + contents: migratedContent.length, + movements: migratedMovements.length, + blockers, + }, + null, + 2, + ), + ); + if (blockers.length) + throw new Error( + 'Migration blockiert. Review und bestehende Daten korrigieren; keine Änderungen ausgeführt.', + ); + if (!apply) return; + await connection.transaction(async (session) => { + for (const [collection, rows] of [ + ['articles', articles], + ['articlevariants', variants], + ['stockcontents', contents], + ['stockmovements', movements], + ] as const) { + for (const row of rows) + await connection + .collection(`migration_backup_${collection}`) + .updateOne( + { _id: row._id }, + { $setOnInsert: row }, + { upsert: true, session }, + ); + } + for (const group of groups.values()) + await connection + .collection('articlegroups') + .updateOne( + { _id: group._id }, + { $setOnInsert: group }, + { upsert: true, session }, + ); + for (const group of groups.values()) + await connection + .collection('articles') + .updateOne( + { _id: group._id }, + { $set: { legacyGrouping: true } }, + { session }, + ); + for (const article of plannedArticles) { + const { _id, ...values } = article; + await connection + .collection('articles') + .updateOne({ _id }, { $set: values }, { upsert: true, session }); + } + for (const batch of batches.values()) + await connection.collection('batches').insertOne(batch, { session }); + for (const content of migratedContent) { + const { _id, ...values } = content; + await connection.collection('stockcontents').updateOne( + { _id }, + { + $set: { ...values, assetId: null }, + $unset: { articleVariantId: '', batchNumber: '', expiryDate: '' }, + }, + { session }, + ); + } + for (const movement of migratedMovements) { + const { _id, ...values } = movement; + await connection.collection('stockmovements').updateOne( + { _id }, + { + $set: values, + $unset: { articleVariantId: '' }, + }, + { session }, + ); + } + }); + console.log( + 'Migration abgeschlossen. Legacy-Datensätze und Sicherungskopien bleiben erhalten.', + ); + } finally { + await mongoose.disconnect(); + } +} +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +}); diff --git a/apps/backend/src/app.module.ts b/apps/backend/src/app.module.ts index 418965f..a2d72b7 100644 --- a/apps/backend/src/app.module.ts +++ b/apps/backend/src/app.module.ts @@ -6,19 +6,21 @@ import { MongooseModule } from '@nestjs/mongoose'; import { LocationsModule } from './locations/locations.module'; import { UsersModule } from './users/users.module'; -import { CatalogModule } from './catalog/catalog.module'; +import { ProductsModule } from './products/products.module'; import { InventoryModule } from './inventory/inventory.module'; import { ChatGateway } from './chat.gateway'; @Module({ - imports: [MongooseModule.forRoot('mongodb://192.168.50.206/nest'), - CatalogModule, + imports: [ + MongooseModule.forRoot( + process.env.MONGODB_URI ?? 'mongodb://192.168.50.206/nest', + ), + ProductsModule, InventoryModule, UsersModule, - LocationsModule, + LocationsModule, ], //controllers: [AppController], - providers: [ChatGateway,LocationsModule], + providers: [ChatGateway, LocationsModule], }) -export class AppModule { } - \ No newline at end of file +export class AppModule {} diff --git a/apps/backend/src/catalog/_dto/article.dto.ts b/apps/backend/src/catalog/_dto/article.dto.ts deleted file mode 100644 index a5d9b4d..0000000 --- a/apps/backend/src/catalog/_dto/article.dto.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { Types } from 'mongoose'; -import { PartialType } from '@nestjs/mapped-types'; - -import { CategoryDto } from './category.dto'; -import { ManufacturerDto } from './manufacturer.dto'; -import { Type } from "class-transformer"; -import { IsArray, IsMongoId, IsObject, IsOptional, IsString, ValidateNested } from "class-validator"; - - - - - -export class ArticleDto { - _id: Types.ObjectId; - name: string; - category: CategoryDto; - attributes?: Record; - variants: ArticleVariantDto[] -} - - -export class ArticleAndVariantsDto { - _id: Types.ObjectId; - name: string; - categoryId: Types.ObjectId; - attributes?: Record; - variants: { - _id:Types.ObjectId; - manufacturerId: Types.ObjectId; - supplierArticleNumber?: string; - packagingUnit?: string; - extra?: Record; - }[] -} - -export class ArticleVariantBaseDto { - _id: Types.ObjectId; - article: ArticleDto; - manufacturer: ManufacturerDto; - supplierArticleNumber?: string; - packagingUnit?: string; - extra?: Record; -} - - - - - -export class ArticleVariantDto { - @IsMongoId() - manufacturerId: string; - - @IsOptional() - @IsString() - supplierArticleNumber?: string; - - @IsOptional() - @IsString() - packagingUnit?: string; - - @IsOptional() - @IsObject() - extra?: Record; -} - - -export class ArticleCreateDto { - @IsString() - name: string; - - @IsMongoId() - categoryId: string; - - @IsOptional() - @IsObject() - attributes?: Record; - - - @IsArray() - @ValidateNested({ each: true }) - @Type(() => ArticleVariantDto) - variants: ArticleVariantDto[]; -} - -export class ArticleUpdateDto extends PartialType(ArticleCreateDto) {} \ No newline at end of file diff --git a/apps/backend/src/catalog/_dto/upsert-article.dto.ts b/apps/backend/src/catalog/_dto/upsert-article.dto.ts deleted file mode 100644 index d1c1a99..0000000 --- a/apps/backend/src/catalog/_dto/upsert-article.dto.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { Type } from "class-transformer"; -import { IsArray, IsBoolean, IsMongoId, IsObject, IsOptional, IsString, ValidateNested } from "class-validator"; - -export class ArticleVariantUpsertDto { - @IsOptional() - @IsMongoId() - _id: string; - - @IsOptional() - @IsMongoId() - manufacturerId: string; - - @IsOptional() - @IsString() - supplierArticleNumber?: string; - - @IsOptional() - @IsString() - packagingUnit?: string; - - @IsOptional() - @IsObject() - extra?: Record; - - @IsOptional() - @IsBoolean() - deleted?: boolean; -} - -export class ArticleUpsertDto { - @IsOptional() - //@IsMongoId() - _id: string; - - - @IsOptional() - @IsString() - name: string; - - @IsOptional() - @IsMongoId() - categoryId: string; - - @IsOptional() - @IsObject() - attributes?: Record; - - - @IsOptional() - @IsArray() - @ValidateNested({ each: true }) - @Type(() => ArticleVariantUpsertDto) - variants: ArticleVariantUpsertDto[]; -} diff --git a/apps/backend/src/catalog/_entities/article.entity.ts b/apps/backend/src/catalog/_entities/article.entity.ts deleted file mode 100644 index 119b6a3..0000000 --- a/apps/backend/src/catalog/_entities/article.entity.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; -import { Document, Types } from 'mongoose'; - -@Schema({ timestamps: true }) -export class Article extends Document { - @Prop({ required: true }) - name: string; - - @Prop({ type: Types.ObjectId, ref: 'Category', required: true }) - categoryId: Types.ObjectId; - - @Prop({ type: Map, of: String }) - attributes?: Map; - -} - - - -export const ArticleSchema = SchemaFactory.createForClass(Article); - -ArticleSchema.virtual('varianten', { - ref: 'ArticleVariant', - localField: '_id', - foreignField: 'articleId', -}); - -ArticleSchema.set('toJSON', { virtuals: true }); -ArticleSchema.set('toObject', { virtuals: true }); \ No newline at end of file diff --git a/apps/backend/src/catalog/articles/articles.service.ts b/apps/backend/src/catalog/articles/articles.service.ts deleted file mode 100644 index 2bc748d..0000000 --- a/apps/backend/src/catalog/articles/articles.service.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Injectable, NotFoundException } from '@nestjs/common'; - - -import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; -import { Article } from '../_entities/article.entity'; -import { ArticleRepository } from './repository/article.repository'; -import { ArticleAndVariantsDto, ArticleDto, ArticleUpdateDto,ArticleCreateDto } from '../_dto/article.dto'; - -import { ArticleUpsertDto } from '../_dto/upsert-article.dto'; - - -@Injectable() -export class ArticlesService { - constructor( - @InjectModel(Article.name) private articleModel: Model
, - private readonly articleRepository: ArticleRepository - ) { } - - create(dto: ArticleCreateDto) { - return this.articleRepository.creatArticle(dto); - - } - - async findAll(): Promise { - return this.articleRepository.findAll(); - } - - async findOne(id: string): Promise { - const article = await this.articleRepository.findOne(id); - - - - - return article; - - } - - update(id: string, dto: ArticleUpsertDto) { - console.log('update service') - return this.articleRepository.updateArticle(id,dto); - } - - async remove(id: string) { - console.log('all variants deleted') - return this.articleRepository.deleteArticle(id); - - - //return this.articleModel.findByIdAndDelete(id); - } -} diff --git a/apps/backend/src/catalog/articles/querys/article-get.query.ts b/apps/backend/src/catalog/articles/querys/article-get.query.ts deleted file mode 100644 index c27f0bd..0000000 --- a/apps/backend/src/catalog/articles/querys/article-get.query.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { Types } from "mongoose"; - -export const articleGetQuery = [ - { - $lookup: { - from: 'articlevariants', - localField: '_id', - foreignField: 'articleId', - as: 'varianten', - }, - }, - { - $lookup: { - from: 'manufacturers', - localField: 'varianten.manufacturerId', - foreignField: '_id', - as: 'manufacturer', - }, - }, - { - $lookup: { - from: 'categories', - localField: 'categoryId', - foreignField: '_id', - as: 'category', - }, - }, - { - $unwind: { - path: '$category', - preserveNullAndEmptyArrays: true - }, - }, - { - $project: { - name: 1, - category: { - _id: '$category._id', - name: '$category.name', - isConsumable: '$category.isConsumable' - }, - - variants: { - $map: { - input: '$varianten', - as: 'v', - in: { - _id: '$$v._id', - packagingUnit: '$$v.packagingUnit', - manufacturer: { - $arrayElemAt: [ - { - $filter: { - input: '$manufacturer', - as: 'm', - cond: { - $eq: [ - '$$m._id', - { $toObjectId: '$$v.manufacturerId' } - ] - } - } - }, - 0 - ] - } - } - } - } - - } - } - -]; - -export const articleGetQuery2 = [ - { - $lookup: { - from: 'articlevariants', - localField: '_id', - foreignField: 'articleId', - as: 'varianten', - }, - }, - { - $lookup: { - from: 'manufacturers', - localField: 'varianten.manufacturerId', - foreignField: '_id', - as: 'manufacturer', - }, - }, - { $unwind: '$manufacturer' }, - { - $lookup: { - from: 'categories', - localField: 'categoryId', - foreignField: '_id', - as: 'category', - }, - }, - { - $unwind: { - path: '$category', - preserveNullAndEmptyArrays: true - }, - }, - - { - $project: { - name: 1, - category: { - _id: '$category._id', - name: '$category.name', - isConsumable: 1, - }, - varianten: { - _id: 1, - manufacturer: { - _id: '$manufacturer._id', - name: '$manufacturer.name', - }, - packagingUnit: 1 - - } - } - } - -]; \ No newline at end of file diff --git a/apps/backend/src/catalog/articles/repository/article.repository.ts b/apps/backend/src/catalog/articles/repository/article.repository.ts deleted file mode 100644 index e79f903..0000000 --- a/apps/backend/src/catalog/articles/repository/article.repository.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { Injectable, NotFoundException, ConflictException } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; - -import { ArticleCreateDto, ArticleDto } from 'src/catalog/_dto/article.dto'; -import { Article } from 'src/catalog/_entities/article.entity'; -import { ArticleVariantRepository } from 'src/catalog/article-variant/repository/article-variant.repository'; -import { articleGetQuery } from '../querys/article-get.query'; - -import { ArticleUpsertDto, ArticleVariantUpsertDto } from 'src/catalog/_dto/upsert-article.dto'; - -@Injectable() -export class ArticleRepository { - - constructor( - @InjectModel(Article.name) - private articleModel: Model
, - private readonly articleVariantRepository: ArticleVariantRepository - - ) { } - - async findAll(): Promise { - const res = await this.articleModel.aggregate( - [...articleGetQuery]); - - return res; - } - - async findOne(id: string): Promise { - const res = await this.articleModel.aggregate( - [{ $match: { _id: new Types.ObjectId(id) } } - , ...articleGetQuery]); - - return res[0]; - } - - async creatArticle(dto: ArticleCreateDto) { - const { name, variants, categoryId, attributes } = dto; - - - const isSameName = await this.articleModel.findOne({ name: name }); - if (isSameName) throw new ConflictException("Name ist arlready exsist!"); - - const newArticle = await this.articleModel.create({ name, categoryId: new Types.ObjectId(categoryId), attributes }) - - - const variantsWithNewArticleId = variants.map((variant) => ( - { - packagingUnit: variant.packagingUnit, - manufacturerId: new Types.ObjectId(variant.manufacturerId), - articleId: newArticle._id - } - )); - - await this.articleVariantRepository.createMany(variantsWithNewArticleId) - - return this.findOne(newArticle.id); - - } - - async updateArticle(id: string, dto: ArticleUpsertDto) { - const { name, variants, categoryId, attributes } = dto; - - - const article = await this.articleModel.findOne({ _id: id }); - - if (!article) throw new NotFoundException("Article nicht gefunden"); - - if (dto.name !== undefined) article.name = dto.name; - if (dto.categoryId !== undefined) article.categoryId = new Types.ObjectId(dto.categoryId); - if (dto.attributes !== undefined) { article.attributes = new Map(Object.entries(dto.attributes));} - - article.updateOne({ - $set:{ - name,categoryId,attributes - } - }); - article.save(); - - - await this.articleVariantRepository.upsertVariants(id,variants) - - return this.findOne(id); - - } - - async deleteArticle(id: string) { - - const article = await this.findOne(id); - - if (true) throw new NotFoundException("deleteArticle Not Supportet jet"); - if (!article) throw new NotFoundException("Article nicht gefunden"); - - /* - for (const item of article.variants) { - const res = await this.articleVariantRepository.remove(item._id.toString()) - } - - const deleteIt = await this.articleModel.deleteOne(article._id); - - console.log(deleteIt) - - - - - - - return {_id:id}; -*/ - } - - -} \ No newline at end of file diff --git a/apps/backend/src/catalog/catalog.module.ts b/apps/backend/src/catalog/catalog.module.ts deleted file mode 100644 index 46011d4..0000000 --- a/apps/backend/src/catalog/catalog.module.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Module } from '@nestjs/common'; -import { CategoriesModule } from './categories/categories.module'; -import { ArticlesModule } from './articles/articles.module'; -import { ArticleVariantModule } from './article-variant/article-variant.module'; -import { ManufacturerModule } from './manufacturer/manufacturer.module'; - -@Module({ - imports: [ - ArticlesModule, - ArticleVariantModule, - CategoriesModule, - ManufacturerModule, - ], - exports: [ArticlesModule, ArticleVariantModule] -}) -export class CatalogModule { } diff --git a/apps/backend/src/chat.gateway.ts b/apps/backend/src/chat.gateway.ts index cbdff35..aad913b 100644 --- a/apps/backend/src/chat.gateway.ts +++ b/apps/backend/src/chat.gateway.ts @@ -13,7 +13,7 @@ import { Server } from 'socket.io'; }) export class ChatGateway { @WebSocketServer() - server: Server; // 👈 DAS fehlt dir gerade + server!: Server; // 👈 DAS fehlt dir gerade @SubscribeMessage('message') handleMessage(@MessageBody() data: string) { diff --git a/apps/backend/src/draw/draw.service.ts b/apps/backend/src/draw/draw.service.ts index 3d6a7d3..a4afcd4 100644 --- a/apps/backend/src/draw/draw.service.ts +++ b/apps/backend/src/draw/draw.service.ts @@ -1,62 +1,62 @@ -import { Injectable } from '@nestjs/common'; -import { DrawContainer } from 'src/graphics/lib/draw'; -import { DrawEllipse } from 'src/graphics/lib/drawEllipse'; -import { DrawGroup } from 'src/graphics/lib/drawGroup'; -import { DrawPath, PathCommand } from 'src/graphics/lib/drawPath'; - -@Injectable() -export class DrawService { - constructor() { } - - async ellypse() { - - const raster = 4; - const scale = 2.0; - const x0 = 0; - const y0 = 0; - - const l1 = 40 * raster * scale - const h1 = 2 * raster * scale - - const r = h1 / 2; - - const deck: PathCommand[] = [ - { type: "M", x: r, y: y0 }, - { type: "H", x: l1 - r }, // -- - { type: "A", rx: r, ry: r, - xAxisRotation: 0, - largeArcFlag: 0, - sweepFlag: 1, x: l1 - r, y: h1 }, // > - - { type: "H", x: x0 + r }, // -- - { type: "A", rx: r, ry: r, - xAxisRotation: 0, - largeArcFlag: 0, - sweepFlag: 1, x: r, y: y0 }, // < - { type: "Z" } - ]; - - const c1 = new DrawGroup({}); - const c2 = new DrawGroup({}); - - const rtc = new DrawPath(deck); - const ely1 = new DrawEllipse( { cx: 10, cy: 10, rx: 5, ry: 5}); - c2.add(ely1); - - c1.add(rtc); - c1.add(c2); - c1.add(rtc); - - return c1.getChildString(false,0) - - - - - - } - -} - - - - +import { Injectable } from '@nestjs/common'; +import { DrawContainer } from '../graphics/lib/draw'; +import { DrawEllipse } from '../graphics/lib/drawEllipse'; +import { DrawGroup } from '../graphics/lib/drawGroup'; +import { DrawPath, PathCommand } from '../graphics/lib/drawPath'; + +@Injectable() +export class DrawService { + constructor() { } + + async ellypse() { + + const raster = 4; + const scale = 2.0; + const x0 = 0; + const y0 = 0; + + const l1 = 40 * raster * scale + const h1 = 2 * raster * scale + + const r = h1 / 2; + + const deck: PathCommand[] = [ + { type: "M", x: r, y: y0 }, + { type: "H", x: l1 - r }, // -- + { type: "A", rx: r, ry: r, + xAxisRotation: 0, + largeArcFlag: 0, + sweepFlag: 1, x: l1 - r, y: h1 }, // > + + { type: "H", x: x0 + r }, // -- + { type: "A", rx: r, ry: r, + xAxisRotation: 0, + largeArcFlag: 0, + sweepFlag: 1, x: r, y: y0 }, // < + { type: "Z" } + ]; + + const c1 = new DrawGroup({}); + const c2 = new DrawGroup({}); + + const rtc = new DrawPath(deck); + const ely1 = new DrawEllipse( { cx: 10, cy: 10, rx: 5, ry: 5}); + c2.add(ely1); + + c1.add(rtc); + c1.add(c2); + c1.add(rtc); + + return c1.getChildString(false,0) + + + + + + } + +} + + + + diff --git a/apps/backend/src/inventory/_controllers/movements.controller.ts b/apps/backend/src/inventory/_controllers/movements.controller.ts index 06833d3..c194de4 100644 --- a/apps/backend/src/inventory/_controllers/movements.controller.ts +++ b/apps/backend/src/inventory/_controllers/movements.controller.ts @@ -1,45 +1,27 @@ -import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; +import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common'; import { StockMovementsService } from '../movements/movements.service'; -import { StockMovementInDto,StockMovementOutDto,StockMovementTransferDto } from '../_dto/stock-movement.dto'; - +import { + StockMovementInDto, + StockMovementOutDto, + StockMovementTransferDto, +} from '../_dto/stock-movement.dto'; @Controller('stock-movements') export class StockMovementsController { - constructor( - - private readonly stockMovementsService: StockMovementsService - ) { console.log('movement controller');} - - @Post('in') - async stockIn(@Body() dto: StockMovementInDto) { - - return this.stockMovementsService.in(dto); + constructor(private readonly service: StockMovementsService) {} + @Post('in') stockIn(@Body() dto: StockMovementInDto) { + return this.service.in(dto); } - - @Post('out') - async stockOut(@Body() dto: StockMovementOutDto) { - return this.stockMovementsService.out(dto); + @Post('out') stockOut(@Body() dto: StockMovementOutDto) { + return this.service.out(dto); } - - @Post('transfer') - async transfer(@Body() dto: StockMovementTransferDto) { - return this.stockMovementsService.transfer(dto); + @Post('transfer') transfer(@Body() dto: StockMovementTransferDto) { + return this.service.transfer(dto); } - - @Get() - async findx() { - return "Hello from movement"; + @Get() findAll() { + return this.service.findAll(); } - - - @Get() - async findAll() { - return this.stockMovementsService.findAll(); - } - - - @Delete(':id') - remove(@Param('id') id: string) { - return this.stockMovementsService.remove(id); + @Delete(':id') remove(@Param('id') id: string) { + return this.service.remove(id); } } diff --git a/apps/backend/src/inventory/_controllers/stock-content.controller.ts b/apps/backend/src/inventory/_controllers/stock-content.controller.ts index a685ab4..2621ce4 100644 --- a/apps/backend/src/inventory/_controllers/stock-content.controller.ts +++ b/apps/backend/src/inventory/_controllers/stock-content.controller.ts @@ -1,4 +1,12 @@ -import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; +import { + Controller, + Get, + Post, + Body, + Patch, + Param, + Delete, +} from '@nestjs/common'; import { StockContentService } from '../stock-content/stock-content.service'; import { StockSummaryQuery } from '../_queries/stock-summary.query'; @@ -7,8 +15,7 @@ export class StockContentController { constructor( private readonly stockService: StockContentService, private readonly stockSummaryQuery: StockSummaryQuery, - ) { } - + ) {} @Get() findAll() { @@ -20,13 +27,12 @@ export class StockContentController { return this.stockService.findOne(id); } - @Delete(':id') remove(@Param('id') id: string) { return this.stockService.remove(id); } - @Get('summary/by-variant') + @Get(['summary/by-article', 'summary/by-variant']) getStockByVariant() { return this.stockSummaryQuery.byArticle(); } diff --git a/apps/backend/src/inventory/_dto/stock-content.dto.ts b/apps/backend/src/inventory/_dto/stock-content.dto.ts index 6df9135..1d384f0 100644 --- a/apps/backend/src/inventory/_dto/stock-content.dto.ts +++ b/apps/backend/src/inventory/_dto/stock-content.dto.ts @@ -1,50 +1,12 @@ -import { PartialType } from "@nestjs/mapped-types"; -import { StockDto } from "./stock.dto"; -import { ArticleVariantDto } from "src/catalog/_dto/article.dto"; +import { ArticleDto } from '../../products/_dto/article.dto'; +import { StockDto } from './stock.dto'; - -export class StockContentDto { - id:string - stock: StockDto; - articleVariant: ArticleVariantDto; - batchNumber?: string; - area?:string; - quantity:number +export interface StockContentDto { + id: string; + stock: StockDto; + article: ArticleDto; + batchId?: string; + assetId?: string; + area?: string; + quantity: number; } - -export class StockContentCreateDto { - stock: StockDto; - articleVariant: ArticleVariantDto; - batchNumber?: string; - area?:string; - quantity:number -} - -export class StockContentFindConsumableDto { - stockId: string; - articleVariantId: string; - batchNumber: string; -} - -export class StockContentFindNonConsumableDto { - stockId: string; - articleVariantId: string; -} - -export class StockContentConsumableInDto { - stockId: string; - articleVariantId: string; - quantity: number; - expiryDate?: Date; - batchNumber?: string; - area?: string; -} - -export class StockContentNonConsumableInDto{ - stockId: string; - articleVariantId: string; - quantity: number; - area?: string; -} - -export class StockContentUpdateDto extends PartialType(StockContentConsumableInDto) { } diff --git a/apps/backend/src/inventory/_dto/stock-movement.dto.ts b/apps/backend/src/inventory/_dto/stock-movement.dto.ts index 3883c52..5f9fc08 100644 --- a/apps/backend/src/inventory/_dto/stock-movement.dto.ts +++ b/apps/backend/src/inventory/_dto/stock-movement.dto.ts @@ -1,4 +1,13 @@ -import { IsDate, IsMongoId, IsNumber, IsOptional, IsString } from "class-validator"; +import { Type } from 'class-transformer'; +import { + IsDate, + IsMongoId, + IsNotEmpty, + IsNumber, + IsOptional, + IsString, + Min, +} from 'class-validator'; export enum StockMovementType { IN = 'IN', @@ -7,66 +16,53 @@ export enum StockMovementType { } export class StockMovementInDto { - @IsString() @IsMongoId() - stockId: string; - - @IsString() + stockId!: string; @IsMongoId() - articleVariantId: string; - + articleId!: string; @IsNumber() - quantity: number; - - @IsString() + @Min(Number.MIN_VALUE) + quantity!: number; @IsOptional() + @IsString() + @IsNotEmpty() batchNumber?: string; - + @IsOptional() + @Type(() => Date) @IsDate() - @IsOptional() expiryDate?: Date; - - @IsString() @IsOptional() + @IsString() area?: string; - + @IsOptional() + @IsString() + @IsNotEmpty() + inventoryNumber?: string; + @IsOptional() + @IsString() + serialNumber?: string; + @IsOptional() + @IsString() + condition?: string; + @IsOptional() + @IsString() + purpose?: string; + @IsOptional() + @Type(() => Date) + @IsDate() + acquiredAt?: Date; } - export class StockMovementOutDto { - @IsString() @IsMongoId() - stockContentId: string; - + stockContentId!: string; @IsNumber() - quantity: number; - + @Min(Number.MIN_VALUE) + quantity!: number; } - -export class StockMovementTransferDto { - @IsString() +export class StockMovementTransferDto extends StockMovementOutDto { @IsMongoId() - articleVariantId: string; - - @IsString() - @IsMongoId() - fromStockId: string; - - @IsString() - @IsMongoId() - toStockId: string; - - @IsString() + toStockId!: string; @IsOptional() + @IsString() toArea?: string; - - @IsNumber() - quantity: number; - - @IsString() - @IsOptional() - batchNumber?: string; - } - - - diff --git a/apps/backend/src/inventory/_dto/stock.dto.ts b/apps/backend/src/inventory/_dto/stock.dto.ts index 408b9ca..c13e5b4 100644 --- a/apps/backend/src/inventory/_dto/stock.dto.ts +++ b/apps/backend/src/inventory/_dto/stock.dto.ts @@ -1,14 +1,14 @@ import { IsMongoId, IsOptional, IsString, IsArray } from "class-validator"; import { Types } from "mongoose"; -import { LocationDto } from "src/locations/dto/location.dto"; +import { LocationDto } from "../../locations/dto/location.dto"; export class StockCreateDto { @IsString() - name: string; + name!: string; @IsString() @IsMongoId() - locationId: string; + locationId!: string; @IsArray() @IsOptional() @@ -32,15 +32,15 @@ export class StockUpdateDto { } export class StockRowDto { - _id: string - name: string; - locationId: Types.ObjectId; + _id!: string + name!: string; + locationId!: Types.ObjectId; areas?:string[] } export class StockDto { - id: string - name: string; - location: LocationDto; + id!: string + name!: string; + location!: LocationDto; areas?:string[] } \ No newline at end of file diff --git a/apps/backend/src/inventory/_entities/asset.entity.ts b/apps/backend/src/inventory/_entities/asset.entity.ts new file mode 100644 index 0000000..4247e12 --- /dev/null +++ b/apps/backend/src/inventory/_entities/asset.entity.ts @@ -0,0 +1,23 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { Document, Types } from 'mongoose'; + +@Schema({ timestamps: true }) +export class Asset extends Document { + @Prop({ type: Types.ObjectId, ref: 'Article', required: true }) + articleId!: Types.ObjectId; + @Prop({ required: true, trim: true, unique: true }) + inventoryNumber!: string; + @Prop() + serialNumber?: string; + @Prop() + condition?: string; + @Prop() + purpose?: string; + @Prop() + acquiredAt?: Date; + @Prop({ type: Types.ObjectId, ref: 'Stock', default: null }) + stockId?: Types.ObjectId | null; + @Prop({ enum: ['in-stock', 'withdrawn'], default: 'in-stock' }) + status!: string; +} +export const AssetSchema = SchemaFactory.createForClass(Asset); diff --git a/apps/backend/src/inventory/_entities/batch.entity.ts b/apps/backend/src/inventory/_entities/batch.entity.ts new file mode 100644 index 0000000..500e24b --- /dev/null +++ b/apps/backend/src/inventory/_entities/batch.entity.ts @@ -0,0 +1,14 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { Document, Types } from 'mongoose'; + +@Schema({ timestamps: true }) +export class Batch extends Document { + @Prop({ type: Types.ObjectId, ref: 'Article', required: true }) + articleId!: Types.ObjectId; + @Prop({ required: true, trim: true }) + batchNumber!: string; + @Prop() + expiryDate?: Date; +} +export const BatchSchema = SchemaFactory.createForClass(Batch); +BatchSchema.index({ articleId: 1, batchNumber: 1 }, { unique: true }); diff --git a/apps/backend/src/inventory/_entities/stock-content.entity.ts b/apps/backend/src/inventory/_entities/stock-content.entity.ts index 8d2abf4..c62c77c 100644 --- a/apps/backend/src/inventory/_entities/stock-content.entity.ts +++ b/apps/backend/src/inventory/_entities/stock-content.entity.ts @@ -4,23 +4,28 @@ import { Document, Types } from 'mongoose'; @Schema({ timestamps: true }) export class StockContent extends Document { @Prop({ type: Types.ObjectId, ref: 'Stock', required: true }) - stockId: Types.ObjectId; + stockId!: Types.ObjectId; - @Prop({ type: Types.ObjectId, ref: 'ArticleVariant', required: true }) - articleVariantId: Types.ObjectId; + @Prop({ type: Types.ObjectId, ref: 'Article', required: true }) + articleId!: Types.ObjectId; - @Prop({required:false}) - batchNumber?: string; + @Prop({ type: Types.ObjectId, ref: 'Batch', default: null }) + batchId?: Types.ObjectId | null; - @Prop({ required: true }) - quantity: number; + @Prop({ type: Types.ObjectId, ref: 'Asset', default: null }) + assetId?: Types.ObjectId | null; - @Prop() - expiryDate?: Date; - - @Prop() - area?: string; + @Prop({ required: true, min: 0 }) + quantity!: number; + @Prop({ default: '' }) + area!: string; } - export const StockContentSchema = SchemaFactory.createForClass(StockContent); +StockContentSchema.index( + { articleId: 1, stockId: 1, batchId: 1, assetId: 1, area: 1 }, + { + unique: true, + partialFilterExpression: { articleId: { $type: 'objectId' } }, + }, +); diff --git a/apps/backend/src/inventory/_entities/stock-movement.entity.ts b/apps/backend/src/inventory/_entities/stock-movement.entity.ts index 67cd728..08ecf54 100644 --- a/apps/backend/src/inventory/_entities/stock-movement.entity.ts +++ b/apps/backend/src/inventory/_entities/stock-movement.entity.ts @@ -2,30 +2,23 @@ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document, Types } from 'mongoose'; import { StockMovementType } from '../_dto/stock-movement.dto'; - - @Schema({ timestamps: true }) export class StockMovement extends Document { @Prop({ type: Types.ObjectId, ref: 'Stock', required: true }) - stockId: Types.ObjectId; - - @Prop({ type: Types.ObjectId, ref: 'ArticleVariant', required: true }) - articleVariantId: Types.ObjectId; - - - @Prop({ type: String, enum: StockMovementType, required: true, }) - type: StockMovementType; - - @Prop({ required: true, min: 1 }) - quantity: number; - + stockId!: Types.ObjectId; + @Prop({ type: Types.ObjectId, ref: 'Article', required: true }) + articleId!: Types.ObjectId; + @Prop({ type: String, enum: StockMovementType, required: true }) + type!: StockMovementType; + @Prop({ required: true, min: Number.MIN_VALUE }) + quantity!: number; @Prop({ type: Types.ObjectId, ref: 'Stock' }) toStockId?: Types.ObjectId; - - + @Prop({ type: Types.ObjectId, ref: 'Batch' }) + batchId?: Types.ObjectId; + @Prop({ type: Types.ObjectId, ref: 'Asset' }) + assetId?: Types.ObjectId; @Prop({ type: Object }) - meta?: Record; + meta?: Record; } - -export const StockMovementSchema = - SchemaFactory.createForClass(StockMovement); \ No newline at end of file +export const StockMovementSchema = SchemaFactory.createForClass(StockMovement); diff --git a/apps/backend/src/inventory/_entities/stock.entity.ts b/apps/backend/src/inventory/_entities/stock.entity.ts index 15705b2..ca3afef 100644 --- a/apps/backend/src/inventory/_entities/stock.entity.ts +++ b/apps/backend/src/inventory/_entities/stock.entity.ts @@ -4,13 +4,13 @@ import { Document, Types } from 'mongoose'; @Schema({ timestamps: false }) export class Stock extends Document { @Prop({ required: true }) - name: string; + name!: string; @Prop({ type: Types.ObjectId, ref: 'Location', required: true }) - locationId: Types.ObjectId; + locationId!: Types.ObjectId; @Prop({ }) - areas: Types.Array; + areas!: Types.Array; } diff --git a/apps/backend/src/inventory/_queries/stock-summary.query.ts b/apps/backend/src/inventory/_queries/stock-summary.query.ts index 3348624..abc55f8 100644 --- a/apps/backend/src/inventory/_queries/stock-summary.query.ts +++ b/apps/backend/src/inventory/_queries/stock-summary.query.ts @@ -1,95 +1,37 @@ -import { Injectable, BadRequestException } from '@nestjs/common'; +import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; -import { StockContent } from '../_entities/stock-content.entity' +import { StockContent } from '../_entities/stock-content.entity'; @Injectable() export class StockSummaryQuery { - constructor( - @InjectModel(StockContent.name) - private readonly stockModel: Model, - ) { } - - async byArticle() { - console.log('get'); - const x = await this.stockModel.aggregate<{id_:string,articleVariantId:string,articleName:string,manufacturer:string,totalQuantity:number}>([ - { - $group: { - _id: '$articleVariantId', - totalQuantity: { $sum: '$quantity' }, - }, - }, - - { - $lookup: { - from: 'articlevariants', - localField: '_id', - foreignField: '_id', - as: 'variant', - } - }, - - { $unwind: '$variant' }, - { - $lookup: { - from: 'articles', - localField: 'variant.articleId', - foreignField: '_id', - as: 'article', - }, - }, - { $unwind: '$article' }, - // 4️⃣ Hersteller holen - { - $lookup: { - from: 'manufacturers', - localField: 'variant.manufacturerId', - foreignField: '_id', - as: 'manufacturer', - }, - }, - { $unwind: '$manufacturer' }, - { - $project: { - _id: 0, - articleVariantId: '$_id', - articleName: '$article.name', - manufacturer: '$manufacturer.name', - totalQuantity: 1, - }, - } - - ]); - console.log(x[0].articleName + ' von ' + x[0].manufacturer); - return x; - } - - async byArticle2() { - return this.stockModel.aggregate([ - { - $group: { - _id: '$articleVariantId', - totalQuantity: { $sum: '$quantity' }, - }, - }, - { - $lookup: { - from: 'articlevariants', - localField: '_id', - foreignField: '_id', - as: 'variant', - }, - }, - { $unwind: '$variant' }, - { - $lookup: { - from: 'articles', - localField: 'variant.articleId', - foreignField: '_id', - as: 'article', - }, - }, - { $unwind: '$article' }, - ]); - } -} \ No newline at end of file + constructor( + @InjectModel(StockContent.name) private readonly model: Model, + ) {} + byArticle() { + return this.model + .aggregate([ + { $match: { articleId: { $exists: true } } }, + { $group: { _id: '$articleId', totalQuantity: { $sum: '$quantity' } } }, + { + $lookup: { + from: 'articles', + localField: '_id', + foreignField: '_id', + as: 'article', + }, + }, + { $unwind: '$article' }, + { + $project: { + _id: 0, + articleId: '$_id', + articleName: '$article.name', + baseUnit: '$article.baseUnit', + totalQuantity: 1, + }, + }, + ]) + .exec(); + } +} diff --git a/apps/backend/src/inventory/inventory.module.ts b/apps/backend/src/inventory/inventory.module.ts index c978692..ea12581 100644 --- a/apps/backend/src/inventory/inventory.module.ts +++ b/apps/backend/src/inventory/inventory.module.ts @@ -2,7 +2,7 @@ import { Module } from '@nestjs/common'; import { MovementsModule } from './movements/movements.module'; import { StockContentModule } from './stock-content/stock-content.module'; import { StockModule } from './stock/stock.module'; -import { LocationsModule } from 'src/locations/locations.module'; +import { LocationsModule } from '../locations/locations.module'; @Module({ imports: [ diff --git a/apps/backend/src/inventory/movements/movement.repository.ts b/apps/backend/src/inventory/movements/movement.repository.ts index 31997d1..e60e59b 100644 --- a/apps/backend/src/inventory/movements/movement.repository.ts +++ b/apps/backend/src/inventory/movements/movement.repository.ts @@ -1,76 +1,53 @@ -import { Injectable } from '@nestjs/common'; +import { BadRequestException, Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; +import { ClientSession, Model, Types } from 'mongoose'; import { StockMovement } from '../_entities/stock-movement.entity'; - -import { StockMovementInDto, StockMovementType, StockMovementTransferDto, StockMovementOutDto } from '../_dto/stock-movement.dto'; - +import { StockContent } from '../_entities/stock-content.entity'; +import { StockMovementType } from '../_dto/stock-movement.dto'; @Injectable() export class MovementRepository { constructor( @InjectModel(StockMovement.name) private readonly model: Model, - - ) { } - - async findAll() { - return this.model.find().exec(); + ) {} + findAll() { + return this.model + .find({ articleId: { $exists: true } }) + .sort({ createdAt: -1 }) + .exec(); } - - remove(id: string) { - return this.model.findByIdAndDelete(id); - } - - // =============================== - // IN - // =============================== - async logStockMoveIn(dto: StockMovementInDto) { - const { articleVariantId, stockId, quantity } = dto; - return this.model.create( - { - articleVariantId, - stockId, - type: StockMovementType.IN, - quantity - } + remove(_id: string): never { + throw new BadRequestException( + 'Buchungsprotokolle können nicht gelöscht werden', ); } - - - // =============================== - // OUT - // =============================== - async logStockMoveOut(dto: StockMovementOutDto,result:any) { - - return this.model.create({ - stockId: new Types.ObjectId(dto.stockContentId), - articleVariantId: new Types.ObjectId(result.articelVariantId), - type: StockMovementType.OUT, - quantity: dto.quantity, - }); + async log( + type: StockMovementType, + content: StockContent, + quantity: number, + session: ClientSession, + toStockId?: string, + toArea?: string, + ) { + const [movement] = await this.model.create( + [ + { + type, + articleId: content.articleId, + stockId: content.stockId, + quantity, + batchId: content.batchId ?? undefined, + assetId: content.assetId ?? undefined, + toStockId: toStockId ? new Types.ObjectId(toStockId) : undefined, + meta: { + fromArea: content.area, + ...(toArea !== undefined ? { toArea } : {}), + }, + }, + ], + { session }, + ); + return movement; } - - // =============================== - // TRANSFER - // =============================== - async logStockContentTransfer(dto: StockMovementTransferDto) { - const { articleVariantId, quantity, fromStockId, toStockId } = dto; - - - return this.model.create({ - articleVariantId: new Types.ObjectId(articleVariantId), - stockId:fromStockId, - type: StockMovementType.TRANSFER, - quantity, - meta: { - fromLocationId: new Types.ObjectId(fromStockId), - toLocationId: new Types.ObjectId(toStockId), - }, - }); - } - - - - -} \ No newline at end of file +} diff --git a/apps/backend/src/inventory/movements/movements.module.ts b/apps/backend/src/inventory/movements/movements.module.ts index ae88fec..40212bd 100644 --- a/apps/backend/src/inventory/movements/movements.module.ts +++ b/apps/backend/src/inventory/movements/movements.module.ts @@ -1,43 +1,22 @@ import { Module } from '@nestjs/common'; - -import { StockMovementsController } from '../_controllers/movements.controller'; -import { StockMovementsService } from './movements.service'; - import { MongooseModule } from '@nestjs/mongoose'; - -import { MovementRepository } from './movement.repository'; - -import { StockContent, StockContentSchema } from '../_entities/stock-content.entity'; -import { StockMovement, StockMovementSchema } from '../_entities/stock-movement.entity'; -import { Article, ArticleSchema } from 'src/catalog/_entities/article.entity'; -import { ArticleVariant, ArticleVariantSchema } from 'src/catalog/_entities/article-variant.entity'; -import { CatalogModule } from 'src/catalog/catalog.module'; +import { StockMovementsController } from '../_controllers/movements.controller'; +import { + StockMovement, + StockMovementSchema, +} from '../_entities/stock-movement.entity'; import { StockContentModule } from '../stock-content/stock-content.module'; -import { StockContentRepository } from '../stock-content/stock-content.repository'; -import { StockContentService } from '../stock-content/stock-content.service'; - - +import { StockMovementsService } from './movements.service'; +import { MovementRepository } from './movement.repository'; @Module({ imports: [ - MongooseModule.forFeature([ - { name: StockContent.name, schema: StockContentSchema }, - { name: StockMovement.name, schema: StockMovementSchema }, - { name: Article.name, schema: ArticleSchema }, - { name: ArticleVariant.name, schema: ArticleVariantSchema }, - - ]), - CatalogModule, - - ], - - controllers: [StockMovementsController], - providers: [ - StockMovementsService, - StockContentService, - StockContentRepository, - MovementRepository, + MongooseModule.forFeature([ + { name: StockMovement.name, schema: StockMovementSchema }, + ]), + StockContentModule, ], - + controllers: [StockMovementsController], + providers: [StockMovementsService, MovementRepository], }) -export class MovementsModule { } +export class MovementsModule {} diff --git a/apps/backend/src/inventory/movements/movements.service.spec.ts b/apps/backend/src/inventory/movements/movements.service.spec.ts new file mode 100644 index 0000000..142da4e --- /dev/null +++ b/apps/backend/src/inventory/movements/movements.service.spec.ts @@ -0,0 +1,74 @@ +import { Connection, ClientSession } from 'mongoose'; +import { StockMovementsService } from './movements.service'; +import { MovementRepository } from './movement.repository'; +import { StockContentService } from '../stock-content/stock-content.service'; +import { StockMovementType } from '../_dto/stock-movement.dto'; + +function setup() { + const session = {} as ClientSession; + const connection = { transaction: jest.fn((action) => action(session)) }; + const content = { articleId: 'article', stockId: 'source', quantity: 2 }; + const stock = { + moveIn: jest.fn().mockResolvedValue(content), + moveOut: jest.fn().mockResolvedValue(content), + transfer: jest.fn().mockResolvedValue(content), + }; + const movements = { log: jest.fn().mockResolvedValue({ type: 'IN' }) }; + const service = new StockMovementsService( + movements as unknown as MovementRepository, + stock as unknown as StockContentService, + connection as unknown as Connection, + ); + return { service, session, stock, movements, content, connection }; +} + +describe('Lagerbuchungen', () => { + it('protokolliert fehlgeschlagene Einlagerungen nicht', async () => { + const { service, stock, movements } = setup(); + stock.moveIn.mockRejectedValue(new Error('Charge fehlt')); + await expect( + service.in({ articleId: 'article', stockId: 'stock', quantity: 2 }), + ).rejects.toThrow('Charge fehlt'); + expect(movements.log).not.toHaveBeenCalled(); + }); + + it('führt Bestand und Protokoll in derselben Transaktion aus', async () => { + const { service, stock, movements, session, content, connection } = setup(); + const dto = { articleId: 'article', stockId: 'stock', quantity: 2 }; + await service.in(dto); + expect(connection.transaction).toHaveBeenCalledTimes(1); + expect(stock.moveIn).toHaveBeenCalledWith(dto, session); + expect(movements.log).toHaveBeenCalledWith( + StockMovementType.IN, + content, + 2, + session, + ); + }); + + it('meldet auch Protokollfehler als fehlgeschlagene Buchung', async () => { + const { service, movements } = setup(); + movements.log.mockRejectedValue(new Error('Schreibfehler')); + await expect( + service.out({ stockContentId: 'content', quantity: 2 }), + ).rejects.toThrow('Schreibfehler'); + }); + + it('übergibt tatsächliche Quellreferenzen und Ziel für Umlagerungen', async () => { + const { service, movements, session, content } = setup(); + await service.transfer({ + stockContentId: 'content', + toStockId: 'target', + toArea: 'Fach 1', + quantity: 1, + }); + expect(movements.log).toHaveBeenCalledWith( + StockMovementType.TRANSFER, + content, + 1, + session, + 'target', + 'Fach 1', + ); + }); +}); diff --git a/apps/backend/src/inventory/movements/movements.service.ts b/apps/backend/src/inventory/movements/movements.service.ts index 4d8da97..1edde93 100644 --- a/apps/backend/src/inventory/movements/movements.service.ts +++ b/apps/backend/src/inventory/movements/movements.service.ts @@ -1,48 +1,94 @@ -import { Injectable, BadRequestException } from '@nestjs/common'; -import { StockMovementOutDto, StockMovementInDto, StockMovementTransferDto } from '../_dto/stock-movement.dto'; +import { + ConflictException, + Injectable, + ServiceUnavailableException, +} from '@nestjs/common'; +import { InjectConnection } from '@nestjs/mongoose'; +import { ClientSession, Connection } from 'mongoose'; +import { + StockMovementInDto, + StockMovementOutDto, + StockMovementTransferDto, + StockMovementType, +} from '../_dto/stock-movement.dto'; import { MovementRepository } from './movement.repository'; import { StockContentService } from '../stock-content/stock-content.service'; - - @Injectable() export class StockMovementsService { - constructor( - private readonly movementRepo: MovementRepository, - private readonly stockContentService: StockContentService - ) { } - - findAll() { - return this.movementRepo.findAll(); + constructor( + private readonly movementRepo: MovementRepository, + private readonly stockContentService: StockContentService, + @InjectConnection() private readonly connection: Connection, + ) {} + findAll() { + return this.movementRepo.findAll(); + } + remove(id: string) { + return this.movementRepo.remove(id); + } + in(dto: StockMovementInDto) { + return this.book(async (session) => { + const content = await this.stockContentService.moveIn(dto, session); + return this.movementRepo.log( + StockMovementType.IN, + content, + dto.quantity, + session, + ); + }); + } + out(dto: StockMovementOutDto) { + return this.book(async (session) => { + const content = await this.stockContentService.moveOut(dto, session); + return this.movementRepo.log( + StockMovementType.OUT, + content, + dto.quantity, + session, + ); + }); + } + transfer(dto: StockMovementTransferDto) { + return this.book(async (session) => { + const content = await this.stockContentService.transfer(dto, session); + return this.movementRepo.log( + StockMovementType.TRANSFER, + content, + dto.quantity, + session, + dto.toStockId, + dto.toArea ?? '', + ); + }); + } + private async book( + action: (session: ClientSession) => Promise, + ): Promise { + try { + return await this.connection.transaction(action); + } catch (error) { + if ( + error && + typeof error === 'object' && + 'code' in error && + error.code === 20 + ) { + throw new ServiceUnavailableException( + 'Lagerbuchungen benötigen MongoDB als Replica Set oder Sharded Cluster', + ); + } + if ( + error && + typeof error === 'object' && + 'code' in error && + error.code === 11000 + ) { + throw new ConflictException( + 'Inventarnummer oder Bestandsposition ist bereits vergeben; Buchung erneut prüfen', + ); + } + throw error; } - - remove(id: string) { - return this.movementRepo.remove(id); - } - - - async in(dto: StockMovementInDto) { - this.validateIn(dto); - - const result = this.stockContentService.moveIn(dto); - return await this.movementRepo.logStockMoveIn(dto); - } - - async out(dto: StockMovementOutDto) { - const outResult = await this.stockContentService.moveOut(dto); - return await this.movementRepo.logStockMoveOut(dto, outResult); - } - - async transfer(dto: StockMovementTransferDto) { - const result = await this.stockContentService.transfer(dto); - return this.movementRepo.logStockContentTransfer(dto); - } - - - private validateIn(dto: StockMovementInDto) { - if (dto.quantity <= 0) { - throw new BadRequestException('Menge muss > 0 sein'); - } - - } -} \ No newline at end of file + } +} diff --git a/apps/backend/src/inventory/records/inventory-records.controller.ts b/apps/backend/src/inventory/records/inventory-records.controller.ts new file mode 100644 index 0000000..bfadd41 --- /dev/null +++ b/apps/backend/src/inventory/records/inventory-records.controller.ts @@ -0,0 +1,13 @@ +import { Controller, Get } from '@nestjs/common'; +import { InventoryRecordsService } from './inventory-records.service'; + +@Controller() +export class InventoryRecordsController { + constructor(private readonly service: InventoryRecordsService) {} + @Get('batches') batches() { + return this.service.findBatches(); + } + @Get('assets') assets() { + return this.service.findAssets(); + } +} diff --git a/apps/backend/src/inventory/records/inventory-records.service.ts b/apps/backend/src/inventory/records/inventory-records.service.ts new file mode 100644 index 0000000..6c375c4 --- /dev/null +++ b/apps/backend/src/inventory/records/inventory-records.service.ts @@ -0,0 +1,19 @@ +import { Injectable } from '@nestjs/common'; +import { InjectModel } from '@nestjs/mongoose'; +import { Model } from 'mongoose'; +import { Batch } from '../_entities/batch.entity'; +import { Asset } from '../_entities/asset.entity'; + +@Injectable() +export class InventoryRecordsService { + constructor( + @InjectModel(Batch.name) private readonly batches: Model, + @InjectModel(Asset.name) private readonly assets: Model, + ) {} + findBatches() { + return this.batches.find().populate('articleId').exec(); + } + findAssets() { + return this.assets.find().populate('articleId').populate('stockId').exec(); + } +} diff --git a/apps/backend/src/inventory/records/inventory-records.ts b/apps/backend/src/inventory/records/inventory-records.ts new file mode 100644 index 0000000..f8ce43d --- /dev/null +++ b/apps/backend/src/inventory/records/inventory-records.ts @@ -0,0 +1,2 @@ +export { InventoryRecordsController } from './inventory-records.controller'; +export { InventoryRecordsService } from './inventory-records.service'; diff --git a/apps/backend/src/inventory/stock-content/stock-content.module.ts b/apps/backend/src/inventory/stock-content/stock-content.module.ts index e58e55f..1d3b98b 100644 --- a/apps/backend/src/inventory/stock-content/stock-content.module.ts +++ b/apps/backend/src/inventory/stock-content/stock-content.module.ts @@ -1,27 +1,39 @@ import { Module } from '@nestjs/common'; +import { MongooseModule } from '@nestjs/mongoose'; +import { + StockContent, + StockContentSchema, +} from '../_entities/stock-content.entity'; +import { Stock, StockSchema } from '../_entities/stock.entity'; +import { Batch, BatchSchema } from '../_entities/batch.entity'; +import { Asset, AssetSchema } from '../_entities/asset.entity'; +import { Article, ArticleSchema } from '../../products/_entities/article.entity'; import { StockContentService } from './stock-content.service'; +import { StockContentRepository } from './stock-content.repository'; import { StockContentController } from '../_controllers/stock-content.controller'; import { StockSummaryQuery } from '../_queries/stock-summary.query'; - -import { MongooseModule } from '@nestjs/mongoose'; -import { StockContent, StockContentSchema } from '../_entities/stock-content.entity'; -import { StockContentRepository } from './stock-content.repository'; -import { CatalogModule } from 'src/catalog/catalog.module'; -import { StockModule } from '../stock/stock.module'; -import { StockService } from '../stock/stock.service'; - - +import { + InventoryRecordsController, + InventoryRecordsService, +} from '../records/inventory-records'; @Module({ imports: [ MongooseModule.forFeature([ { name: StockContent.name, schema: StockContentSchema }, + { name: Stock.name, schema: StockSchema }, + { name: Article.name, schema: ArticleSchema }, + { name: Batch.name, schema: BatchSchema }, + { name: Asset.name, schema: AssetSchema }, ]), - CatalogModule, - ], - controllers: [StockContentController], - providers: [StockContentService, StockSummaryQuery,StockContentRepository], - exports: [StockContentService] + controllers: [StockContentController, InventoryRecordsController], + providers: [ + StockContentService, + StockContentRepository, + StockSummaryQuery, + InventoryRecordsService, + ], + exports: [StockContentService], }) -export class StockContentModule { } +export class StockContentModule {} diff --git a/apps/backend/src/inventory/stock-content/stock-content.repository.spec.ts b/apps/backend/src/inventory/stock-content/stock-content.repository.spec.ts new file mode 100644 index 0000000..31140be --- /dev/null +++ b/apps/backend/src/inventory/stock-content/stock-content.repository.spec.ts @@ -0,0 +1,232 @@ +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; +import { ClientSession, Model, Types } from 'mongoose'; +import { StockContentRepository } from './stock-content.repository'; +import { StockContent } from '../_entities/stock-content.entity'; +import { Stock } from '../_entities/stock.entity'; +import { Article, TrackingMode } from '../../products/_entities/article.entity'; +import { Batch } from '../_entities/batch.entity'; +import { Asset } from '../_entities/asset.entity'; +import { + StockMovementInDto, + StockMovementOutDto, + StockMovementTransferDto, +} from '../_dto/stock-movement.dto'; + +const id = new Types.ObjectId().toString(); +function query(value: T) { + return { + session: jest.fn().mockReturnThis(), + exec: jest.fn().mockResolvedValue(value), + }; +} +function setup(article: Partial
= {}) { + const content = { + _id: new Types.ObjectId(), + stockId: new Types.ObjectId(), + articleId: new Types.ObjectId(), + batchId: new Types.ObjectId(), + assetId: null, + quantity: 0, + area: '', + }; + const stocks = { findById: jest.fn(() => query({ areas: [] })) }; + const articles = { + findById: jest.fn(() => + query({ + _id: new Types.ObjectId(), + articleNumber: 'TEST', + trackingMode: TrackingMode.QUANTITY, + ...article, + }), + ), + }; + const batches = { findOne: jest.fn(() => query(null)), create: jest.fn() }; + const assets = { + findOne: jest.fn(() => query(null as Asset | null)), + create: jest.fn(), + updateOne: jest.fn().mockResolvedValue({}), + }; + const model = { + findById: jest.fn(() => query(content)), + findOneAndUpdate: jest.fn(() => query(content)), + deleteOne: jest.fn().mockResolvedValue({}), + }; + const repository = new StockContentRepository( + model as unknown as Model, + articles as unknown as Model
, + stocks as unknown as Model, + batches as unknown as Model, + assets as unknown as Model, + ); + return { repository, model, content, batches, assets }; +} + +describe('Bestandsregeln', () => { + it.each([StockMovementInDto, StockMovementOutDto, StockMovementTransferDto])( + 'weist negative Mengen im DTO zurück', + async (Dto) => { + const dto = plainToInstance(Dto, { + articleId: id, + stockId: id, + stockContentId: id, + toStockId: id, + quantity: -2, + }); + expect((await validate(dto)).map((error) => error.property)).toContain( + 'quantity', + ); + }, + ); + it('wandelt ISO-Ablaufdaten in gültige Dates um', async () => { + const dto = plainToInstance(StockMovementInDto, { + articleId: id, + stockId: id, + quantity: 1, + expiryDate: '2026-10-20', + }); + expect(dto.expiryDate).toBeInstanceOf(Date); + expect(await validate(dto)).toEqual([]); + }); + it('verlangt für Verbrauchsartikel ohne Chargenführung keine Charge', async () => { + const { repository, batches } = setup({ isConsumable: true }); + await repository.moveIn( + { articleId: id, stockId: id, quantity: 3 }, + {} as ClientSession, + ); + expect(batches.findOne).not.toHaveBeenCalled(); + }); + it('verlangt bei Chargenführung eine Chargennummer', async () => { + const { repository } = setup({ trackingMode: TrackingMode.BATCH }); + await expect( + repository.moveIn( + { articleId: id, stockId: id, quantity: 1 }, + {} as ClientSession, + ), + ).rejects.toThrow('Chargennummer erforderlich'); + }); + it('verlangt bei Ablaufverfolgung ein Ablaufdatum für neue Chargen', async () => { + const { repository } = setup({ + trackingMode: TrackingMode.BATCH, + tracksExpiryDate: true, + }); + await expect( + repository.moveIn( + { articleId: id, stockId: id, quantity: 1, batchNumber: 'A' }, + {} as ClientSession, + ), + ).rejects.toThrow('Ablaufdatum'); + }); + it('verhindert mehrere Exemplare in einer Einzelstückbuchung', async () => { + const { repository, assets } = setup({ + trackingMode: TrackingMode.INDIVIDUAL, + }); + await expect( + repository.moveIn( + { articleId: id, stockId: id, quantity: 2, inventoryNumber: 'PI-1' }, + {} as ClientSession, + ), + ).rejects.toThrow('Menge 1'); + expect(assets.create).not.toHaveBeenCalled(); + }); + it('lagert ein entnommenes Exemplar unter derselben Inventarnummer erneut ein', async () => { + const articleId = new Types.ObjectId(); + const asset = { _id: new Types.ObjectId(), articleId, status: 'withdrawn' }; + const { repository, assets, model } = setup({ + _id: articleId, + trackingMode: TrackingMode.INDIVIDUAL, + }); + assets.findOne.mockReturnValue(query(asset as unknown as Asset)); + await repository.moveIn( + { + articleId: articleId.toString(), + stockId: id, + quantity: 1, + inventoryNumber: 'PI-1', + }, + {} as ClientSession, + ); + expect(assets.create).not.toHaveBeenCalled(); + expect(model.findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({ assetId: asset._id }), + expect.anything(), + expect.anything(), + ); + }); + it('weist eine schon eingelagerte Inventarnummer zurück', async () => { + const articleId = new Types.ObjectId(); + const { repository, assets } = setup({ + _id: articleId, + trackingMode: TrackingMode.INDIVIDUAL, + }); + assets.findOne.mockReturnValue( + query({ articleId, status: 'in-stock' } as unknown as Asset), + ); + await expect( + repository.moveIn( + { + articleId: articleId.toString(), + stockId: id, + quantity: 1, + inventoryNumber: 'PI-1', + }, + {} as ClientSession, + ), + ).rejects.toThrow('bereits eingelagert'); + }); + it('weist widersprüchliche Ablaufdaten für dieselbe Charge zurück', async () => { + const { repository, batches } = setup({ + trackingMode: TrackingMode.BATCH, + tracksExpiryDate: true, + }); + batches.findOne.mockReturnValue( + query({ + _id: new Types.ObjectId(), + expiryDate: new Date('2026-10-20'), + } as unknown as Batch), + ); + await expect( + repository.moveIn( + { + articleId: id, + stockId: id, + quantity: 1, + batchNumber: 'A', + expiryDate: new Date('2026-10-21'), + }, + {} as ClientSession, + ), + ).rejects.toThrow('Ablaufdatum weicht'); + }); + it('löscht nach vollständiger Entnahme die Bestands-ID und erhält die Artikelreferenz', async () => { + const { repository, model, content } = setup(); + const session = {} as ClientSession; + const result = await repository.moveOut( + { stockContentId: id, quantity: 2 }, + session, + ); + expect(model.deleteOne).toHaveBeenCalledWith( + { _id: content._id }, + { session }, + ); + expect(result.articleId).toEqual(content.articleId); + expect(result.stockId).toEqual(content.stockId); + }); + it('erhält beim Umlagern dieselbe Charge', async () => { + const { repository, model, content } = setup(); + const session = {} as ClientSession; + await repository.transfer( + { stockContentId: id, toStockId: id, quantity: 2 }, + session, + ); + expect(model.findOneAndUpdate).toHaveBeenLastCalledWith( + expect.objectContaining({ + articleId: content.articleId, + batchId: content.batchId, + stockId: id, + }), + { $inc: { quantity: 2 } }, + expect.objectContaining({ session }), + ); + }); +}); diff --git a/apps/backend/src/inventory/stock-content/stock-content.repository.ts b/apps/backend/src/inventory/stock-content/stock-content.repository.ts index bf74c5d..5ed8da6 100644 --- a/apps/backend/src/inventory/stock-content/stock-content.repository.ts +++ b/apps/backend/src/inventory/stock-content/stock-content.repository.ts @@ -1,286 +1,264 @@ -import { Injectable, BadRequestException } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model, Types } from 'mongoose'; -import { StockContent } from '../_entities/stock-content.entity'; import { - StockContentConsumableInDto, - StockContentNonConsumableInDto, - StockContentFindConsumableDto, - StockContentFindNonConsumableDto -} from '../_dto/stock-content.dto'; - -import { StockMovementOutDto, StockMovementTransferDto } from '../_dto/stock-movement.dto'; -import { ArticleVariantService } from 'src/catalog/article-variant/article-variant.service'; - - - + BadRequestException, + ConflictException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { InjectModel } from '@nestjs/mongoose'; +import { ClientSession, Model, Types } from 'mongoose'; +import { Article, TrackingMode } from '../../products/_entities/article.entity'; +import { StockContent } from '../_entities/stock-content.entity'; +import { Stock } from '../_entities/stock.entity'; +import { Batch } from '../_entities/batch.entity'; +import { Asset } from '../_entities/asset.entity'; +import { + StockMovementInDto, + StockMovementOutDto, + StockMovementTransferDto, +} from '../_dto/stock-movement.dto'; @Injectable() export class StockContentRepository { constructor( - @InjectModel(StockContent.name) - private readonly model: Model, - //private readonly articleService: ArticleVariantService, + @InjectModel(StockContent.name) private readonly model: Model, + @InjectModel(Article.name) private readonly articles: Model
, + @InjectModel(Stock.name) private readonly stocks: Model, + @InjectModel(Batch.name) private readonly batches: Model, + @InjectModel(Asset.name) private readonly assets: Model, + ) {} - ) { } + async moveIn(dto: StockMovementInDto, session: ClientSession) { + this.positive(dto.quantity); + const article = await this.articles + .findById(dto.articleId) + .session(session) + .exec(); + if (!article || !article.articleNumber) + throw new NotFoundException( + 'Artikel nicht gefunden oder noch nicht migriert', + ); + if (article.archivedAt) + throw new ConflictException( + 'Archivierte Artikel können nicht eingelagert werden', + ); + await this.validateStock(dto.stockId, dto.area, session); + let batchId: Types.ObjectId | null = null; + let assetId: Types.ObjectId | null = null; - async remove(id: string) { - return this.model.findByIdAndDelete(id); - } - - async findById(stockId: string) { - return this.model.findById(stockId); - } - - async findNonConsumable(dto: StockContentFindNonConsumableDto) { - return this.model - .findOne({ - articleVariantId: dto.articleVariantId, - stockId: dto.stockId, - batchNumber: null, - }) - - } - - async findConsumable(dto: StockContentFindConsumableDto) { - const { articleVariantId, stockId, batchNumber } = dto; - - return this.model - .findOne({ - articleVariantId, - stockId, - batchNumber, - }) - - } - - /** - * Stock IN - */ - - //--- Konsumierbare artikel - async moveConsumableIn(dto: StockContentConsumableInDto): Promise { - - const { stockId, articleVariantId, batchNumber, quantity } = dto; - - if (!batchNumber) { + if (article.trackingMode === TrackingMode.BATCH) { + if (!dto.batchNumber?.trim()) + throw new BadRequestException('Chargennummer erforderlich'); + const existing = await this.batches + .findOne({ + articleId: article._id, + batchNumber: dto.batchNumber.trim(), + }) + .session(session) + .exec(); + if ( + article.tracksExpiryDate && + !dto.expiryDate && + !existing?.expiryDate + ) { + throw new BadRequestException( + 'Ablaufdatum für diese Charge erforderlich', + ); + } + if (!article.tracksExpiryDate && dto.expiryDate) + throw new BadRequestException('Dieser Artikel führt keine Ablaufdaten'); + if (existing) { + if ( + dto.expiryDate && + existing.expiryDate?.getTime() !== dto.expiryDate.getTime() + ) { + throw new ConflictException( + 'Ablaufdatum weicht von der bestehenden Charge ab', + ); + } + batchId = existing._id; + } else { + const [batch] = await this.batches.create( + [ + { + articleId: article._id, + batchNumber: dto.batchNumber.trim(), + expiryDate: dto.expiryDate, + }, + ], + { session }, + ); + batchId = batch._id; + } + } else if (dto.batchNumber || dto.expiryDate) { throw new BadRequestException( - 'Batch Nummer erfoderlich erforderlich', + 'Charge und Ablaufdatum sind nur bei Chargenführung erlaubt', ); } - const stockContent = await this.findConsumable({ stockId, articleVariantId, batchNumber }); - - return await this.moveIn(dto, stockContent); - - } - - - // Nicht Konsumierbare artikel - async moveNonConsumableIn(dto: StockContentNonConsumableInDto): Promise { - - const stockContent = await this.findNonConsumable({ - articleVariantId: dto.articleVariantId, - stockId: dto.stockId, - }); - - return this.moveIn(dto, stockContent); - - } - - private async moveIn(dto: StockContentConsumableInDto, stockContent?: StockContent | null): Promise { - - let result: StockContent; - - if (stockContent) { - // Artikel im Lager bereits vorhanden - stockContent.quantity += dto.quantity; - result = await stockContent.save(); - } else { - // Artikel nicht im Lager vorhanden - const create = { - articleVariantId: new Types.ObjectId(dto.articleVariantId), - stockId: new Types.ObjectId(dto.stockId), - quantity: dto.quantity, - + if (article.trackingMode === TrackingMode.INDIVIDUAL) { + if (dto.quantity !== 1 || !dto.inventoryNumber?.trim()) { + throw new BadRequestException( + 'Einzelstücke benötigen Menge 1 und eine Inventarnummer', + ); } - if (dto.area) create['area'] = dto.area; - if (dto.batchNumber) create['batchNumber'] = dto.batchNumber; - if (dto.expiryDate) create['expiryDate'] = dto.expiryDate; - - result = await this.model.create(create); - - } - return result; - - } - - /** - * Move from Stock OUT - */ - async moveOut(dto: StockMovementOutDto) { - - let stockContent = await this.findById(dto.stockContentId); - if (!stockContent) throw new BadRequestException('consumeStock: Stock Content nicht gefunden'); - - - - let result = { - stockId: stockContent._id, - articleVariantId: stockContent.articleVariantId, - quantity: dto.quantity, - empty: false - } - - stockContent.quantity -= dto.quantity; - - if (stockContent.quantity < 0) { - throw new BadRequestException('Negativer Bestand'); - } - - if (stockContent.quantity === 0) { - result.empty = true; - await stockContent.deleteOne(); - } else { - await stockContent.save(); - } - - return result; - } - - - - // ================================= - // TRANSFER - // ================================= - - - - async transfer(dto: StockMovementTransferDto, isConsumable: boolean) { - const { articleVariantId, quantity, fromStockId, toStockId } = dto; - //const articleVariant = await this.articleService.findOne(articleVariantId); - //const isConsumable = articleVariant.article.category.isConsumable; - - if (isConsumable && !dto.batchNumber) throw new BadRequestException('Batch Nummer muss für Konsumierbare Artikel zum Verschieben vorhanden sein'); - //if (!articleVariant) throw new BadRequestException('Artikel Variante nicht gefunden'); - - if (isConsumable && dto.batchNumber) { - this.handelTransferConsumable(dto) - } else { - this.handelTransferNonConsumable(articleVariantId, fromStockId, toStockId, quantity) - } - - let retValue = { - //articleVariant, - isConsumable, - - } - } - - private async handelTransferConsumable(dto: StockMovementTransferDto) { - const { articleVariantId, fromStockId, batchNumber, quantity, toStockId, toArea } = dto; - - if (!batchNumber) throw new BadRequestException('handelTransferConsumable: Batch Nummer muss vorhanden sein'); - - //--- StockContent -- FROM - const stockContentFrom = await this.findConsumable({ articleVariantId, stockId: fromStockId, batchNumber }); - - if (!stockContentFrom) throw new BadRequestException('handelTransferConsumable: stockContentFrom nicht gefunden'); - if (stockContentFrom.quantity < quantity) throw new BadRequestException('handelTransferConsumable: Menge überschreitet Lagerbestand im Quell Lager'); - - //--- StockContent -- TO - const stockContetTo = await this.findConsumable({ articleVariantId, stockId: toStockId, batchNumber }); - - // From Content aktualisieren - stockContentFrom.quantity -= quantity; - if (stockContentFrom.quantity == 0) { - // Lager ist leergeräumt - await this.remove(fromStockId); - } else { - // neuer lagerbestand speichern - await stockContentFrom.save(); - } - - if (stockContetTo) { - // Besteand vom exisitierenden Lagerbestand erhöhen - stockContetTo.quantity += quantity; - await stockContetTo.save(); - } else { - // Besteand im Ziellager neu anlegen - let data = { - stockId: toStockId, - articleVariantId, - quantity, - batchNumber, + const inventoryNumber = dto.inventoryNumber.trim(); + const existing = await this.assets + .findOne({ inventoryNumber }) + .session(session) + .exec(); + if (existing) { + if ( + existing.articleId.toString() !== article._id.toString() || + existing.status !== 'withdrawn' + ) { + throw new ConflictException( + 'Inventarnummer gehört zu einem anderen Artikel oder ist bereits eingelagert', + ); + } + await this.assets.updateOne( + { _id: existing._id }, + { + $set: { + status: 'in-stock', + stockId: new Types.ObjectId(dto.stockId), + }, + }, + { session }, + ); + assetId = existing._id; + } else { + const [asset] = await this.assets.create( + [ + { + articleId: article._id, + inventoryNumber, + serialNumber: dto.serialNumber, + condition: dto.condition, + purpose: dto.purpose, + acquiredAt: dto.acquiredAt, + stockId: dto.stockId, + }, + ], + { session }, + ); + assetId = asset._id; } - if(toArea) data['area'] = toArea; - this.moveConsumableIn(data) + } else if ( + dto.inventoryNumber || + dto.serialNumber || + dto.condition || + dto.purpose || + dto.acquiredAt + ) { + throw new BadRequestException( + 'Exemplardaten sind nur bei Einzelstückführung erlaubt', + ); } - + return this.model + .findOneAndUpdate( + { + articleId: article._id, + stockId: dto.stockId, + batchId, + assetId, + area: dto.area ?? '', + }, + { $inc: { quantity: dto.quantity } }, + { new: true, upsert: true, runValidators: true, session }, + ) + .exec(); } - private async handelTransferNonConsumable(articleVariantId: string, fromStockId: string, toStockId: string, quantity: number) { - - const stockContentFrom = await this.findNonConsumable({ articleVariantId, stockId: fromStockId, }); - if (!stockContentFrom) throw new BadRequestException('from StockContent not found'); - - const stockContetTo = await this.findNonConsumable({ articleVariantId, stockId: toStockId, }); - if (stockContentFrom.quantity < quantity) throw new BadRequestException('Menge überschreitet Lagerbestand im Quell Lager'); - - stockContentFrom.quantity -= quantity; - if (stockContentFrom.quantity == 0) { - // Lager ist leergeräumt - await this.remove(fromStockId); - } else { - // neuer lagerbestand speichern - await stockContentFrom.save(); - } - - if (stockContetTo) { - // Besteand vom exisitierenden Lagerbestand erhöhen - stockContetTo.quantity += quantity; - await stockContetTo.save(); - } else { - // Besteand im Ziellager neu anlegen - this.moveNonConsumableIn({ - stockId: toStockId, - articleVariantId, - quantity - }) - } - + async moveOut(dto: StockMovementOutDto, session: ClientSession) { + this.positive(dto.quantity); + const content = await this.model + .findOneAndUpdate( + { + _id: dto.stockContentId, + articleId: { $exists: true }, + quantity: { $gte: dto.quantity }, + }, + { $inc: { quantity: -dto.quantity } }, + { new: true, session }, + ) + .exec(); + if (!content) + throw new BadRequestException( + 'Bestand nicht gefunden oder Menge überschreitet Bestand', + ); + if (content.assetId && dto.quantity !== 1) + throw new BadRequestException( + 'Einzelstücke können nur vollständig entnommen werden', + ); + if (content.quantity === 0) + await this.model.deleteOne({ _id: content._id }, { session }); + if (content.assetId) + await this.assets.updateOne( + { _id: content.assetId }, + { + $set: { status: 'withdrawn', stockId: null }, + }, + { session }, + ); + return content; } + async transfer(dto: StockMovementTransferDto, session: ClientSession) { + this.positive(dto.quantity); + const source = await this.model + .findById(dto.stockContentId) + .session(session) + .exec(); + if (!source?.articleId) + throw new NotFoundException('Bestand nicht gefunden'); + await this.validateStock(dto.toStockId, dto.toArea, session); + if ( + source.stockId.toString() === dto.toStockId && + source.area === (dto.toArea ?? '') + ) { + throw new BadRequestException('Quelle und Ziel sind identisch'); + } + const content = await this.moveOut(dto, session); + await this.model + .findOneAndUpdate( + { + articleId: source.articleId, + stockId: dto.toStockId, + batchId: source.batchId ?? null, + assetId: source.assetId ?? null, + area: dto.toArea ?? '', + }, + { $inc: { quantity: dto.quantity } }, + { new: true, upsert: true, runValidators: true, session }, + ) + .exec(); + if (source.assetId) + await this.assets.updateOne( + { _id: source.assetId }, + { + $set: { + status: 'in-stock', + stockId: new Types.ObjectId(dto.toStockId), + }, + }, + { session }, + ); + return content; + } -} + private positive(quantity: number) { + if (!Number.isFinite(quantity) || quantity <= 0) + throw new BadRequestException('Menge muss größer als 0 sein'); + } -/* - async increaseOrCreate( - data: { - articleId: string; - locationId: string; - quantity: number; - expiryDate?: Date; - batchNumber?: string; - }, - session?: ClientSession, + private async validateStock( + stockId: string, + area: string | undefined, + session: ClientSession, ) { - const filter: any = { - articleId: data.articleId, - locationId: data.locationId, - expiryDate: data.expiryDate ?? null, - batchNumber: data.batchNumber ?? null, - }; - - const stock = await this.model - .findOne(filter) - .session(session ?? null); - - if (stock) { - stock.quantity += data.quantity; - await stock.save({ session }); - } else { - await this.model.create([data], { session }); - } + const stock = await this.stocks.findById(stockId).session(session).exec(); + if (!stock) throw new NotFoundException('Lager nicht gefunden'); + if (area && !stock.areas?.includes(area)) + throw new BadRequestException('Lagerbereich ist nicht vorhanden'); } -*/ \ No newline at end of file +} diff --git a/apps/backend/src/inventory/stock-content/stock-content.service.ts b/apps/backend/src/inventory/stock-content/stock-content.service.ts index 766a8a7..10fc651 100644 --- a/apps/backend/src/inventory/stock-content/stock-content.service.ts +++ b/apps/backend/src/inventory/stock-content/stock-content.service.ts @@ -1,234 +1,55 @@ -import { Injectable, NotFoundException } from '@nestjs/common'; +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; +import { ClientSession, Model, Types } from 'mongoose'; import { StockContent } from '../_entities/stock-content.entity'; -import { StockContentConsumableInDto, StockContentNonConsumableInDto, StockContentFindConsumableDto, StockContentFindNonConsumableDto, StockContentDto } from '../_dto/stock-content.dto'; import { StockContentRepository } from './stock-content.repository'; -import { StockMovementInDto, StockMovementOutDto, StockMovementTransferDto } from '../_dto/stock-movement.dto'; -import { ArticleVariantService } from 'src/catalog/article-variant/article-variant.service'; -import { StockService } from '../stock/stock.service'; +import { + StockMovementInDto, + StockMovementOutDto, + StockMovementTransferDto, +} from '../_dto/stock-movement.dto'; @Injectable() export class StockContentService { - - constructor( - @InjectModel(StockContent.name) private stockContentModel: Model, - private readonly stockContentRepo: StockContentRepository, - private readonly articleVariantService: ArticleVariantService, - // private readonly stockService: StockService - - ) { } - - async findAll() { - let stockContent = await this.stockContentModel.aggregate([ - { - $lookup: { - from: 'articlevariants', - localField: 'articleVariantId', - foreignField: '_id', - as: 'articleVariant', - pipeline: [ - { - $addFields: { id: "$_id" } - }, - { - $lookup: { - from: 'articles', - localField: 'articleId', - foreignField: '_id', - as: 'article', - pipeline: [ - { - $addFields: { id: "$_id" } - }, - { - $project: { - __v: 0, - _id: 0 - } - } - ] - } - }, - { - $unwind: { - path: "$article", - preserveNullAndEmptyArrays: true - } - }, - - { - $project: { - articleId: 0, - __v: 0, - _id: 0 - } - } - ] - }, - - }, - { - $unwind: { - path: "$articleVariant", - preserveNullAndEmptyArrays: true - } - }, - { - $lookup: { - from: 'stocks', - localField: 'stockId', - foreignField: '_id', - as: 'stock', - pipeline: [ - { - $addFields: { id: "$_id" } - }, - - { - $lookup: { - from: 'locations', - localField: 'locationId', - foreignField: '_id', - as: 'location', - pipeline: [ - { - $addFields: { id: "$_id" } - }, - { - $project: { - __v: 0, - _id: 0 - } - } - ] - } - }, - { - $unwind: { - path: "$location", - preserveNullAndEmptyArrays: true - } - }, - { - $project: { - // articleId:0, - __v: 0, - _id: 0, - locationId:0 - } - } - ] - }, - - }, - { - $unwind: { - path: "$stock", - preserveNullAndEmptyArrays: true - } - }, - { - $addFields: { id: "$_id" } - }, - { - $project: { - id: 1, - _id: 0, - stock: 1, - batchNumber: 1, - area: 1, - quantity: 1, - articleVariant: 1, - - } - } - ]); - - return stockContent; - return this.stockContentModel.aggregate([ - { - $lookup: { - from: 'articlevariants', - localField: 'articleVariantId', - foreignField: '_id', - as: 'articleVariant', - } - }, - { - $lookup: { - from: 'stocks', - localField: 'stockId', - foreignField: '_id', - as: 'stock', - } - }, - { $unwind: '$stock' }, - { - $project: { - - articleVariantId: 1, - stockId: 1, - batchNumber: 1, - area: 1, - quantity: 1 - } - } - ]) - - } - - async findOne(id: string) { - const item = await this.stockContentModel.findById(id); - if (!item) throw new NotFoundException('Stock Content nicht gefunden'); - return item; - } - - - remove(id: string) { - return this.stockContentRepo.remove(id); - } - - - //--- Stock IN - async moveIn(dto: StockMovementInDto): Promise { - - const articleVariant = await this.articleVariantService.findOne(dto.articleVariantId); - const avId = articleVariant._id.toString(); - const isConsumable = articleVariant.article.category.isConsumable; - - let moveData = { - ...dto, - articleVariantId: avId, - } - - if (isConsumable) { - return await this.stockContentRepo.moveConsumableIn(moveData); - } else { - return await this.stockContentRepo.moveNonConsumableIn(moveData); - - } - } - - //--- Stock OUT - moveOut(dto: StockMovementOutDto) { - return this.stockContentRepo.moveOut(dto); - } - - - //--- Stock Transfer - async transfer(dto: StockMovementTransferDto) { - - const articleVariant = await this.articleVariantService.findOne(dto.articleVariantId); - const avId = articleVariant._id.toString(); - const isConsumable = articleVariant.article.category.isConsumable; - - this.stockContentRepo.transfer(dto, isConsumable); - - return { - articleVariant, - isConsumable, - } - - } + constructor( + @InjectModel(StockContent.name) private readonly model: Model, + private readonly repository: StockContentRepository, + ) {} + findAll() { + return this.model + .find({ articleId: { $exists: true } }) + .populate('articleId') + .populate({ path: 'stockId', populate: { path: 'locationId' } }) + .populate('batchId') + .populate('assetId') + .exec(); + } + async findOne(id: string) { + if (!Types.ObjectId.isValid(id)) + throw new BadRequestException('Ungültige Bestands-ID'); + const item = await this.model + .findById(id) + .populate('articleId') + .populate('batchId') + .populate('assetId') + .exec(); + if (!item) throw new NotFoundException('Bestand nicht gefunden'); + return item; + } + remove(_id: string): never { + throw new BadRequestException('Bestände nur über Auslagerungen verändern'); + } + moveIn(dto: StockMovementInDto, session: ClientSession) { + return this.repository.moveIn(dto, session); + } + moveOut(dto: StockMovementOutDto, session: ClientSession) { + return this.repository.moveOut(dto, session); + } + transfer(dto: StockMovementTransferDto, session: ClientSession) { + return this.repository.transfer(dto, session); + } } diff --git a/apps/backend/src/inventory/stock/stock.module.ts b/apps/backend/src/inventory/stock/stock.module.ts index 8c0311d..66a85a9 100644 --- a/apps/backend/src/inventory/stock/stock.module.ts +++ b/apps/backend/src/inventory/stock/stock.module.ts @@ -6,7 +6,7 @@ import { MongooseModule } from '@nestjs/mongoose'; import { Stock, StockSchema } from '../_entities/stock.entity'; import { StockController } from '../_controllers/stock.controller'; import { StockService } from './stock.service'; -import { LocationsModule } from 'src/locations/locations.module'; +import { LocationsModule } from '../../locations/locations.module'; @Module({ diff --git a/apps/backend/src/inventory/stock/stock.service.ts b/apps/backend/src/inventory/stock/stock.service.ts index d67772c..add4740 100644 --- a/apps/backend/src/inventory/stock/stock.service.ts +++ b/apps/backend/src/inventory/stock/stock.service.ts @@ -5,7 +5,7 @@ import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; import { Stock } from '../_entities/stock.entity'; import { StockCreateDto, StockDto, StockRowDto, StockUpdateDto } from '../_dto/stock.dto'; -import { LocationsService } from 'src/locations/locations.service'; +import { LocationsService } from '../../locations/locations.service'; @Injectable() diff --git a/apps/backend/src/locations/dto/location.dto.ts b/apps/backend/src/locations/dto/location.dto.ts index 164b5b7..8b4fd21 100644 --- a/apps/backend/src/locations/dto/location.dto.ts +++ b/apps/backend/src/locations/dto/location.dto.ts @@ -5,7 +5,7 @@ import { Types } from 'mongoose'; export class LocationCreateDto { @IsString() - name: string; + name!: string; @IsOptional() @IsString() @@ -20,32 +20,32 @@ export class LocationUpdateDto extends PartialType(LocationCreateDto) { } export class LocationNodeDto { @IsString() - _id: Types.ObjectId; + _id!: Types.ObjectId; @IsString() - name: string; + name!: string; - parentLocationId: Types.ObjectId; - children: LocationNodeDto[]; + parentLocationId?: Types.ObjectId; + children!: LocationNodeDto[]; } export class LocationDto { - id: string; - name: string; + id!: string; + name!: string; parentLocation?: LocationViewDto; children?: LocationViewDto[]; } export class LocationViewDto { - id: string; - name: string; + id!: string; + name!: string; parentLocation?: string; } export class LocationRawDto { - _id: string; - name: string; + _id!: string; + name!: string; parentLocationId?: Types.ObjectId; } diff --git a/apps/backend/src/locations/entities/location.entity.ts b/apps/backend/src/locations/entities/location.entity.ts index c46554b..8384dd5 100644 --- a/apps/backend/src/locations/entities/location.entity.ts +++ b/apps/backend/src/locations/entities/location.entity.ts @@ -4,13 +4,13 @@ import { Document, Types } from 'mongoose'; @Schema({ timestamps: true }) export class Location extends Document { @Prop({ required: true }) - name: string; + name!: string; @Prop() description?: string; @Prop({ type: Types.ObjectId, ref: 'Location' }) - parentLocationId: Types.ObjectId + parentLocationId?: Types.ObjectId } diff --git a/apps/backend/src/locations/locations.service.ts b/apps/backend/src/locations/locations.service.ts index 1fa5540..e53f7ad 100644 --- a/apps/backend/src/locations/locations.service.ts +++ b/apps/backend/src/locations/locations.service.ts @@ -17,7 +17,7 @@ export class LocationsService { return this.locationModel.create({ name, - parentLocationId: new Types.ObjectId(parentLocationId), + ...(parentLocationId ? { parentLocationId: new Types.ObjectId(parentLocationId) } : {}), description }); } diff --git a/apps/backend/src/products/_dto/article-group.dto.ts b/apps/backend/src/products/_dto/article-group.dto.ts new file mode 100644 index 0000000..64a736b --- /dev/null +++ b/apps/backend/src/products/_dto/article-group.dto.ts @@ -0,0 +1,13 @@ +import { IsNotEmpty, IsOptional, IsString } from 'class-validator'; +import { PartialType } from '@nestjs/mapped-types'; + +export class ArticleGroupCreateDto { + @IsString() + @IsNotEmpty() + name!: string; + + @IsOptional() + @IsString() + description?: string; +} +export class ArticleGroupUpdateDto extends PartialType(ArticleGroupCreateDto) {} diff --git a/apps/backend/src/catalog/_dto/article-variant.dto.ts b/apps/backend/src/products/_dto/article-variant.dto.ts similarity index 77% rename from apps/backend/src/catalog/_dto/article-variant.dto.ts rename to apps/backend/src/products/_dto/article-variant.dto.ts index b276228..6a5734d 100644 --- a/apps/backend/src/catalog/_dto/article-variant.dto.ts +++ b/apps/backend/src/products/_dto/article-variant.dto.ts @@ -4,17 +4,17 @@ import { ArticleDto } from './article.dto'; import { PartialType } from '@nestjs/mapped-types'; export class ArticleVariantDto { - _id: Types.ObjectId; - article: ArticleDto; - manufacturer: ManufacturerDto; + _id!: Types.ObjectId; + article!: ArticleDto; + manufacturer!: ManufacturerDto; supplierArticleNumber?: string; packagingUnit?: string; extra?: Record; } export class ArticleVariantCreateDto { - articleId: Types.ObjectId; - manufacturerId: Types.ObjectId; + articleId!: Types.ObjectId; + manufacturerId!: Types.ObjectId; supplierArticleNumber?: string; packagingUnit?: string; extra?: Record; diff --git a/apps/backend/src/products/_dto/article.dto.ts b/apps/backend/src/products/_dto/article.dto.ts new file mode 100644 index 0000000..c22c7a4 --- /dev/null +++ b/apps/backend/src/products/_dto/article.dto.ts @@ -0,0 +1,99 @@ +import { PartialType } from '@nestjs/mapped-types'; +import { Type } from 'class-transformer'; +import { + IsArray, + IsBoolean, + IsEnum, + IsMongoId, + IsNotEmpty, + IsNumber, + IsObject, + IsOptional, + IsString, + Min, + ValidateNested, +} from 'class-validator'; +import { TrackingMode } from '../_entities/article.entity'; +import { CategoryDto } from './category.dto'; +import { ManufacturerDto } from './manufacturer.dto'; + +export class ArticlePackagingDto { + @IsString() + @IsNotEmpty() + name!: string; + + @IsNumber() + @Min(Number.MIN_VALUE) + quantityInBaseUnits!: number; + + @IsOptional() + @IsString() + barcode?: string; +} + +export class ArticleCreateDto { + @IsString() + @IsNotEmpty() + articleNumber!: string; + + @IsString() + @IsNotEmpty() + name!: string; + + @IsOptional() + @IsString() + description?: string; + + @IsOptional() + @IsMongoId() + categoryId?: string | null; + + @IsOptional() + @IsMongoId() + groupId?: string | null; + + @IsOptional() + @IsMongoId() + manufacturerId?: string | null; + + @IsOptional() + @IsString() + manufacturerArticleNumber?: string; + + @IsOptional() + @IsString() + barcode?: string; + + @IsString() + @IsNotEmpty() + baseUnit!: string; + + @IsBoolean() + isConsumable!: boolean; + + @IsEnum(TrackingMode) + trackingMode!: TrackingMode; + + @IsBoolean() + tracksExpiryDate!: boolean; + + @IsOptional() + @IsObject() + attributes?: Record; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ArticlePackagingDto) + packaging?: ArticlePackagingDto[]; +} + +export class ArticleUpdateDto extends PartialType(ArticleCreateDto) {} + +export interface ArticleDto extends ArticleCreateDto { + _id: string; + category?: CategoryDto; + manufacturer?: ManufacturerDto; + group?: { _id: string; name: string }; + archivedAt?: Date | null; +} diff --git a/apps/backend/src/catalog/_dto/category.dto.ts b/apps/backend/src/products/_dto/category.dto.ts similarity index 78% rename from apps/backend/src/catalog/_dto/category.dto.ts rename to apps/backend/src/products/_dto/category.dto.ts index a3227aa..ea01e86 100644 --- a/apps/backend/src/catalog/_dto/category.dto.ts +++ b/apps/backend/src/products/_dto/category.dto.ts @@ -2,8 +2,8 @@ import { PartialType } from "@nestjs/mapped-types"; import { Types } from "mongoose"; export class CategoryCreateDto { - name: string; - isConsumable: boolean; + name!: string; + isConsumable!: boolean; description?: string; requiredAttributes?: Record; parentCategoryId?: Types.ObjectId; @@ -13,9 +13,9 @@ export class CategoryCreateDto { export class CategoryUpdateDto extends PartialType(CategoryCreateDto) {} export class CategoryDto { - _id: Types.ObjectId; - name: string; - isConsumable: boolean; + _id!: Types.ObjectId; + name!: string; + isConsumable!: boolean; description?: string; requiredAttributes?: Record; parentCategoryId?: Types.ObjectId; diff --git a/apps/backend/src/catalog/_dto/manufacturer.dto.ts b/apps/backend/src/products/_dto/manufacturer.dto.ts similarity index 72% rename from apps/backend/src/catalog/_dto/manufacturer.dto.ts rename to apps/backend/src/products/_dto/manufacturer.dto.ts index 6e4b03f..1ba9ad2 100644 --- a/apps/backend/src/catalog/_dto/manufacturer.dto.ts +++ b/apps/backend/src/products/_dto/manufacturer.dto.ts @@ -3,17 +3,17 @@ import { Types } from "mongoose"; export class ManufacturerCreateDto { @IsString() - name: string; + name!: string; } export class ManufacturerDto { - _id: Types.ObjectId; - name: string; + _id!: Types.ObjectId; + name!: string; } export class ManufacturerUpdateDto { @IsOptional() @IsString() - name: string; + name?: string; } diff --git a/apps/backend/src/products/_dto/upsert-article.dto.ts b/apps/backend/src/products/_dto/upsert-article.dto.ts new file mode 100644 index 0000000..b06f1b4 --- /dev/null +++ b/apps/backend/src/products/_dto/upsert-article.dto.ts @@ -0,0 +1,13 @@ +import { ArticleUpdateDto } from './article.dto'; + +export class ArticleUpsertDto extends ArticleUpdateDto {} + +// Retained only for the unregistered legacy variant module and migration reference. +export class ArticleVariantUpsertDto { + _id?: string; + manufacturerId?: string; + supplierArticleNumber?: string; + packagingUnit?: string; + extra?: Record; + deleted?: boolean; +} diff --git a/apps/backend/src/products/_entities/article-group.entity.ts b/apps/backend/src/products/_entities/article-group.entity.ts new file mode 100644 index 0000000..f2d4834 --- /dev/null +++ b/apps/backend/src/products/_entities/article-group.entity.ts @@ -0,0 +1,12 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { Document } from 'mongoose'; + +@Schema({ timestamps: true }) +export class ArticleGroup extends Document { + @Prop({ required: true, trim: true }) + name!: string; + + @Prop() + description?: string; +} +export const ArticleGroupSchema = SchemaFactory.createForClass(ArticleGroup); diff --git a/apps/backend/src/catalog/_entities/article-variant.entity.ts b/apps/backend/src/products/_entities/article-variant.entity.ts similarity index 89% rename from apps/backend/src/catalog/_entities/article-variant.entity.ts rename to apps/backend/src/products/_entities/article-variant.entity.ts index 07fea0f..b6a3ce7 100644 --- a/apps/backend/src/catalog/_entities/article-variant.entity.ts +++ b/apps/backend/src/products/_entities/article-variant.entity.ts @@ -4,10 +4,10 @@ import { Document, Types } from 'mongoose'; @Schema() export class ArticleVariant extends Document { @Prop({ type: Types.ObjectId, ref: 'Article', required: true }) - articleId: Types.ObjectId; + articleId!: Types.ObjectId; @Prop({ type: Types.ObjectId, ref: 'Manufacturer', required: true }) - manufacturerId: Types.ObjectId; + manufacturerId!: Types.ObjectId; @Prop() supplierArticleNumber?: string; diff --git a/apps/backend/src/products/_entities/article.entity.ts b/apps/backend/src/products/_entities/article.entity.ts new file mode 100644 index 0000000..102a5a5 --- /dev/null +++ b/apps/backend/src/products/_entities/article.entity.ts @@ -0,0 +1,82 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { Document, Schema as MongooseSchema, Types } from 'mongoose'; + +export enum TrackingMode { + QUANTITY = 'quantity', + BATCH = 'batch', + INDIVIDUAL = 'individual', +} + +@Schema({ _id: false }) +export class ArticlePackaging { + @Prop({ required: true, trim: true }) + name!: string; + + @Prop({ required: true, min: Number.MIN_VALUE }) + quantityInBaseUnits!: number; + + @Prop({ trim: true }) + barcode?: string; +} +export const ArticlePackagingSchema = + SchemaFactory.createForClass(ArticlePackaging); + +@Schema({ timestamps: true }) +export class Article extends Document { + @Prop({ required: true, trim: true }) + articleNumber!: string; + + @Prop({ required: true, trim: true }) + name!: string; + + @Prop() + description?: string; + + @Prop({ type: Types.ObjectId, ref: 'Category' }) + categoryId?: Types.ObjectId; + + @Prop({ type: Types.ObjectId, ref: 'ArticleGroup' }) + groupId?: Types.ObjectId; + + @Prop({ type: Types.ObjectId, ref: 'Manufacturer' }) + manufacturerId?: Types.ObjectId; + + @Prop() + manufacturerArticleNumber?: string; + + @Prop() + barcode?: string; + + @Prop({ required: true, trim: true }) + baseUnit!: string; + + @Prop({ required: true, default: false }) + isConsumable!: boolean; + + @Prop({ type: String, enum: TrackingMode, default: TrackingMode.QUANTITY }) + trackingMode!: TrackingMode; + + @Prop({ default: false }) + tracksExpiryDate!: boolean; + + @Prop({ type: Map, of: MongooseSchema.Types.Mixed }) + attributes?: Map; + + @Prop({ type: [ArticlePackagingSchema], default: [] }) + packaging!: ArticlePackaging[]; + + @Prop({ type: Date, default: null }) + archivedAt?: Date | null; +} + +export const ArticleSchema = SchemaFactory.createForClass(Article); +// Partial index permits inspecting legacy records before the explicit migration. +ArticleSchema.index( + { articleNumber: 1 }, + { + unique: true, + partialFilterExpression: { articleNumber: { $type: 'string' } }, + }, +); +ArticleSchema.index({ categoryId: 1 }); +ArticleSchema.index({ groupId: 1 }); diff --git a/apps/backend/src/catalog/_entities/category.entity.ts b/apps/backend/src/products/_entities/category.entity.ts similarity index 90% rename from apps/backend/src/catalog/_entities/category.entity.ts rename to apps/backend/src/products/_entities/category.entity.ts index 693d98b..8c1a0cd 100644 --- a/apps/backend/src/catalog/_entities/category.entity.ts +++ b/apps/backend/src/products/_entities/category.entity.ts @@ -5,13 +5,13 @@ import { Document, Types } from 'mongoose'; @Schema({ timestamps: true }) export class Category extends Document { @Prop({ required: true }) - name: string; + name!: string; @Prop() description?: string; @Prop({ default: true }) - isConsumable: boolean; + isConsumable!: boolean; @Prop({ type: Map, of: String }) requiredAttributes?: Map; diff --git a/apps/backend/src/catalog/_entities/manufacturer.entity.ts b/apps/backend/src/products/_entities/manufacturer.entity.ts similarity index 78% rename from apps/backend/src/catalog/_entities/manufacturer.entity.ts rename to apps/backend/src/products/_entities/manufacturer.entity.ts index 6d5c62d..9e23a93 100644 --- a/apps/backend/src/catalog/_entities/manufacturer.entity.ts +++ b/apps/backend/src/products/_entities/manufacturer.entity.ts @@ -5,7 +5,7 @@ import { Document, Types } from 'mongoose'; @Schema() export class Manufacturer extends Document { @Prop({ required: true }) - name: string; + name!: string; } diff --git a/apps/backend/src/products/article-groups/article-groups.controller.ts b/apps/backend/src/products/article-groups/article-groups.controller.ts new file mode 100644 index 0000000..1ce53ee --- /dev/null +++ b/apps/backend/src/products/article-groups/article-groups.controller.ts @@ -0,0 +1,26 @@ +import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common'; +import { ArticleGroupsService } from './article-groups.service'; +import { + ArticleGroupCreateDto, + ArticleGroupUpdateDto, +} from '../_dto/article-group.dto'; + +@Controller('article-groups') +export class ArticleGroupsController { + constructor(private readonly service: ArticleGroupsService) {} + + @Get() findAll() { + return this.service.findAll(); + } + + @Post() create(@Body() dto: ArticleGroupCreateDto) { + return this.service.create(dto); + } + + @Patch(':id') update( + @Param('id') id: string, + @Body() dto: ArticleGroupUpdateDto, + ) { + return this.service.update(id, dto); + } +} diff --git a/apps/backend/src/products/article-groups/article-groups.module.ts b/apps/backend/src/products/article-groups/article-groups.module.ts new file mode 100644 index 0000000..852c358 --- /dev/null +++ b/apps/backend/src/products/article-groups/article-groups.module.ts @@ -0,0 +1,19 @@ +import { Module } from '@nestjs/common'; +import { MongooseModule } from '@nestjs/mongoose'; +import { + ArticleGroup, + ArticleGroupSchema, +} from '../_entities/article-group.entity'; +import { ArticleGroupsController } from './article-groups.controller'; +import { ArticleGroupsService } from './article-groups.service'; + +@Module({ + imports: [ + MongooseModule.forFeature([ + { name: ArticleGroup.name, schema: ArticleGroupSchema }, + ]), + ], + controllers: [ArticleGroupsController], + providers: [ArticleGroupsService], +}) +export class ArticleGroupsModule {} diff --git a/apps/backend/src/products/article-groups/article-groups.service.ts b/apps/backend/src/products/article-groups/article-groups.service.ts new file mode 100644 index 0000000..4b655ea --- /dev/null +++ b/apps/backend/src/products/article-groups/article-groups.service.ts @@ -0,0 +1,33 @@ +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { InjectModel } from '@nestjs/mongoose'; +import { Model, Types } from 'mongoose'; +import { ArticleGroup } from '../_entities/article-group.entity'; +import { + ArticleGroupCreateDto, + ArticleGroupUpdateDto, +} from '../_dto/article-group.dto'; + +@Injectable() +export class ArticleGroupsService { + constructor( + @InjectModel(ArticleGroup.name) private readonly model: Model, + ) {} + findAll() { + return this.model.find().sort({ name: 1 }).exec(); + } + create(dto: ArticleGroupCreateDto) { + return this.model.create(dto); + } + update(id: string, dto: ArticleGroupUpdateDto) { + if (!Types.ObjectId.isValid(id)) + throw new BadRequestException('Ungültige Gruppen-ID'); + return this.model + .findByIdAndUpdate(id, dto, { new: true, runValidators: true }) + .orFail(() => new NotFoundException('Produktgruppe nicht gefunden')) + .exec(); + } +} diff --git a/apps/backend/src/catalog/article-variant/article-variant.controller.ts b/apps/backend/src/products/article-variant/article-variant.controller.ts similarity index 100% rename from apps/backend/src/catalog/article-variant/article-variant.controller.ts rename to apps/backend/src/products/article-variant/article-variant.controller.ts diff --git a/apps/backend/src/catalog/article-variant/article-variant.module.ts b/apps/backend/src/products/article-variant/article-variant.module.ts similarity index 100% rename from apps/backend/src/catalog/article-variant/article-variant.module.ts rename to apps/backend/src/products/article-variant/article-variant.module.ts diff --git a/apps/backend/src/catalog/article-variant/article-variant.service.ts b/apps/backend/src/products/article-variant/article-variant.service.ts similarity index 100% rename from apps/backend/src/catalog/article-variant/article-variant.service.ts rename to apps/backend/src/products/article-variant/article-variant.service.ts diff --git a/apps/backend/src/catalog/article-variant/querys/article-variant-get.query.ts b/apps/backend/src/products/article-variant/querys/article-variant-get.query.ts similarity index 100% rename from apps/backend/src/catalog/article-variant/querys/article-variant-get.query.ts rename to apps/backend/src/products/article-variant/querys/article-variant-get.query.ts diff --git a/apps/backend/src/catalog/article-variant/repository/article-variant.repository.ts b/apps/backend/src/products/article-variant/repository/article-variant.repository.ts similarity index 96% rename from apps/backend/src/catalog/article-variant/repository/article-variant.repository.ts rename to apps/backend/src/products/article-variant/repository/article-variant.repository.ts index f1a1f73..0049879 100644 --- a/apps/backend/src/catalog/article-variant/repository/article-variant.repository.ts +++ b/apps/backend/src/products/article-variant/repository/article-variant.repository.ts @@ -1,10 +1,10 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; -import { ArticleVariantCreateDto, ArticleVariantDto, ArticleVariantUpdateDto } from 'src/catalog/_dto/article-variant.dto'; -import { ArticleVariant } from 'src/catalog/_entities/article-variant.entity'; +import { ArticleVariantCreateDto, ArticleVariantDto, ArticleVariantUpdateDto } from '../../_dto/article-variant.dto'; +import { ArticleVariant } from '../../_entities/article-variant.entity'; import { articleVariantGetQuery } from '../querys/article-variant-get.query'; -import { ArticleVariantUpsertDto } from 'src/catalog/_dto/upsert-article.dto'; +import { ArticleVariantUpsertDto } from '../../_dto/upsert-article.dto'; import { BulkWriteResult } from 'mongodb'; @Injectable() diff --git a/apps/backend/src/products/articles/article-validation.spec.ts b/apps/backend/src/products/articles/article-validation.spec.ts new file mode 100644 index 0000000..56a18ad --- /dev/null +++ b/apps/backend/src/products/articles/article-validation.spec.ts @@ -0,0 +1,84 @@ +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; +import { ArticleCreateDto } from '../_dto/article.dto'; +import { TrackingMode } from '../_entities/article.entity'; +import { ArticleRepository } from './repository/article.repository'; +import { ConflictException } from '@nestjs/common'; +import { Model, Connection, Types } from 'mongoose'; +import { Article } from '../_entities/article.entity'; + +const article = { + articleNumber: 'TEST-001', + name: 'Banane', + baseUnit: 'Stück', + isConsumable: true, + trackingMode: TrackingMode.QUANTITY, + tracksExpiryDate: false, +}; + +describe('Gemeinsames Artikelmodell', () => { + it('akzeptiert einen Artikel ohne Hersteller und Varianten', async () => { + const dto = plainToInstance(ArticleCreateDto, article); + expect( + await validate(dto, { whitelist: true, forbidNonWhitelisted: true }), + ).toEqual([]); + }); + + it('weist die alte Variantenstruktur zurück', async () => { + const dto = plainToInstance(ArticleCreateDto, { ...article, variants: [] }); + expect( + ( + await validate(dto, { whitelist: true, forbidNonWhitelisted: true }) + ).map((error) => error.property), + ).toContain('variants'); + }); + + it('weist eine Verpackung mit Inhalt null zurück', async () => { + const dto = plainToInstance(ArticleCreateDto, { + ...article, + packaging: [{ name: 'Packung', quantityInBaseUnits: 0 }], + }); + expect(await validate(dto)).not.toEqual([]); + }); + + it('verlangt Chargenführung für Ablaufdaten', async () => { + const repository = new ArticleRepository( + {} as Model
, + {} as Connection, + ); + await expect( + repository.create({ ...article, tracksExpiryDate: true }), + ).rejects.toThrow('Ablaufdaten erfordern Chargenführung'); + }); + + it('verlangt Stück als Einheit bei Einzelstückführung', async () => { + const repository = new ArticleRepository( + {} as Model
, + {} as Connection, + ); + await expect( + repository.create({ + ...article, + baseUnit: 'kg', + trackingMode: TrackingMode.INDIVIDUAL, + }), + ).rejects.toThrow('Basiseinheit Stück'); + }); + + it('verhindert Änderungen der Einheit nach einer Lagerbuchung', async () => { + const current = { ...article, _id: new Types.ObjectId().toString() }; + const connection = { + collection: jest.fn(() => ({ + findOne: jest.fn().mockResolvedValue({ quantity: 1 }), + })), + }; + const repository = new ArticleRepository( + {} as Model
, + connection as unknown as Connection, + ); + jest.spyOn(repository, 'findOne').mockResolvedValue(current); + await expect( + repository.update(current._id, { baseUnit: 'kg' }), + ).rejects.toBeInstanceOf(ConflictException); + }); +}); diff --git a/apps/backend/src/catalog/articles/articles.controller.ts b/apps/backend/src/products/articles/articles.controller.ts similarity index 61% rename from apps/backend/src/catalog/articles/articles.controller.ts rename to apps/backend/src/products/articles/articles.controller.ts index 594115d..6cff550 100644 --- a/apps/backend/src/catalog/articles/articles.controller.ts +++ b/apps/backend/src/products/articles/articles.controller.ts @@ -1,19 +1,24 @@ -import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; +import { + Controller, + Get, + Post, + Body, + Patch, + Param, + Delete, +} from '@nestjs/common'; import { ArticlesService } from './articles.service'; - -import { ArticleCreateDto, ArticleUpdateDto } from '../_dto/article.dto'; +import { ArticleCreateDto, ArticleUpdateDto } from '../_dto/article.dto'; import { ArticleUpsertDto } from '../_dto/upsert-article.dto'; @Controller('articles') export class ArticlesController { - constructor( - private readonly articlesService: ArticlesService, - ) { } + constructor(private readonly articlesService: ArticlesService) {} @Post() create(@Body() dto: ArticleCreateDto) { - console.log('Create Artikel') + console.log('Create Artikel'); return this.articlesService.create(dto); } @@ -22,23 +27,24 @@ export class ArticlesController { return this.articlesService.findAll(); } + @Get('migration-status') + migrationStatus() { + return this.articlesService.migrationStatus(); + } + @Get(':id') findOne(@Param('id') id: string) { - console.log('Find one') + console.log('Find one'); return this.articlesService.findOne(id); } @Patch(':id') - update(@Param('id') id: string, @Body() updateArticleDto: ArticleUpsertDto) { + update(@Param('id') id: string, @Body() updateArticleDto: ArticleUpsertDto) { return this.articlesService.update(id, updateArticleDto); - - } + } @Delete(':id') remove(@Param('id') id: string) { return this.articlesService.remove(id); } - - - } diff --git a/apps/backend/src/catalog/articles/articles.module.ts b/apps/backend/src/products/articles/articles.module.ts similarity index 53% rename from apps/backend/src/catalog/articles/articles.module.ts rename to apps/backend/src/products/articles/articles.module.ts index f556197..909374d 100644 --- a/apps/backend/src/catalog/articles/articles.module.ts +++ b/apps/backend/src/products/articles/articles.module.ts @@ -1,22 +1,16 @@ import { Module } from '@nestjs/common'; -import { ArticlesService } from './articles.service'; -import { ArticlesController } from './articles.controller'; - import { MongooseModule } from '@nestjs/mongoose'; import { Article, ArticleSchema } from '../_entities/article.entity'; -import { ArticleVariantModule } from '../article-variant/article-variant.module'; +import { ArticlesService } from './articles.service'; +import { ArticlesController } from './articles.controller'; import { ArticleRepository } from './repository/article.repository'; - @Module({ - imports: [ - MongooseModule.forFeature([ - { name: Article.name, schema: ArticleSchema }, - ]), - ArticleVariantModule - ], + imports: [ + MongooseModule.forFeature([{ name: Article.name, schema: ArticleSchema }]), + ], controllers: [ArticlesController], - providers: [ArticlesService,ArticleRepository], - exports:[ArticlesService] + providers: [ArticlesService, ArticleRepository], + exports: [ArticlesService], }) -export class ArticlesModule { } +export class ArticlesModule {} diff --git a/apps/backend/src/products/articles/articles.service.ts b/apps/backend/src/products/articles/articles.service.ts new file mode 100644 index 0000000..6473340 --- /dev/null +++ b/apps/backend/src/products/articles/articles.service.ts @@ -0,0 +1,26 @@ +import { Injectable } from '@nestjs/common'; +import { ArticleRepository } from './repository/article.repository'; +import { ArticleCreateDto, ArticleUpdateDto } from '../_dto/article.dto'; + +@Injectable() +export class ArticlesService { + constructor(private readonly repository: ArticleRepository) {} + create(dto: ArticleCreateDto) { + return this.repository.create(dto); + } + migrationStatus() { + return this.repository.migrationStatus(); + } + findAll() { + return this.repository.findAll(); + } + findOne(id: string) { + return this.repository.findOne(id); + } + update(id: string, dto: ArticleUpdateDto) { + return this.repository.update(id, dto); + } + remove(id: string) { + return this.repository.archive(id); + } +} diff --git a/apps/backend/src/products/articles/querys/article-get.query.ts b/apps/backend/src/products/articles/querys/article-get.query.ts new file mode 100644 index 0000000..feac766 --- /dev/null +++ b/apps/backend/src/products/articles/querys/article-get.query.ts @@ -0,0 +1,30 @@ +export const articleGetQuery = [ + { + $lookup: { + from: 'categories', + localField: 'categoryId', + foreignField: '_id', + as: 'category', + }, + }, + { $unwind: { path: '$category', preserveNullAndEmptyArrays: true } }, + { + $lookup: { + from: 'manufacturers', + localField: 'manufacturerId', + foreignField: '_id', + as: 'manufacturer', + }, + }, + { $unwind: { path: '$manufacturer', preserveNullAndEmptyArrays: true } }, + { + $lookup: { + from: 'articlegroups', + localField: 'groupId', + foreignField: '_id', + as: 'group', + }, + }, + { $unwind: { path: '$group', preserveNullAndEmptyArrays: true } }, + { $project: { __v: 0 } }, +]; diff --git a/apps/backend/src/products/articles/repository/article.repository.ts b/apps/backend/src/products/articles/repository/article.repository.ts new file mode 100644 index 0000000..bf971bb --- /dev/null +++ b/apps/backend/src/products/articles/repository/article.repository.ts @@ -0,0 +1,203 @@ +import { + BadRequestException, + ConflictException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { InjectConnection, InjectModel } from '@nestjs/mongoose'; +import { Connection, Model, Types } from 'mongoose'; +import { + ArticleCreateDto, + ArticleDto, + ArticleUpdateDto, +} from '../../_dto/article.dto'; +import { Article, TrackingMode } from '../../_entities/article.entity'; +import { articleGetQuery } from '../querys/article-get.query'; + +@Injectable() +export class ArticleRepository { + constructor( + @InjectModel(Article.name) private readonly articleModel: Model
, + @InjectConnection() private readonly connection: Connection, + ) {} + + async migrationStatus() { + const pending = await this.articleModel + .countDocuments({ + articleNumber: { $exists: false }, + legacyGrouping: { $ne: true }, + }) + .exec(); + return { pendingLegacyArticles: pending }; + } + + findAll(): Promise { + return this.articleModel + .aggregate([ + { $match: { archivedAt: null, articleNumber: { $exists: true } } }, + ...articleGetQuery, + { $sort: { name: 1, articleNumber: 1 } }, + ]) + .exec(); + } + + async findOne(id: string): Promise { + this.validateId(id); + const [article] = await this.articleModel + .aggregate([ + { + $match: { + _id: new Types.ObjectId(id), + articleNumber: { $exists: true }, + }, + }, + ...articleGetQuery, + ]) + .exec(); + if (!article) + throw new NotFoundException( + 'Artikel nicht gefunden oder noch nicht migriert', + ); + return article; + } + + async create(dto: ArticleCreateDto) { + await this.validate(dto); + try { + const article = await new this.articleModel(dto).save(); + return this.findOne(article._id.toString()); + } catch (error) { + this.rethrow(error); + } + } + + async update(id: string, dto: ArticleUpdateDto) { + const current = await this.findOne(id); + const merged = { ...current, ...dto }; + await this.validate(merged); + if ( + (dto.baseUnit !== undefined && dto.baseUnit !== current.baseUnit) || + (dto.trackingMode !== undefined && + dto.trackingMode !== current.trackingMode) || + (dto.tracksExpiryDate !== undefined && + dto.tracksExpiryDate !== current.tracksExpiryDate) + ) { + const objectId = new Types.ObjectId(id); + const [stock, movement, asset, batch] = await Promise.all([ + this.connection + .collection('stockcontents') + .findOne({ articleId: objectId }), + this.connection + .collection('stockmovements') + .findOne({ articleId: objectId }), + this.connection.collection('assets').findOne({ articleId: objectId }), + this.connection.collection('batches').findOne({ articleId: objectId }), + ]); + if (stock || movement || asset || batch) { + throw new ConflictException( + 'Einheit und Bestandsregeln können nach einer Buchung nicht geändert werden', + ); + } + } + try { + await this.articleModel + .findByIdAndUpdate(id, dto, { runValidators: true }) + .exec(); + return this.findOne(id); + } catch (error) { + this.rethrow(error); + } + } + + async archive(id: string) { + await this.findOne(id); + await this.articleModel + .findByIdAndUpdate(id, { archivedAt: new Date() }) + .exec(); + return this.findOne(id); + } + + private validateId(id: string) { + if (!Types.ObjectId.isValid(id)) + throw new BadRequestException('Ungültige Artikel-ID'); + } + + private async validate(dto: ArticleCreateDto) { + if ( + !dto.articleNumber?.trim() || + !dto.name?.trim() || + !dto.baseUnit?.trim() + ) { + throw new BadRequestException( + 'Artikelnummer, Name und Basiseinheit sind erforderlich', + ); + } + if ( + !Object.values(TrackingMode).includes(dto.trackingMode) || + typeof dto.isConsumable !== 'boolean' || + typeof dto.tracksExpiryDate !== 'boolean' + ) { + throw new BadRequestException('Bestandsregeln sind ungültig'); + } + if (dto.tracksExpiryDate && dto.trackingMode !== TrackingMode.BATCH) { + throw new BadRequestException('Ablaufdaten erfordern Chargenführung'); + } + if ( + dto.trackingMode === TrackingMode.INDIVIDUAL && + dto.baseUnit !== 'Stück' + ) { + throw new BadRequestException( + 'Einzelstücke müssen die Basiseinheit Stück verwenden', + ); + } + if ( + Object.keys(dto.attributes ?? {}).some( + (key) => + !key.trim() || + key.includes('.') || + key.startsWith('$') || + ['__proto__', 'constructor', 'prototype'].includes(key), + ) + ) { + throw new BadRequestException('Eigenschaftsnamen sind ungültig'); + } + if ( + Object.values(dto.attributes ?? {}).some( + (value) => + !['string', 'number', 'boolean'].includes(typeof value) || + (typeof value === 'number' && !Number.isFinite(value)), + ) + ) { + throw new BadRequestException( + 'Eigenschaften dürfen nur Text, Zahlen oder Wahrheitswerte enthalten', + ); + } + for (const [field, collection] of [ + ['categoryId', 'categories'], + ['manufacturerId', 'manufacturers'], + ['groupId', 'articlegroups'], + ] as const) { + const id = dto[field]; + if ( + id && + !(await this.connection + .collection(collection) + .findOne({ _id: new Types.ObjectId(id) })) + ) { + throw new BadRequestException(`${field}: Referenz nicht gefunden`); + } + } + } + + private rethrow(error: unknown): never { + if ( + error && + typeof error === 'object' && + 'code' in error && + error.code === 11000 + ) { + throw new ConflictException('Artikelnummer ist bereits vergeben'); + } + throw error; + } +} diff --git a/apps/backend/src/catalog/categories/categories.controller.ts b/apps/backend/src/products/categories/categories.controller.ts similarity index 100% rename from apps/backend/src/catalog/categories/categories.controller.ts rename to apps/backend/src/products/categories/categories.controller.ts diff --git a/apps/backend/src/catalog/categories/categories.module.ts b/apps/backend/src/products/categories/categories.module.ts similarity index 100% rename from apps/backend/src/catalog/categories/categories.module.ts rename to apps/backend/src/products/categories/categories.module.ts diff --git a/apps/backend/src/catalog/categories/categories.service.ts b/apps/backend/src/products/categories/categories.service.ts similarity index 100% rename from apps/backend/src/catalog/categories/categories.service.ts rename to apps/backend/src/products/categories/categories.service.ts diff --git a/apps/backend/src/catalog/manufacturer/manufacturer.controller.ts b/apps/backend/src/products/manufacturer/manufacturer.controller.ts similarity index 100% rename from apps/backend/src/catalog/manufacturer/manufacturer.controller.ts rename to apps/backend/src/products/manufacturer/manufacturer.controller.ts diff --git a/apps/backend/src/catalog/manufacturer/manufacturer.module.ts b/apps/backend/src/products/manufacturer/manufacturer.module.ts similarity index 100% rename from apps/backend/src/catalog/manufacturer/manufacturer.module.ts rename to apps/backend/src/products/manufacturer/manufacturer.module.ts diff --git a/apps/backend/src/catalog/manufacturer/manufacturer.service.ts b/apps/backend/src/products/manufacturer/manufacturer.service.ts similarity index 100% rename from apps/backend/src/catalog/manufacturer/manufacturer.service.ts rename to apps/backend/src/products/manufacturer/manufacturer.service.ts diff --git a/apps/backend/src/products/products.module.ts b/apps/backend/src/products/products.module.ts new file mode 100644 index 0000000..2d921a0 --- /dev/null +++ b/apps/backend/src/products/products.module.ts @@ -0,0 +1,16 @@ +import { Module } from '@nestjs/common'; +import { CategoriesModule } from './categories/categories.module'; +import { ArticlesModule } from './articles/articles.module'; +import { ManufacturerModule } from './manufacturer/manufacturer.module'; +import { ArticleGroupsModule } from './article-groups/article-groups.module'; + +@Module({ + imports: [ + ArticlesModule, + CategoriesModule, + ManufacturerModule, + ArticleGroupsModule, + ], + exports: [ArticlesModule], +}) +export class ProductsModule {} diff --git a/apps/backend/src/users/dto/create-user.dto.ts b/apps/backend/src/users/dto/create-user.dto.ts index 4831a2c..b06bb3a 100644 --- a/apps/backend/src/users/dto/create-user.dto.ts +++ b/apps/backend/src/users/dto/create-user.dto.ts @@ -2,10 +2,10 @@ import { IsString, IsEmail, IsOptional, IsInt, Min } from 'class-validator'; export class CreateUserDto { @IsString() - name: string; + name!: string; @IsEmail() - email: string; + email!: string; @IsOptional() @IsInt() diff --git a/apps/backend/src/users/entities/user.entity.ts b/apps/backend/src/users/entities/user.entity.ts index 9fb444b..503844c 100644 --- a/apps/backend/src/users/entities/user.entity.ts +++ b/apps/backend/src/users/entities/user.entity.ts @@ -4,10 +4,10 @@ import { Document } from 'mongoose'; @Schema() export class User extends Document { @Prop({ required: true }) - name: string; + name!: string; @Prop({ required: true, unique: true }) - email: string; + email!: string; } diff --git a/apps/backend/tsconfig.build.json b/apps/backend/tsconfig.build.json index 64f86c6..052134c 100644 --- a/apps/backend/tsconfig.build.json +++ b/apps/backend/tsconfig.build.json @@ -1,4 +1,4 @@ { "extends": "./tsconfig.json", - "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] + "exclude": ["node_modules", "test", "dist", "**/*spec.ts", "scripts"] } diff --git a/apps/backend/tsconfig.json b/apps/backend/tsconfig.json index e2f3514..2f2c59e 100644 --- a/apps/backend/tsconfig.json +++ b/apps/backend/tsconfig.json @@ -13,7 +13,9 @@ "target": "ES2023", "sourceMap": true, "outDir": "./dist", - "baseUrl": "./", + "paths": { + "@/*": ["./src/*"] + }, "incremental": true, "skipLibCheck": true, "strictNullChecks": true, diff --git a/apps/backend/tsconfig.scripts.json b/apps/backend/tsconfig.scripts.json new file mode 100644 index 0000000..30ee609 --- /dev/null +++ b/apps/backend/tsconfig.scripts.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "moduleResolution": "node", + "resolvePackageJsonExports": false, + "noEmit": true, + "incremental": false + }, + "include": ["scripts/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/apps/frontend/actions/article.actions.ts b/apps/frontend/actions/article.actions.ts index dbc948b..9b158c1 100644 --- a/apps/frontend/actions/article.actions.ts +++ b/apps/frontend/actions/article.actions.ts @@ -1,94 +1,97 @@ -'use server' +'use server'; -import { revalidatePath } from 'next/cache' -import { Article, ArticleCreate, ArticleUpsert } from "@/apps/frontend/types/catalog"; +import { revalidatePath } from 'next/cache'; +import { + Article, + ArticleCreate, + ArticleGroup, + ArticleUpsert, +} from '../types/catalog'; import { sites } from '../_config/sites'; +import { endpoints } from '../_config/endpoints'; -export async function articleCreate(data: ArticleCreate) { - console.log(data); - const result = await fetch('http://192.168.50.205/api/articles', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data), - }) - - const resultData = await result.json(); +const api = endpoints.apiServer.url; - if (!result.ok) { +async function mutate( + url: string, + method: string, + data?: unknown, +): Promise { + try { + const response = await fetch(`${api}${url}`, { + method, + headers: { 'Content-Type': 'application/json' }, + body: data === undefined ? undefined : JSON.stringify(data), + }); + const result = await response.json(); + if (!response.ok) { + return { + success: false, + errors: Array.isArray(result.message) + ? result.message + : [result.message ?? 'Speichern fehlgeschlagen'], + }; + } + revalidatePath(sites.article.url); + return { success: true, data: result }; + } catch { return { success: false, - errors: resultData.message, // kommt aus NestJS + errors: [ + 'Der Artikelserver ist nicht erreichbar. Bitte erneut versuchen.', + ], }; } - - - revalidatePath(sites.article.new.url) } - -export async function articleUpdate(id: string, data: ArticleUpsert): Promise { - - const result = await fetch(`http://192.168.50.205/api/articles/${id}`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data), - }) - - const resultData = await result.json(); - - if (!result.ok) { - return { - success: false, - errors: resultData.message, // kommt aus NestJS - }; - } - - revalidatePath(sites.article.update.url + '/' + id); - return { success: true }; - +export async function articleCreate( + data: ArticleCreate, +): Promise { + return mutate('/articles', 'POST', data); +} +export async function articleUpdate( + id: string, + data: ArticleUpsert, +): Promise { + const result = await mutate(`/articles/${id}`, 'PATCH', data); + if (result.success) revalidatePath(`${sites.article.update.url}/${id}`); + return result; } - export async function articleFindAll(): Promise { - - const result = await fetch(`http://192.168.50.205/api/articles`, { - method: 'GET', - headers: { 'Content-Type': 'application/json' } - }) - const data = await result.json() as Article[]; - - return data; + const response = await fetch(`${api}/articles`, { cache: 'no-store' }); + if (!response.ok) throw new Error('Artikel konnten nicht geladen werden'); + return response.json(); +} +export async function articleFindById(id: string): Promise
{ + const response = await fetch(`${api}/articles/${id}`, { cache: 'no-store' }); + if (response.status === 404) return null; + if (!response.ok) throw new Error('Artikel konnte nicht geladen werden'); + return response.json(); +} +export async function articleDelete( + id: string, + revalidateUrl?: string, +): Promise { + const result = await mutate(`/articles/${id}`, 'DELETE'); + if (result.success && revalidateUrl) revalidatePath(revalidateUrl); + return result; +} +export async function articleGroupsFindAll(): Promise { + const response = await fetch(`${api}/article-groups`, { cache: 'no-store' }); + if (!response.ok) + throw new Error('Produktgruppen konnten nicht geladen werden'); + return response.json(); +} +export async function articleGroupCreate(name: string): Promise { + return mutate('/article-groups', 'POST', { name }); } -export async function articleFindById(id: string): Promise { - - const result = await fetch(`http://192.168.50.205/api/articles/${id}`, { - method: 'GET', - headers: { 'Content-Type': 'application/json' } - }) - const data = await result.json() as Article - console.log('getArticle', data) - return data; +export async function articleMigrationStatus(): Promise<{ + pendingLegacyArticles: number; +}> { + const response = await fetch(`${api}/articles/migration-status`, { + cache: 'no-store', + }); + if (!response.ok) + throw new Error('Migrationsstatus konnte nicht geladen werden'); + return response.json(); } - - -export async function articleDelete(id: string,revalidateUrl?:string): Promise { - - - const result = await fetch(`http://192.168.50.205/api/articles/${id}`, { - method: 'DELETE', - headers: { 'Content-Type': 'application/json' } - }) - - const resultData = await result.json(); - - if (!result.ok) { - return { - success: false, - errors: resultData.message, // kommt aus NestJS - }; - } - - if(revalidateUrl) revalidatePath(revalidateUrl); - - return { success: true }; - -} \ No newline at end of file diff --git a/apps/frontend/actions/stock.actions.ts b/apps/frontend/actions/stock.actions.ts index 9ecc1e8..d5dbfb4 100644 --- a/apps/frontend/actions/stock.actions.ts +++ b/apps/frontend/actions/stock.actions.ts @@ -1,94 +1,79 @@ -'use server' +'use server'; -import { revalidatePath } from 'next/cache' +import { revalidatePath } from 'next/cache'; import { sites } from '../_config/sites'; -import { Stock, StockCreate, StockUpdate } from '../types/inventory/stockContent.types'; +import { endpoints } from '../_config/endpoints'; +import { + Stock, + StockCreate, + StockUpdate, +} from '../types/inventory/stock.types'; +import { StockContent } from '../types/inventory/stockContent.types'; +import { + StockMovementIn, + StockMovementOut, + StockMovementTransfer, +} from '../types/inventory/stockMovement.types'; +const api = endpoints.apiServer.url; +async function mutate( + path: string, + method: string, + data?: unknown, +): Promise { + try { + const response = await fetch(`${api}${path}`, { + method, + headers: { 'Content-Type': 'application/json' }, + body: data === undefined ? undefined : JSON.stringify(data), + }); + const result = await response.json(); + if (!response.ok) + return { + success: false, + errors: Array.isArray(result.message) + ? result.message + : [result.message ?? 'Buchung fehlgeschlagen'], + }; + revalidatePath(sites.stock.new.url); + return { success: true, data: result }; + } catch { + return { + success: false, + errors: ['Der Lagerserver ist nicht erreichbar. Bitte erneut versuchen.'], + }; + } +} export async function stockCreate(data: StockCreate) { - - const result = await fetch('http://192.168.50.205/api/stock', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data), - }) - - const resultData = await result.json(); - - if (!result.ok) { - return { - success: false, - errors: resultData.message, // kommt aus NestJS - }; - } - - - revalidatePath(sites.stock.new.url) + return mutate('/stock', 'POST', data); } - -export async function stockUpdate(id: string, data: StockUpdate): Promise { - - const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data), - }) - - const resultData = await result.json(); - - if (!result.ok) { - return { - success: false, - errors: resultData.message, // kommt aus NestJS - }; - } - - revalidatePath(sites.stock.update.url + '/' + id); - return { success: true }; - +export async function stockUpdate(id: string, data: StockUpdate) { + return mutate(`/stock/${id}`, 'PATCH', data); +} +export async function stockDelete(id: string) { + return mutate(`/stock/${id}`, 'DELETE'); } - export async function stockFindAll(): Promise { - - const result = await fetch(`http://192.168.50.205/api/stocks`, { - method: 'GET', - headers: { 'Content-Type': 'application/json' } - }) - const data = await result.json() as Stock[]; - - return data; + const response = await fetch(`${api}/stock`, { cache: 'no-store' }); + if (!response.ok) throw new Error('Lager konnten nicht geladen werden'); + return response.json(); } - -export async function stockFindById(id: string): Promise { - - const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, { - method: 'GET', - headers: { 'Content-Type': 'application/json' } - }) - const data = await result.json() as Stock - console.log('getArticle', data) - return data; +export async function stockFindById(id: string) { + const response = await fetch(`${api}/stock/${id}`, { cache: 'no-store' }); + if (!response.ok) throw new Error('Lager konnte nicht geladen werden'); + return response.json(); +} +export async function stockContentFindAll(): Promise { + const response = await fetch(`${api}/stock-content`, { cache: 'no-store' }); + if (!response.ok) throw new Error('Bestände konnten nicht geladen werden'); + return response.json(); +} +export async function stockMoveIn(data: StockMovementIn) { + return mutate('/stock-movements/in', 'POST', data); +} +export async function stockMoveOut(data: StockMovementOut) { + return mutate('/stock-movements/out', 'POST', data); +} +export async function stockTransfer(data: StockMovementTransfer) { + return mutate('/stock-movements/transfer', 'POST', data); } - - -export async function stockDelete(id: string,revalidateUrl?:string): Promise { - - - const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, { - method: 'DELETE', - headers: { 'Content-Type': 'application/json' } - }) - - const resultData = await result.json(); - - if (!result.ok) { - return { - success: false, - errors: resultData.message, // kommt aus NestJS - }; - } - - if(revalidateUrl) revalidatePath(revalidateUrl); - - return { success: true }; - -} \ No newline at end of file diff --git a/apps/frontend/app/catalog/article/[id]/page.tsx b/apps/frontend/app/catalog/article/[id]/page.tsx index e48dccc..dd7cffc 100644 --- a/apps/frontend/app/catalog/article/[id]/page.tsx +++ b/apps/frontend/app/catalog/article/[id]/page.tsx @@ -1,37 +1,40 @@ -import Link from "next/link"; -import { sites } from "../../../../_config/sites"; -import { articleFindById } from "../../../../actions/article.actions"; -import { ArticleMainForm } from "../../../../components/article/articleMain.form"; -import { categoryFindAll } from "../../../../actions/category.actions"; -import { manufacturerFindAll } from "../../../../actions/manufacturer.actions"; - -interface PageProps { - params: Promise<{ id: string }> - -} -export default async function CatergoryUpdate({ params }: PageProps) { - - - const { id } = await params - const article = await articleFindById(id); - const cats = await categoryFindAll(); - const manufacturer = await manufacturerFindAll(); - - if(!article._id) { - return (
-
Artikel nicht gefunden
-
- zurück1 -
-
) - } - const {name,category,variants} = article; - console.log('Varianten:',article.variants) +import Link from 'next/link'; +import { sites } from '../../../../_config/sites'; +import { + articleFindById, + articleGroupsFindAll, +} from '../../../../actions/article.actions'; +import { ArticleMainForm } from '../../../../components/article/articleMain.form'; +import { categoryFindAll } from '../../../../actions/category.actions'; +import { manufacturerFindAll } from '../../../../actions/manufacturer.actions'; +export default async function ArticleUpdatePage({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + const [article, categories, manufacturer, groups] = await Promise.all([ + articleFindById(id), + categoryFindAll(), + manufacturerFindAll(), + articleGroupsFindAll(), + ]); return ( -
- - zurück +
+ {article ? ( + + ) : ( +

Artikel nicht gefunden.

+ )} + + Zurück zu den Artikeln +
); } diff --git a/apps/frontend/app/catalog/article/new/page.tsx b/apps/frontend/app/catalog/article/new/page.tsx index 1b35973..874cbe9 100644 --- a/apps/frontend/app/catalog/article/new/page.tsx +++ b/apps/frontend/app/catalog/article/new/page.tsx @@ -1,27 +1,26 @@ -import { manufacturerFindAll } from "../../../../actions/manufacturer.actions"; -import { categoryFindAll } from "../../../../actions/category.actions"; -import { ArticleMainForm } from "../../../../components/article/articleMain.form"; -import { articleCreate, articleFindAll } from "../../../../actions/article.actions"; -import Link from "next/link"; -import { sites } from "../../../../../../apps/frontend/_config/sites"; -//import { sites } from "@/"; +import { manufacturerFindAll } from '../../../../actions/manufacturer.actions'; +import { categoryFindAll } from '../../../../actions/category.actions'; +import { articleGroupsFindAll } from '../../../../actions/article.actions'; +import { ArticleMainForm } from '../../../../components/article/articleMain.form'; +import Link from 'next/link'; +import { sites } from '../../../../_config/sites'; - -interface Props { - -} - -export default async function ArticlePage({ }: Props) { - - const cats = await categoryFindAll(); - const manufacturer = await manufacturerFindAll(); - const artikel = await articleFindAll(); - - if(!manufacturer) return
Keine Hersteller gefunden
- - return <> - - zurück - +export default async function ArticleNewPage() { + const [categories, manufacturer, groups] = await Promise.all([ + categoryFindAll(), + manufacturerFindAll(), + articleGroupsFindAll(), + ]); + return ( + <> + + + Zurück zu den Artikeln + -} \ No newline at end of file + ); +} diff --git a/apps/frontend/app/catalog/article/page.tsx b/apps/frontend/app/catalog/article/page.tsx index ecbf118..f8ac1f1 100644 --- a/apps/frontend/app/catalog/article/page.tsx +++ b/apps/frontend/app/catalog/article/page.tsx @@ -1,26 +1,33 @@ -import { manufacturerFindAll } from "../../../actions/manufacturer.actions"; -import { articleFindAll } from "../../../actions/article.actions"; -import Link from "next/link"; -import { sites } from "../../../../../apps/frontend/_config/sites"; -import { ArticleList } from "../../../components/article/articleList"; -import { Icon, CirclePlus } from "lucide-react"; +import { + articleFindAll, + articleMigrationStatus, +} from '../../../actions/article.actions'; +import Link from 'next/link'; +import { sites } from '../../../_config/sites'; +import { ArticleList } from '../../../components/article/articleList'; -interface Props { } - -export default async function ArticlePage({ }: Props) { - - - const manufacturer = await manufacturerFindAll(); - const artikel = await articleFindAll(); - - if (!manufacturer) return
Keine Hersteller gefunden
- - return
-
- neu -
- - zurück -
- -} \ No newline at end of file +export default async function ArticlePage() { + const [articles, migration] = await Promise.all([ + articleFindAll(), + articleMigrationStatus(), + ]); + return ( +
+

Artikel

+ + Artikel anlegen + + {migration.pendingLegacyArticles > 0 && ( +

+ Es gibt noch {migration.pendingLegacyArticles} bisherige Artikel, die + vor ihrer Nutzung in die neue Artikelstruktur übernommen werden + müssen. +

+ )} + + + Zurück + +
+ ); +} diff --git a/apps/frontend/app/stock/movement/new/page.tsx b/apps/frontend/app/stock/movement/new/page.tsx index 30316de..269a2fc 100644 --- a/apps/frontend/app/stock/movement/new/page.tsx +++ b/apps/frontend/app/stock/movement/new/page.tsx @@ -1,27 +1,31 @@ -import Link from "next/link"; -import { sites } from "../../../../_config/sites"; -import { LocationForm } from "../../../../components/location/location.form"; -import { articleFindAll } from "../../../../actions/article.actions"; -import { locationFindAll, locationTree } from "../../../../actions/location.actions"; -import { StockForm } from "../../../../components/stock/stock.form"; -import { categoryFindAll } from "../../../../actions/category.actions"; +import Link from 'next/link'; +import { sites } from '../../../../_config/sites'; +import { articleFindAll } from '../../../../actions/article.actions'; +import { locationTree } from '../../../../actions/location.actions'; +import { + stockContentFindAll, + stockFindAll, +} from '../../../../actions/stock.actions'; +import { StockForm } from '../../../../components/stock/stock.form'; - - -export default async function StockMovmentNewPage() { - - const artikel = await articleFindAll(); - const orte = await locationTree(); - const kategorien = await categoryFindAll(); - - return ( -
-
- {sites.location.new.name} - -
- - zurück zu {sites.location.name} -
- ); +export default async function StockMovementPage() { + const [article, orte, stocks, contents] = await Promise.all([ + articleFindAll(), + locationTree(), + stockFindAll(), + stockContentFindAll(), + ]); + return ( +
+ + + Zurück + +
+ ); } diff --git a/apps/frontend/components/article/articleBase.form.tsx b/apps/frontend/components/article/articleBase.form.tsx index 3448d88..ff763bf 100644 --- a/apps/frontend/components/article/articleBase.form.tsx +++ b/apps/frontend/components/article/articleBase.form.tsx @@ -1,26 +1,131 @@ -"use client"; +'use client'; -import { ArticleCreate, ArticleUpsert, Category } from "../../types/catalog" -import { useFormContext } from "react-hook-form" -import { InputTextR } from "../ui/inputTextR"; -import ComboBoxR from "../ui/ComboBoxR"; +import { + ArticleCreate, + ArticleGroup, + Category, + Manufacturer, +} from '../../types/catalog'; +import { useFormContext } from 'react-hook-form'; +import { InputTextR } from '../ui/inputTextR'; - -interface Params { - categories: Category[] +interface Props { + categories: Category[]; + manufacturer: Manufacturer[]; + groups: ArticleGroup[]; } - -export const ArticleBaseForm = ({ categories }: Params) => { - - const { register, control } = useFormContext(); - - const values = categories.map((i) => ({ id: i._id, value: i.name })) - return ( - <> - - - - - - ) -} \ No newline at end of file +export const ArticleBaseForm = ({ + categories, + manufacturer, + groups, +}: Props) => { + const { + register, + watch, + setValue, + formState: { errors }, + } = useFormContext(); + const trackingMode = watch('trackingMode'); + return ( +
+ + + + + + + + + + + + +

+ {Object.values(errors) + .map((error) => error?.message) + .filter(Boolean) + .join(' · ')} +

+
+ ); +}; diff --git a/apps/frontend/components/article/articleList.tsx b/apps/frontend/components/article/articleList.tsx index 6dc41b0..9d48e2e 100644 --- a/apps/frontend/components/article/articleList.tsx +++ b/apps/frontend/components/article/articleList.tsx @@ -1,57 +1,86 @@ -"use client"; +'use client'; -import { useRouter } from 'next/navigation' -import { Article } from "../../types/catalog" - -import { articleDelete } from "../../actions/article.actions"; -import { sites } from "../../_config/sites"; -import Link from "next/link"; -import { Eye, OctagonX } from 'lucide-react'; - - -interface Params { - articles: Article[] -} - -export const ArticleList = ({ articles }: Params) => { - - - const router = useRouter() - - const handlerOnDelete = (id: string) => { - articleDelete(id) - router.refresh(); - } - - return ( -
- {articles.map((a) => ( -
-
-
- {a.name} -
-
- - - - - -
-
- -
-
-
))} - -
- ) - - - - -} +import { useRouter } from 'next/navigation'; +import { useState } from 'react'; +import { Article } from '../../types/catalog'; +import { articleDelete } from '../../actions/article.actions'; +import { sites } from '../../_config/sites'; +import Link from 'next/link'; +export const ArticleList = ({ articles }: { articles: Article[] }) => { + const router = useRouter(); + const [error, setError] = useState(''); + const [pendingId, setPendingId] = useState(null); + const archive = async (id: string) => { + setPendingId(id); + setError(''); + const result = await articleDelete(id); + if (!result.success) setError(result.errors.join(' · ')); + else router.refresh(); + setPendingId(null); + }; + return ( +
+ {error && ( +

+ {error} +

+ )} + + + + + + + + + + + + + {articles.map((article) => ( + + + + + + + + + ))} + +
NummerArtikelHerstellerEinheitBestandsführungAktionen
{article.articleNumber} + {article.name} + {article.group && ( + + {article.group.name} + + )} + {article.manufacturer?.name ?? '–'}{article.baseUnit} + { + { + quantity: 'Menge', + batch: 'Charge', + individual: 'Einzelstücke', + }[article.trackingMode] + } + + + Bearbeiten + + +
+ {articles.length === 0 && ( +

Noch keine Artikel vorhanden.

+ )} +
+ ); +}; diff --git a/apps/frontend/components/article/articleMain.form.tsx b/apps/frontend/components/article/articleMain.form.tsx index ab07d01..7127569 100644 --- a/apps/frontend/components/article/articleMain.form.tsx +++ b/apps/frontend/components/article/articleMain.form.tsx @@ -1,106 +1,329 @@ -"use client"; +'use client'; -import { emptyArticleDto, Article, ArticleCreate, Category, Manufacturer, ArticleUpsert } from "../../types/catalog" -import { FormProvider, useForm } from "react-hook-form" -import { ArticleBaseForm } from "./articleBase.form"; -import { ArticleVariantForm } from "./articleVariants.form"; -import { articleCreate, articleUpdate } from "../../actions/article.actions"; -import { useEffect, useState } from "react"; -import Modal from "../ui/modal"; -import { ManufactuererForm } from "../manufacturer/manufacturer.form"; +import { + Article, + ArticleAttributes, + ArticleCreate, + ArticleGroup, + Category, + Manufacturer, + emptyArticleDto, +} from '../../types/catalog'; +import { FormProvider, useForm } from 'react-hook-form'; +import { ArticleBaseForm } from './articleBase.form'; +import { ArticlePackagingForm } from './articleVariants.form'; +import { + articleCreate, + articleGroupCreate, + articleUpdate, +} from '../../actions/article.actions'; +import { useEffect, useState } from 'react'; +import { useRouter } from 'next/navigation'; +import Modal from '../ui/modal'; +import { ManufactuererForm } from '../manufacturer/manufacturer.form'; +import { InputTextR } from '../ui/inputTextR'; +import { sites } from '../../_config/sites'; - -interface Params { - categories: Category[] - manufacturer: Manufacturer[] - initData?: ArticleUpsert - debug?: boolean +interface Props { + categories: Category[]; + manufacturer: Manufacturer[]; + groups: ArticleGroup[]; + initData?: Article; } +function formValues(article?: Article): ArticleCreate { + if (!article) return emptyArticleDto; + return { + articleNumber: article.articleNumber, + name: article.name, + description: article.description ?? '', + categoryId: article.categoryId ?? '', + manufacturerId: article.manufacturerId ?? '', + groupId: article.groupId ?? '', + manufacturerArticleNumber: article.manufacturerArticleNumber ?? '', + barcode: article.barcode ?? '', + baseUnit: article.baseUnit, + isConsumable: article.isConsumable, + trackingMode: article.trackingMode, + tracksExpiryDate: article.tracksExpiryDate, + packaging: article.packaging ?? [], + attributes: article.attributes ?? {}, + }; +} +export const ArticleMainForm = ({ + categories, + manufacturer, + groups, + initData, +}: Props) => { + const methods = useForm({ + defaultValues: formValues(initData), + }); + const router = useRouter(); + const [errors, setErrors] = useState([]); + const [manufacturers, setManufacturers] = useState(manufacturer); + const [productGroups, setProductGroups] = useState(groups); + const [manufacturerOpen, setManufacturerOpen] = useState(false); + const [groupOpen, setGroupOpen] = useState(false); + const [groupName, setGroupName] = useState(''); + const [groupSaving, setGroupSaving] = useState(false); + const [properties, setProperties] = useState< + { key: string; value: string; type: 'string' | 'number' | 'boolean' }[] + >([]); + useEffect(() => { + methods.reset(formValues(initData)); + setProperties( + Object.entries(initData?.attributes ?? {}).map(([key, value]) => ({ + key, + value: String(value), + type: typeof value as 'string' | 'number' | 'boolean', + })), + ); + }, [initData, methods]); -export const ArticleMainForm = ({ categories, manufacturer, initData, debug }: Params) => { - - const methods = useForm({ defaultValues: emptyArticleDto }); - const [errMsg, setErrorMsg] = useState([]) - const [error, setError] = useState(false) - const [creatManufacturer, setCreatManufacturer] = useState(-1); - const [hersteller,setHersteller] = useState([]) - - useEffect(() => { - setHersteller(manufacturer); - if (initData && initData._id) { - - methods.reset(initData); + const onSubmit = async (data: ArticleCreate) => { + setErrors([]); + const attributes: ArticleAttributes = {}; + for (const property of properties) { + const key = property.key.trim(); + if ( + !key || + Object.hasOwn(attributes, key) || + ['__proto__', 'constructor', 'prototype'].includes(key) || + key.includes('.') || + key.startsWith('$') + ) { + setErrors(['Eigenschaften benötigen unterschiedliche, gültige Namen.']); + return; + } + if (property.type === 'number') { + if ( + !property.value.trim() || + !Number.isFinite(Number(property.value)) + ) { + setErrors([`${key}: Bitte eine gültige Zahl eingeben.`]); + return; } - }, [initData]) - - const handlerCreatManufacturer = (data: Manufacturer) => { - console.log('Create') - setHersteller((cur)=>([...cur,data])); - - - methods.setValue( - `variants.${creatManufacturer}.manufacturerId`, - data._id, - { shouldDirty: true, shouldValidate: true } - ); - setCreatManufacturer(-1) + attributes[key] = Number(property.value); + } else + attributes[key] = + property.type === 'boolean' + ? property.value === 'true' + : property.value; } - - const onSubmit = async (data: ArticleUpsert) => { - if (initData?._id) { - - const result = await articleUpdate(initData._id, data) - if (!result.success) { - setError(true) - setErrorMsg(() => result.errors) - console.log(result) - } else { - setError(false) - - } - } else { - console.log('create') - - const { name, categoryId, variants, attributes } = data; - if (categoryId) { - const create = { - name, - categoryId, - variants, - attributes - } - articleCreate(create); - } - } - + const payload = { + ...data, + categoryId: data.categoryId || null, + manufacturerId: data.manufacturerId || null, + groupId: data.groupId || null, + attributes, }; + const result = initData + ? await articleUpdate(initData._id, payload) + : await articleCreate(payload); + if (!result.success) setErrors(result.errors); + else { + router.push(sites.article.url); + router.refresh(); + } + }; - return ( -
- - {initData?._id &&
{initData._id}
} -
- - setCreatManufacturer(index)}> + const addGroup = async () => { + if (!groupName.trim()) return; + setGroupSaving(true); + try { + const result = await articleGroupCreate(groupName.trim()); + if (!result.success) { + setErrors(result.errors); + return; + } + const group = result.data as ArticleGroup; + setProductGroups((current) => [...current, group]); + methods.setValue('groupId', group._id); + setGroupOpen(false); + setGroupName(''); + } finally { + setGroupSaving(false); + } + }; -
{methods.watch("name")}
-
{JSON.stringify(methods.watch(), null, 2)}
- -
- -
- = 0} onClose={() => setCreatManufacturer(-1)}> - handlerCreatManufacturer(d)}> - - - {error &&
- Error - {errMsg.map((msg, id) => (
{msg}
))} -
} - -
- - - ) -} \ No newline at end of file + return ( +
+

+ {initData ? 'Artikel bearbeiten' : 'Artikel anlegen'} +

+ +
+ +
+ + +
+
+ Eigenschaften (optional) + {properties.map((property, index) => ( +
+ + setProperties((current) => + current.map((item, i) => + i === index + ? { ...item, key: event.target.value } + : item, + ), + ) + } + /> + + {property.type === 'boolean' ? ( + + ) : ( + + setProperties((current) => + current.map((item, i) => + i === index + ? { ...item, value: event.target.value } + : item, + ), + ) + } + /> + )} + +
+ ))} + +
+ + + +
+ {errors.length > 0 && ( +
    + {errors.map((error, index) => ( +
  • {error}
  • + ))} +
+ )} + setManufacturerOpen(false)}> + { + setManufacturers((current) => [...current, item]); + methods.setValue('manufacturerId', item._id); + setManufacturerOpen(false); + }} + /> + + setGroupOpen(false)}> + setGroupName(event.target.value)} + /> + + +
+ ); +}; diff --git a/apps/frontend/components/article/articleVariants.form.tsx b/apps/frontend/components/article/articleVariants.form.tsx index 24edb1e..1e8bf6c 100644 --- a/apps/frontend/components/article/articleVariants.form.tsx +++ b/apps/frontend/components/article/articleVariants.form.tsx @@ -1,85 +1,65 @@ -"use client"; +'use client'; -import { ArticleCreate, ArticleUpsert, Manufacturer } from "../../types/catalog" -import { useFieldArray, useFormContext } from "react-hook-form" -import { InputTextR } from "../ui/inputTextR"; -import ComboBoxRHF from "../ui/ComboBoxR"; -import { useState } from "react"; -import Modal from "../ui/modal"; -import { ManufactuererForm } from "../manufacturer/manufacturer.form"; -import SelectAndSearch2 from "../ui/SelectAndSearch2"; - - -interface Params { - manufacturer: Manufacturer[] - onOpenManufacturer: (index: number) => void -} - -export const ArticleVariantForm = ({ manufacturer, onOpenManufacturer }: Params) => { - - const { control, register, getValues, setValue } = useFormContext(); - const { fields, append, remove } = useFieldArray({ control, name: "variants", }); - const [creatManufacturer, setCreatManufacturer] = useState(false); - - const handleRemove = (index: number) => { - - const id = getValues(`variants.${index}._id`); - if (!id) { - remove(index); - return; - } - const x = getValues(`variants.${index}.deleted`) ? true : false; - - setValue(`variants.${index}.deleted`, !x, { shouldDirty: true }) - } - - const hersteller = manufacturer.map((i) => ({ id: i._id, value: i.name })) - - return ( -
- -
- -
- - - -
-
-
- Hersteller -
-
- Packungseinheit -
-
- Aktion -
-
-
- {fields.map((field, index) => ( -
-
- - - -
-
- -
-
- -
-
- ))} -
+import { ArticleCreate } from '../../types/catalog'; +import { useFieldArray, useFormContext } from 'react-hook-form'; +import { InputTextR } from '../ui/inputTextR'; +export const ArticlePackagingForm = () => { + const { + control, + register, + watch, + formState: { errors }, + } = useFormContext(); + const { fields, append, remove } = useFieldArray({ + control, + name: 'packaging', + }); + return ( +
+ Verpackungen (optional) +

+ Der Bestand wird in {watch('baseUnit') || 'der Basiseinheit'} geführt. + Hier hinterlegst du den Inhalt einer Verpackung. +

+ {fields.map((field, index) => ( +
+ + + +
- - - ) -} \ No newline at end of file + ))} + {errors.packaging && ( +

+ Jede Verpackung benötigt eine Bezeichnung und einen positiven Inhalt. +

+ )} + +
+ ); +}; diff --git a/apps/frontend/components/stock/stock.form.tsx b/apps/frontend/components/stock/stock.form.tsx index 61d6053..9061c54 100644 --- a/apps/frontend/components/stock/stock.form.tsx +++ b/apps/frontend/components/stock/stock.form.tsx @@ -1,109 +1,437 @@ -"use client"; +'use client'; -import { emptyArticleDto, Article, ArticleCreate, Category, Manufacturer, ArticleVariant } from "../../types/catalog" -import { FormProvider, useForm } from "react-hook-form" -import { articleCreate, articleUpdate } from "../../actions/article.actions"; -import { useEffect, useState } from "react"; -import Modal from "../ui/modal"; -import { ManufactuererForm } from "../manufacturer/manufacturer.form"; -import { Location, LocationTreeNode } from "../../types/inventory"; -import { emptyStock, Stock, StockCreate } from "../../types/inventory/stockContent.types"; -import { stockCreate, stockUpdate } from "../../actions/stock.actions"; -import { InputTextR } from "../ui/inputTextR"; -import { LocationView } from "../location/location.view"; -import { LocationTreeView } from "../location/location.treeView"; +import { Article } from '../../types/catalog'; +import { useForm } from 'react-hook-form'; +import { useRouter } from 'next/navigation'; +import { useState } from 'react'; +import { Stock } from '../../types/inventory/stock.types'; +import { StockContent } from '../../types/inventory/stockContent.types'; +import { StockMovementIn } from '../../types/inventory/stockMovement.types'; +import { LocationTreeNode } from '../../types/inventory'; +import { + stockCreate, + stockMoveIn, + stockMoveOut, + stockTransfer, +} from '../../actions/stock.actions'; +import { InputTextR } from '../ui/inputTextR'; +import { LocationTreeView } from '../location/location.treeView'; +import Modal from '../ui/modal'; - -interface Params { - categories: Category[] - article: Article[], - orte: LocationTreeNode[] - initData?: Stock - debug?: boolean +interface Props { + article: Article[]; + stocks: Stock[]; + contents: StockContent[]; + orte: LocationTreeNode[]; } +export const StockForm = ({ article, stocks, contents, orte }: Props) => { + const router = useRouter(); + const { + register, + watch, + reset, + setValue, + handleSubmit, + formState: { isSubmitting, errors: formErrors }, + } = useForm({ + shouldUnregister: true, + defaultValues: { articleId: '', stockId: '', quantity: 1 }, + }); + const selectedArticle = article.find( + (item) => item._id === watch('articleId'), + ); + const [errors, setErrors] = useState([]); + const [notice, setNotice] = useState(''); + const [stockOpen, setStockOpen] = useState(false); + const [stockName, setStockName] = useState(''); + const [location, setLocation] = useState(null); + const [busy, setBusy] = useState(false); + const [selectedContent, setSelectedContent] = useState( + null, + ); + const [operation, setOperation] = useState<'out' | 'transfer'>('out'); + const [quantity, setQuantity] = useState(1); + const [targetStock, setTargetStock] = useState(''); + const [targetArea, setTargetArea] = useState(''); - -export const StockForm = ({ article, categories, initData, orte, debug }: Params) => { - - const { register, reset, formState: { errors }, handleSubmit } = useForm({ defaultValues: emptyStock }); - const [errMsg, setErrorMsg] = useState([]) - const [selectetCategory, setSelectedCategory] = useState() - const [selectetArticle, setSelectedArticle] = useState
() - const [selectetArticleVariant, setSelectedArticleVariant] = useState() - const [selectetOrt, setSelectedOrt] = useState() - - const [error, setError] = useState(false) - - useEffect(() => { - - if (initData && initData.id) { - - reset(initData); - } - }, [initData]) - - - - - const onSubmit = async (data: StockCreate) => { - if (initData?.id) { - - const result = await stockUpdate(initData.id, data) - if (!result.success) { - setError(true) - setErrorMsg(() => result.errors) - console.log(result) - } else { - setError(false) - - } - } else { - console.log('create') - - const { articleVariantId, locationId, quantity, expiryDate, batchNumber } = data; - if (true) { - const create = { - articleVariantId, - locationId, - quantity, - expiryDate, - batchNumber - } - stockCreate(create); - } - } - - }; - - const handleLocationSelect = (ort: LocationTreeNode) => { - setSelectedOrt(ort); + const feedback = (result: ActionResult) => { + if (!result.success) { + setErrors(result.errors); + return false; } + setErrors([]); + setNotice('Gespeichert.'); + router.refresh(); + return true; + }; + const onSubmit = async (data: StockMovementIn) => { + setNotice(''); + const payload: StockMovementIn = { + articleId: data.articleId, + stockId: data.stockId, + quantity: data.quantity, + area: data.area || undefined, + }; + if (selectedArticle?.trackingMode === 'batch') { + payload.batchNumber = data.batchNumber; + if (selectedArticle.tracksExpiryDate && data.expiryDate) + payload.expiryDate = data.expiryDate; + } + if (selectedArticle?.trackingMode === 'individual') { + payload.inventoryNumber = data.inventoryNumber; + payload.serialNumber = data.serialNumber || undefined; + payload.condition = data.condition || undefined; + payload.purpose = data.purpose || undefined; + payload.acquiredAt = data.acquiredAt || undefined; + } + if (feedback(await stockMoveIn(payload))) + reset({ + articleId: data.articleId, + stockId: data.stockId, + quantity: 1, + batchNumber: '', + inventoryNumber: '', + serialNumber: '', + expiryDate: '', + }); + }; + const addStock = async () => { + if (!location || !stockName.trim()) return; + setBusy(true); + try { + if ( + feedback( + await stockCreate({ + name: stockName.trim(), + locationId: location._id, + }), + ) + ) { + setStockOpen(false); + setStockName(''); + setLocation(null); + } + } finally { + setBusy(false); + } + }; + const book = async () => { + if (!selectedContent) return; + setBusy(true); + setNotice(''); + try { + const data = { stockContentId: selectedContent._id, quantity }; + const result = + operation === 'out' + ? await stockMoveOut(data) + : await stockTransfer({ + ...data, + toStockId: targetStock, + toArea: targetArea || undefined, + }); + if (feedback(result)) setSelectedContent(null); + } finally { + setBusy(false); + } + }; - - return ( -
- - {initData?.id &&
{initData.id}
} -
- - - - - - handleLocationSelect(item)}> - - {error &&
- Error - {errMsg.map((msg, id) => (
{msg}
))} -
} - {selectetOrt &&
{selectetOrt.name}
} - -
- - - ) -} \ No newline at end of file + return ( +
+

Lager und Bestände

+ +
+ + + + selectedArticle?.trackingMode !== 'individual' || + value === 1 || + 'Einzelstücke benötigen Menge 1', + })} + /> + + {selectedArticle?.trackingMode === 'batch' && ( + <> + + selectedArticle?.trackingMode !== 'batch' || + Boolean(value?.trim()) || + 'Chargennummer erforderlich', + })} + /> + {selectedArticle.tracksExpiryDate && ( + + )} + + )} + {selectedArticle?.trackingMode === 'individual' && ( + <> + + selectedArticle?.trackingMode !== 'individual' || + Boolean(value?.trim()) || + 'Inventarnummer erforderlich', + })} + /> + + + + + + )} +

+ {Object.values(formErrors) + .map((error) => error.message) + .filter(Boolean) + .join(' · ')} +

+ + + {errors.length > 0 && ( +
    + {errors.map((error, index) => ( +
  • {error}
  • + ))} +
+ )} + {notice && ( +

+ {notice} +

+ )} +

Bestände

+
+ + + + + + + + + + + + {contents.map((content) => ( + + + + + + + + ))} + +
ArtikelLagerMengeCharge / ExemplarAktionen
+ {content.articleId?.name ?? 'Artikel fehlt'} + + {content.stockId?.name ?? 'Lager fehlt'} {content.area} + + {content.quantity} {content.articleId?.baseUnit} + + {content.batchId?.batchNumber ?? + content.assetId?.inventoryNumber ?? + '–'} + {content.batchId?.expiryDate && ( + + {new Date(content.batchId.expiryDate).toLocaleDateString( + 'de-DE', + { timeZone: 'UTC' }, + )} + + )} + + {(['out', 'transfer'] as const).map((action) => ( + + ))} +
+
+ {contents.length === 0 &&

Keine Bestände vorhanden.

} + setStockOpen(false)}> + setStockName(event.target.value)} + /> +

Lagerort auswählen: {location?.name}

+ + +
+ setSelectedContent(null)} + > +

+ {operation === 'out' ? 'Entnehmen' : 'Umlagern'}:{' '} + {selectedContent?.articleId?.name} +

+ setQuantity(Number(event.target.value))} + /> + {operation === 'transfer' && ( + <> + + + + )} + +
+
+ ); +}; diff --git a/apps/frontend/types/catalog/article.types.ts b/apps/frontend/types/catalog/article.types.ts index 1d4bd08..ca71145 100644 --- a/apps/frontend/types/catalog/article.types.ts +++ b/apps/frontend/types/catalog/article.types.ts @@ -1,93 +1,56 @@ -import { Category } from "./category.types"; -import {Manufacturer,emptyManufacturer} from "./manufacturer.types" +import { Category } from './category.types'; +import { Manufacturer } from './manufacturer.types'; -export interface Article { - _id: string, - name: string, - category: Category; - attributes?: Record; - variants: Variant[], +export type TrackingMode = 'quantity' | 'batch' | 'individual'; +export type ArticleAttributes = Record; +export interface ArticleGroup { + _id: string; + name: string; + description?: string; +} +export interface ArticlePackaging { + name: string; + quantityInBaseUnits: number; + barcode?: string; } export interface ArticleCreate { - name: string; - categoryId: string; - attributes?: Record; - variants: Variant[], + articleNumber: string; + name: string; + description?: string; + categoryId?: string | null; + groupId?: string | null; + manufacturerId?: string | null; + manufacturerArticleNumber?: string; + barcode?: string; + baseUnit: string; + isConsumable: boolean; + trackingMode: TrackingMode; + tracksExpiryDate: boolean; + attributes?: ArticleAttributes; + packaging?: ArticlePackaging[]; } - - -//--- Artikel Variante -export interface ArticleVariant { - _id: string; - article: Article; - manufacturer: Manufacturer; - supplierArticleNumber?: string; - packagingUnit?: string; - extra?: Record; +export type ArticleUpsert = ArticleCreate; +export interface Article extends ArticleCreate { + _id: string; + category?: Category; + manufacturer?: Manufacturer; + group?: ArticleGroup; + archivedAt?: string | null; } - -export interface ArticleVariantCreate { - articleId: string; - manufacturerId: string; - supplierArticleNumber?: string; - packagingUnit?: string; - extra?: Record; -} - - - -export interface Variant { - _id?: string; - manufacturerId: string; - supplierArticleNumber?: string; - packagingUnit?: string; - extra?: Record; -} - -export interface VariantCreate { - manufacturerId: string; - supplierArticleNumber?: string; - packagingUnit?: string; - extra?: Record; -} - - - - -export const emptyArticle = { - name: '', -} - - - -export const emptyArticleVariant = { - article: emptyArticle, - manufacturer: emptyManufacturer -} - - -export const emptyArticleDto:ArticleCreate = { - name:'', - categoryId:'', - variants:[] -} - - -//Upsert -export interface ArticleUpsert { - _id:string, - name: string; - categoryId?: string; - attributes?: Record; - variants: VariantUpsert[], -} - -export interface VariantUpsert { - _id?:string - manufacturerId: string; - supplierArticleNumber?: string; - packagingUnit?: string; - extra?: Record; - deleted?:boolean; -} \ No newline at end of file +export const emptyArticleDto: ArticleCreate = { + articleNumber: '', + name: '', + description: '', + categoryId: null, + groupId: null, + manufacturerId: null, + manufacturerArticleNumber: '', + barcode: '', + baseUnit: 'Stück', + isConsumable: false, + trackingMode: 'quantity', + tracksExpiryDate: false, + attributes: {}, + packaging: [], +}; diff --git a/apps/frontend/types/inventory/stock.types.ts b/apps/frontend/types/inventory/stock.types.ts index 9cbf24d..496ae21 100644 --- a/apps/frontend/types/inventory/stock.types.ts +++ b/apps/frontend/types/inventory/stock.types.ts @@ -1,20 +1,16 @@ -import { Location } from "./location.types"; - export interface StockCreate { - name: string; - locationId: string; - areas?:string[] + name: string; + locationId: string; + areas?: string[]; } - export interface StockUpdate { - name?: string; - locationId?: string; - areas?:string[] + name?: string; + locationId?: string; + areas?: string[]; } - export interface Stock { - id: string - name: string; - location: Location; - areas?:string[] -} \ No newline at end of file + _id: string; + name: string; + locationId: string; + areas?: string[]; +} diff --git a/apps/frontend/types/inventory/stockContent.types.ts b/apps/frontend/types/inventory/stockContent.types.ts index c23fa9a..b5cc48c 100644 --- a/apps/frontend/types/inventory/stockContent.types.ts +++ b/apps/frontend/types/inventory/stockContent.types.ts @@ -1,36 +1,25 @@ +import { Article } from '../catalog'; +import { Stock } from './stock.types'; - -export interface Stock { - id: string - articleVariantId: string - locationId: string - quantity: number - expiryDate?: Date - batchNumber: string +export interface Batch { + _id: string; + batchNumber: string; + expiryDate?: string; } - - -export interface StockCreate { - articleVariantId: string - locationId: string - quantity: number - expiryDate?: Date - batchNumber: string +export interface Asset { + _id: string; + inventoryNumber: string; + serialNumber?: string; + condition?: string; + purpose?: string; + acquiredAt?: string; } - -export interface StockUpdate { - articleVariantId?: string - locationId?: string - quantity?: number - expiryDate?: Date - batchNumber?: string +export interface StockContent { + _id: string; + articleId: Article; + stockId: Stock; + quantity: number; + area: string; + batchId?: Batch | null; + assetId?: Asset | null; } - - -export const emptyStock:StockCreate = { - articleVariantId: '', - locationId: '', - quantity: 0, - expiryDate: new Date(), - batchNumber: '1' -} \ No newline at end of file diff --git a/apps/frontend/types/inventory/stockMovement.types.ts b/apps/frontend/types/inventory/stockMovement.types.ts index 63d186e..2710e90 100644 --- a/apps/frontend/types/inventory/stockMovement.types.ts +++ b/apps/frontend/types/inventory/stockMovement.types.ts @@ -1,28 +1,21 @@ - - - export interface StockMovementIn { stockId: string; - articleVariantId: string; + articleId: string; quantity: number; batchNumber?: string; - expiryDate?: Date; + expiryDate?: string; area?: string; + inventoryNumber?: string; + serialNumber?: string; + condition?: string; + purpose?: string; + acquiredAt?: string; } - export interface StockMovementOut { stockContentId: string; quantity: number; } - -export interface StockMovementTransfer { - articleVariantId: string; - fromStockId: string; +export interface StockMovementTransfer extends StockMovementOut { toStockId: string; toArea?: string; - quantity: number; - batchNumber?: string; } - - - diff --git a/docs/artikelmodell.md b/docs/artikelmodell.md new file mode 100644 index 0000000..66474ca --- /dev/null +++ b/docs/artikelmodell.md @@ -0,0 +1,134 @@ +# Gemeinsames Artikelmodell + +Der Backend-Bereich `src/products/` bündelt Artikel, Produktgruppen, Kategorien +und Hersteller im `ProductsModule`. Die bestehenden API- und Frontend-URLs +bleiben unverändert. + +Ein Artikel ist ein konkretes Produkt, unabhängig davon, ob es verbraucht wird. +Lager und Bewegungen referenzieren direkt `articleId`. Eine Produktgruppe ist +optional: Raspberry Pi 5 mit 4 GB und mit 8 GB sind zwei Artikel derselben Gruppe. +Die bisherigen Variantenmodule bleiben als Referenz für alte Daten im Repository, +sind aber nicht mehr im laufenden Backend registriert. + +## Artikel + +`articleNumber`, `name`, `baseUnit`, `isConsumable`, `trackingMode` und +`tracksExpiryDate` sind beim Anlegen erforderlich. Hersteller, Kategorie und +Produktgruppe sind optional. Artikelnummern sind eindeutig; Namen dürfen sich +wiederholen. Die bestehenden REST-URLs `/articles` bleiben erhalten. + +- `quantity`: Bestand in der Basiseinheit, ohne Charge. +- `batch`: Chargennummer erforderlich; optional Ablaufverfolgung. +- `individual`: ein Exemplar pro Buchung, Menge 1, Basiseinheit `Stück`, + eindeutige Inventarnummer. Seriennummer, Zustand, Verwendung und + Anschaffungsdatum gehören zum Exemplar. + +Verbrauchbarkeit erzwingt keine bestimmte Bestandsführung. Das bisherige +`Category.isConsumable` bleibt aus Rücksicht auf die Kategorienverwaltung +bestehen, steuert aber keine Lagerbuchungen mehr. + +Eigenschaften enthalten Text, endliche Zahlen oder Wahrheitswerte. +Verpackungen haben `name`, `quantityInBaseUnits` und optional `barcode`. +Alle Lagerbuchungen verwenden Mengen in der Basiseinheit; die Oberfläche +rechnet Packungszahlen nicht automatisch um. Herstellerartikelnummer und +Barcode liegen direkt am Artikel. Lieferantenangebote und deren Nummern +sind noch kein eigener Funktionsbereich. + +## Beispiele + +| Nummer | Artikel | Einheit | Verbrauchbar | Bestandsführung | Ablaufverfolgung | +| ----------- | ------------------------------- | ------- | ------------ | --------------- | ---------------- | +| FLEISCH-001 | Schweinehals, ohne Knochen | kg | ja | batch | nein | +| OBST-001 | Banane, frisch | Stück | ja | quantity | nein | +| MILCH-001 | Vollmilch, 3,5 % Fett | Liter | ja | batch | ja | +| FLEISCH-002 | Schweinerücken, ohne Knochen | kg | ja | batch | nein | +| FLEISCH-003 | Rinderhüfte | kg | ja | batch | nein | +| ELEK-001 | Raspberry Pi 5, 8 GB RAM | Stück | nein | individual | nein | +| RAD-001 | Fahrradschlauch, 28 Zoll, SV 17 | Stück | ja | quantity | nein | + +Dies sind Vorschläge für Stammdaten, keine automatisch eingefügten Daten. + +## Lager-API + +- `POST /stock-movements/in`: `articleId`, `stockId`, `quantity`, optional + `area`; bei Chargen `batchNumber` und ggf. `expiryDate`; bei Einzelstücken + `inventoryNumber` und optionale Exemplardaten. +- `POST /stock-movements/out`: `stockContentId`, `quantity`. +- `POST /stock-movements/transfer`: `stockContentId`, `quantity`, `toStockId`, + optional `toArea`. Die Quelle wird eindeutig über den Bestandsdatensatz + ausgewählt. Das verhindert Verwechslungen zwischen Bereichen und Chargen. +- `GET /stock-content`: Bestände mit aufgelöstem Artikel, Lager, Charge und Exemplar. +- `GET /stock-content/summary/by-article`: Gesamtmenge je Artikel und Basiseinheit. + Die alte URL `summary/by-variant` bleibt als Alias bestehen, liefert jedoch + das neue Antwortformat mit `articleId`. +- `GET /batches`, `GET /assets`: Chargen bzw. Exemplare. +- `GET /article-groups`, `POST /article-groups`, `PATCH /article-groups/:id`: + optionale Produktgruppen. + +Eine Charge kann in mehreren Lagerbereichen liegen. Ein abweichendes Ablaufdatum +für dieselbe Charge wird zurückgewiesen. Ein ausgelagertes Exemplar kann unter +derselben Inventarnummer erneut eingelagert werden; seine Stammdaten bleiben erhalten. + +`DELETE /articles/:id` archiviert statt zu löschen. Archivierte Artikel sind in +bestehenden Beständen und Bewegungen weiter auflösbar, aber nicht mehr neu +wählbar. Entnahme und Umlagerung vorhandener Bestände bleiben möglich. +Einheit, Bestandsführung und Ablaufverfolgung sind nach vorhandenen Buchungen, +Chargen oder Exemplaren gesperrt. Bestände und Bewegungsprotokolle können nicht +mehr direkt gelöscht werden. + +## Datenbankvoraussetzung + +Bestandsänderung, Charge/Exemplar und Bewegungsprotokoll werden gemeinsam in +MongoDB-Transaktionen geschrieben. Dafür ist ein Replica Set (auch mit einem +Knoten) oder ein Sharded Cluster erforderlich. Ein Standalone-MongoDB-Server +unterstützt diese Buchungen nicht. Die konkrete Datenbank wurde hier nicht geprüft. + +Die Verbindungsadresse kann über die Prozess-Umgebungsvariable `MONGODB_URI` +konfiguriert werden. Ohne sie bleibt die bisherige Adresse erhalten. Das Backend +lädt keine `.env`-Dateien selbständig; die Variable muss vom Prozessmanager oder +der aufrufenden Shell gesetzt werden. + +## Übernahme bestehender Daten + +Es wird keine Migration beim Start ausgeführt. Vor der Übernahme Anwendung +anhalten und eine externe Datenbanksicherung erstellen. Den Ablauf zuerst mit +einer Kopie der Datenbank prüfen. Das Skript erstellt zusätzlich Sicherungskopien +in `migration_backup_*`, ersetzt aber keine externe Sicherung. + +1. `scripts/article-migration-review.example.json` kopieren und die Beispiel-IDs + durch die bestehenden **Varianten-IDs** ersetzen. Artikel ohne Varianten nutzen + ihre bisherige Artikel-ID. +2. Für jeden Datensatz Artikelnummer, Basiseinheit und Bestandsregeln festlegen. + Verpackungstext wird nicht automatisch als Zahl interpretiert. Bestehende + Mengen werden nicht umgerechnet; die festgelegte Basiseinheit muss zu deren + bisheriger Bedeutung passen. Alte Lieferantenartikelnummern werden als + Eigenschaft `legacySupplierArticleNumber` erhalten. Eine geprüfte + Herstellerartikelnummer kann im Review separat angegeben werden. +3. Vorschau ausführen, während `MONGODB_URI` auf die gewünschte Datenbank zeigt: + + ```sh + pnpm --filter backend articles:migration --review=/absoluter/pfad/review.json + ``` + +4. Alle gemeldeten Hindernisse beseitigen. Insbesondere enthalten alte + Auslagerungsprotokolle unter Umständen falsche Artikel- oder Lagerreferenzen. + Für solche Bewegungen in `movements` die Bewegungs-ID mit geprüften + `articleId`- und `stockId`-Werten eintragen. Widersprüchliche Chargendaten, + doppelte Bestandspositionen und ungültige Eigenschaften blockieren die Migration. +5. Erst nach Prüfung der Vorschau bewusst anwenden: + + ```sh + pnpm --filter backend articles:migration --review=/absoluter/pfad/review.json --apply + ``` + +Die Varianten-IDs werden zu Artikel-IDs. Übergeordnete alte Artikel werden +Produktgruppen. Alte Quelldatensätze bleiben erhalten; Bestands- und +Bewegungsreferenzen werden innerhalb einer Transaktion umgestellt. +Bereits vollständig migrierte Datensätze werden bei einem erneuten Lauf +übersprungen. Teilweise manuell migrierte Daten sind vorab separat zu prüfen. +Vorhandene Mengenbestände werden nicht automatisch auf einzelne Exemplare +aufgeteilt; dafür fehlen Inventarnummern und eine geprüfte Zuordnung. + +`GET /articles/migration-status` und die Artikelliste zeigen noch nicht +übernommene alte Artikel an. Diese erscheinen bis zur Migration nicht als +buchbare Artikel.