Artikel DB struktur geändert von CODEX

This commit is contained in:
Marco_205 committed 2026-10-12 14:42:28 +00:00
1 parent 0c0a678eaa
commit 9c18234efe
95 files changed
+3717 -2161

No files matched your search

+51
View File
@@ -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
+2 -1
View File
@@ -18,7 +18,8 @@
"test:watch": "jest --watch", "test:watch": "jest --watch",
"test:cov": "jest --coverage", "test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "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": { "dependencies": {
"@nestjs/common": "^11.0.1", "@nestjs/common": "^11.0.1",
@@ -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": {}
}
+468
View File
@@ -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<string, ArticleSettings>;
movements?: Record<string, { articleId: string; stockId: string }>;
}
interface LegacyArticle {
_id: Types.ObjectId;
name: string;
categoryId?: Types.ObjectId;
attributes?: Record<string, unknown>;
articleNumber?: string;
}
interface LegacyVariant {
_id: Types.ObjectId;
articleId: Types.ObjectId;
manufacturerId?: Types.ObjectId;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, unknown>;
}
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<string, unknown>;
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<LegacyArticle>('articles').find().toArray(),
connection
.collection<LegacyVariant>('articlevariants')
.find()
.toArray(),
connection.collection<LegacyContent>('stockcontents').find().toArray(),
connection
.collection<LegacyMovement>('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<string, { _id: Types.ObjectId; name: string }>();
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<string, ArticleSettings>([
...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<string>();
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;
});
+8 -6
View File
@@ -6,19 +6,21 @@ import { MongooseModule } from '@nestjs/mongoose';
import { LocationsModule } from './locations/locations.module'; import { LocationsModule } from './locations/locations.module';
import { UsersModule } from './users/users.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 { InventoryModule } from './inventory/inventory.module';
import { ChatGateway } from './chat.gateway'; import { ChatGateway } from './chat.gateway';
@Module({ @Module({
imports: [MongooseModule.forRoot('mongodb://192.168.50.206/nest'), imports: [
CatalogModule, MongooseModule.forRoot(
process.env.MONGODB_URI ?? 'mongodb://192.168.50.206/nest',
),
ProductsModule,
InventoryModule, InventoryModule,
UsersModule, UsersModule,
LocationsModule, LocationsModule,
], ],
//controllers: [AppController], //controllers: [AppController],
providers: [ChatGateway,LocationsModule], providers: [ChatGateway, LocationsModule],
}) })
export class AppModule { } export class AppModule {}
@@ -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<string, any>;
variants: ArticleVariantDto[]
}
export class ArticleAndVariantsDto {
_id: Types.ObjectId;
name: string;
categoryId: Types.ObjectId;
attributes?: Record<string, any>;
variants: {
_id:Types.ObjectId;
manufacturerId: Types.ObjectId;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}[]
}
export class ArticleVariantBaseDto {
_id: Types.ObjectId;
article: ArticleDto;
manufacturer: ManufacturerDto;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}
export class ArticleVariantDto {
@IsMongoId()
manufacturerId: string;
@IsOptional()
@IsString()
supplierArticleNumber?: string;
@IsOptional()
@IsString()
packagingUnit?: string;
@IsOptional()
@IsObject()
extra?: Record<string, any>;
}
export class ArticleCreateDto {
@IsString()
name: string;
@IsMongoId()
categoryId: string;
@IsOptional()
@IsObject()
attributes?: Record<string, any>;
@IsArray()
@ValidateNested({ each: true })
@Type(() => ArticleVariantDto)
variants: ArticleVariantDto[];
}
export class ArticleUpdateDto extends PartialType(ArticleCreateDto) {}
@@ -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<string, any>;
@IsOptional()
@IsBoolean()
deleted?: boolean;
}
export class ArticleUpsertDto {
@IsOptional()
//@IsMongoId()
_id: string;
@IsOptional()
@IsString()
name: string;
@IsOptional()
@IsMongoId()
categoryId: string;
@IsOptional()
@IsObject()
attributes?: Record<string, any>;
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => ArticleVariantUpsertDto)
variants: ArticleVariantUpsertDto[];
}
@@ -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<string, any>;
}
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 });
@@ -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<Article>,
private readonly articleRepository: ArticleRepository
) { }
create(dto: ArticleCreateDto) {
return this.articleRepository.creatArticle(dto);
}
async findAll(): Promise<ArticleDto[]> {
return this.articleRepository.findAll();
}
async findOne(id: string): Promise<ArticleDto> {
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);
}
}
@@ -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
}
}
}
];
@@ -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<Article>,
private readonly articleVariantRepository: ArticleVariantRepository
) { }
async findAll(): Promise<ArticleDto[]> {
const res = await this.articleModel.aggregate<ArticleDto>(
[...articleGetQuery]);
return res;
}
async findOne(id: string): Promise<ArticleDto> {
const res = await this.articleModel.aggregate<ArticleDto>(
[{ $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};
*/
}
}
@@ -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 { }
+1 -1
View File
@@ -13,7 +13,7 @@ import { Server } from 'socket.io';
}) })
export class ChatGateway { export class ChatGateway {
@WebSocketServer() @WebSocketServer()
server: Server; // 👈 DAS fehlt dir gerade server!: Server; // 👈 DAS fehlt dir gerade
@SubscribeMessage('message') @SubscribeMessage('message')
handleMessage(@MessageBody() data: string) { handleMessage(@MessageBody() data: string) {
+4 -4
View File
@@ -1,8 +1,8 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { DrawContainer } from 'src/graphics/lib/draw'; import { DrawContainer } from '../graphics/lib/draw';
import { DrawEllipse } from 'src/graphics/lib/drawEllipse'; import { DrawEllipse } from '../graphics/lib/drawEllipse';
import { DrawGroup } from 'src/graphics/lib/drawGroup'; import { DrawGroup } from '../graphics/lib/drawGroup';
import { DrawPath, PathCommand } from 'src/graphics/lib/drawPath'; import { DrawPath, PathCommand } from '../graphics/lib/drawPath';
@Injectable() @Injectable()
export class DrawService { export class DrawService {
@@ -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 { 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') @Controller('stock-movements')
export class StockMovementsController { export class StockMovementsController {
constructor( constructor(private readonly service: StockMovementsService) {}
@Post('in') stockIn(@Body() dto: StockMovementInDto) {
private readonly stockMovementsService: StockMovementsService return this.service.in(dto);
) { console.log('movement controller');}
@Post('in')
async stockIn(@Body() dto: StockMovementInDto) {
return this.stockMovementsService.in(dto);
} }
@Post('out') stockOut(@Body() dto: StockMovementOutDto) {
@Post('out') return this.service.out(dto);
async stockOut(@Body() dto: StockMovementOutDto) {
return this.stockMovementsService.out(dto);
} }
@Post('transfer') transfer(@Body() dto: StockMovementTransferDto) {
@Post('transfer') return this.service.transfer(dto);
async transfer(@Body() dto: StockMovementTransferDto) {
return this.stockMovementsService.transfer(dto);
} }
@Get() findAll() {
@Get() return this.service.findAll();
async findx() {
return "Hello from movement";
} }
@Delete(':id') remove(@Param('id') id: string) {
return this.service.remove(id);
@Get()
async findAll() {
return this.stockMovementsService.findAll();
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.stockMovementsService.remove(id);
} }
} }
@@ -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 { StockContentService } from '../stock-content/stock-content.service';
import { StockSummaryQuery } from '../_queries/stock-summary.query'; import { StockSummaryQuery } from '../_queries/stock-summary.query';
@@ -7,8 +15,7 @@ export class StockContentController {
constructor( constructor(
private readonly stockService: StockContentService, private readonly stockService: StockContentService,
private readonly stockSummaryQuery: StockSummaryQuery, private readonly stockSummaryQuery: StockSummaryQuery,
) { } ) {}
@Get() @Get()
findAll() { findAll() {
@@ -20,13 +27,12 @@ export class StockContentController {
return this.stockService.findOne(id); return this.stockService.findOne(id);
} }
@Delete(':id') @Delete(':id')
remove(@Param('id') id: string) { remove(@Param('id') id: string) {
return this.stockService.remove(id); return this.stockService.remove(id);
} }
@Get('summary/by-variant') @Get(['summary/by-article', 'summary/by-variant'])
getStockByVariant() { getStockByVariant() {
return this.stockSummaryQuery.byArticle(); return this.stockSummaryQuery.byArticle();
} }
@@ -1,50 +1,12 @@
import { PartialType } from "@nestjs/mapped-types"; import { ArticleDto } from '../../products/_dto/article.dto';
import { StockDto } from "./stock.dto"; import { StockDto } from './stock.dto';
import { ArticleVariantDto } from "src/catalog/_dto/article.dto";
export interface StockContentDto {
export class StockContentDto { id: string;
id:string
stock: StockDto; stock: StockDto;
articleVariant: ArticleVariantDto; article: ArticleDto;
batchNumber?: string; batchId?: string;
area?:string; assetId?: 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; area?: string;
}
export class StockContentNonConsumableInDto{
stockId: string;
articleVariantId: string;
quantity: number; quantity: number;
area?: string;
} }
export class StockContentUpdateDto extends PartialType(StockContentConsumableInDto) { }
@@ -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 { export enum StockMovementType {
IN = 'IN', IN = 'IN',
@@ -7,66 +16,53 @@ export enum StockMovementType {
} }
export class StockMovementInDto { export class StockMovementInDto {
@IsString()
@IsMongoId() @IsMongoId()
stockId: string; stockId!: string;
@IsString()
@IsMongoId() @IsMongoId()
articleVariantId: string; articleId!: string;
@IsNumber() @IsNumber()
quantity: number; @Min(Number.MIN_VALUE)
quantity!: number;
@IsString()
@IsOptional() @IsOptional()
@IsString()
@IsNotEmpty()
batchNumber?: string; batchNumber?: string;
@IsOptional()
@Type(() => Date)
@IsDate() @IsDate()
@IsOptional()
expiryDate?: Date; expiryDate?: Date;
@IsString()
@IsOptional() @IsOptional()
@IsString()
area?: string; 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 { export class StockMovementOutDto {
@IsString()
@IsMongoId() @IsMongoId()
stockContentId: string; stockContentId!: string;
@IsNumber() @IsNumber()
quantity: number; @Min(Number.MIN_VALUE)
quantity!: number;
} }
export class StockMovementTransferDto extends StockMovementOutDto {
export class StockMovementTransferDto {
@IsString()
@IsMongoId() @IsMongoId()
articleVariantId: string; toStockId!: string;
@IsString()
@IsMongoId()
fromStockId: string;
@IsString()
@IsMongoId()
toStockId: string;
@IsString()
@IsOptional() @IsOptional()
@IsString()
toArea?: string; toArea?: string;
@IsNumber()
quantity: number;
@IsString()
@IsOptional()
batchNumber?: string;
} }
+9 -9
View File
@@ -1,14 +1,14 @@
import { IsMongoId, IsOptional, IsString, IsArray } from "class-validator"; import { IsMongoId, IsOptional, IsString, IsArray } from "class-validator";
import { Types } from "mongoose"; import { Types } from "mongoose";
import { LocationDto } from "src/locations/dto/location.dto"; import { LocationDto } from "../../locations/dto/location.dto";
export class StockCreateDto { export class StockCreateDto {
@IsString() @IsString()
name: string; name!: string;
@IsString() @IsString()
@IsMongoId() @IsMongoId()
locationId: string; locationId!: string;
@IsArray() @IsArray()
@IsOptional() @IsOptional()
@@ -32,15 +32,15 @@ export class StockUpdateDto {
} }
export class StockRowDto { export class StockRowDto {
_id: string _id!: string
name: string; name!: string;
locationId: Types.ObjectId; locationId!: Types.ObjectId;
areas?:string[] areas?:string[]
} }
export class StockDto { export class StockDto {
id: string id!: string
name: string; name!: string;
location: LocationDto; location!: LocationDto;
areas?:string[] areas?:string[]
} }
@@ -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);
@@ -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 });
@@ -4,23 +4,28 @@ import { Document, Types } from 'mongoose';
@Schema({ timestamps: true }) @Schema({ timestamps: true })
export class StockContent extends Document { export class StockContent extends Document {
@Prop({ type: Types.ObjectId, ref: 'Stock', required: true }) @Prop({ type: Types.ObjectId, ref: 'Stock', required: true })
stockId: Types.ObjectId; stockId!: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'ArticleVariant', required: true }) @Prop({ type: Types.ObjectId, ref: 'Article', required: true })
articleVariantId: Types.ObjectId; articleId!: Types.ObjectId;
@Prop({required:false}) @Prop({ type: Types.ObjectId, ref: 'Batch', default: null })
batchNumber?: string; batchId?: Types.ObjectId | null;
@Prop({ required: true }) @Prop({ type: Types.ObjectId, ref: 'Asset', default: null })
quantity: number; assetId?: Types.ObjectId | null;
@Prop() @Prop({ required: true, min: 0 })
expiryDate?: Date; quantity!: number;
@Prop()
area?: string;
@Prop({ default: '' })
area!: string;
} }
export const StockContentSchema = SchemaFactory.createForClass(StockContent); export const StockContentSchema = SchemaFactory.createForClass(StockContent);
StockContentSchema.index(
{ articleId: 1, stockId: 1, batchId: 1, assetId: 1, area: 1 },
{
unique: true,
partialFilterExpression: { articleId: { $type: 'objectId' } },
},
);
@@ -2,30 +2,23 @@ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose'; import { Document, Types } from 'mongoose';
import { StockMovementType } from '../_dto/stock-movement.dto'; import { StockMovementType } from '../_dto/stock-movement.dto';
@Schema({ timestamps: true }) @Schema({ timestamps: true })
export class StockMovement extends Document { export class StockMovement extends Document {
@Prop({ type: Types.ObjectId, ref: 'Stock', required: true }) @Prop({ type: Types.ObjectId, ref: 'Stock', required: true })
stockId: Types.ObjectId; stockId!: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'Article', required: true })
@Prop({ type: Types.ObjectId, ref: 'ArticleVariant', required: true }) articleId!: Types.ObjectId;
articleVariantId: Types.ObjectId; @Prop({ type: String, enum: StockMovementType, required: true })
type!: StockMovementType;
@Prop({ required: true, min: Number.MIN_VALUE })
@Prop({ type: String, enum: StockMovementType, required: true, }) quantity!: number;
type: StockMovementType;
@Prop({ required: true, min: 1 })
quantity: number;
@Prop({ type: Types.ObjectId, ref: 'Stock' }) @Prop({ type: Types.ObjectId, ref: 'Stock' })
toStockId?: Types.ObjectId; toStockId?: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'Batch' })
batchId?: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'Asset' })
assetId?: Types.ObjectId;
@Prop({ type: Object }) @Prop({ type: Object })
meta?: Record<string, any>; meta?: Record<string, unknown>;
} }
export const StockMovementSchema = SchemaFactory.createForClass(StockMovement);
export const StockMovementSchema =
SchemaFactory.createForClass(StockMovement);
@@ -4,13 +4,13 @@ import { Document, Types } from 'mongoose';
@Schema({ timestamps: false }) @Schema({ timestamps: false })
export class Stock extends Document { export class Stock extends Document {
@Prop({ required: true }) @Prop({ required: true })
name: string; name!: string;
@Prop({ type: Types.ObjectId, ref: 'Location', required: true }) @Prop({ type: Types.ObjectId, ref: 'Location', required: true })
locationId: Types.ObjectId; locationId!: Types.ObjectId;
@Prop({ }) @Prop({ })
areas: Types.Array<string>; areas!: Types.Array<string>;
} }
@@ -1,95 +1,37 @@
import { Injectable, BadRequestException } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose'; import { Model } from 'mongoose';
import { StockContent } from '../_entities/stock-content.entity' import { StockContent } from '../_entities/stock-content.entity';
@Injectable() @Injectable()
export class StockSummaryQuery { export class StockSummaryQuery {
constructor( constructor(
@InjectModel(StockContent.name) @InjectModel(StockContent.name) private readonly model: Model<StockContent>,
private readonly stockModel: Model<StockContent>, ) {}
) { } byArticle() {
return this.model
async byArticle() { .aggregate([
console.log('get'); { $match: { articleId: { $exists: true } } },
const x = await this.stockModel.aggregate<{id_:string,articleVariantId:string,articleName:string,manufacturer:string,totalQuantity:number}>([ { $group: { _id: '$articleId', totalQuantity: { $sum: '$quantity' } } },
{
$group: {
_id: '$articleVariantId',
totalQuantity: { $sum: '$quantity' },
},
},
{
$lookup: {
from: 'articlevariants',
localField: '_id',
foreignField: '_id',
as: 'variant',
}
},
{ $unwind: '$variant' },
{ {
$lookup: { $lookup: {
from: 'articles', from: 'articles',
localField: 'variant.articleId', localField: '_id',
foreignField: '_id', foreignField: '_id',
as: 'article', as: 'article',
}, },
}, },
{ $unwind: '$article' }, { $unwind: '$article' },
// 4️⃣ Hersteller holen
{
$lookup: {
from: 'manufacturers',
localField: 'variant.manufacturerId',
foreignField: '_id',
as: 'manufacturer',
},
},
{ $unwind: '$manufacturer' },
{ {
$project: { $project: {
_id: 0, _id: 0,
articleVariantId: '$_id', articleId: '$_id',
articleName: '$article.name', articleName: '$article.name',
manufacturer: '$manufacturer.name', baseUnit: '$article.baseUnit',
totalQuantity: 1, 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' },
}, },
}, ])
{ .exec();
$lookup: {
from: 'articlevariants',
localField: '_id',
foreignField: '_id',
as: 'variant',
},
},
{ $unwind: '$variant' },
{
$lookup: {
from: 'articles',
localField: 'variant.articleId',
foreignField: '_id',
as: 'article',
},
},
{ $unwind: '$article' },
]);
} }
} }
@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { MovementsModule } from './movements/movements.module'; import { MovementsModule } from './movements/movements.module';
import { StockContentModule } from './stock-content/stock-content.module'; import { StockContentModule } from './stock-content/stock-content.module';
import { StockModule } from './stock/stock.module'; import { StockModule } from './stock/stock.module';
import { LocationsModule } from 'src/locations/locations.module'; import { LocationsModule } from '../locations/locations.module';
@Module({ @Module({
imports: [ imports: [
@@ -1,76 +1,53 @@
import { Injectable } from '@nestjs/common'; import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose'; import { ClientSession, Model, Types } from 'mongoose';
import { StockMovement } from '../_entities/stock-movement.entity'; import { StockMovement } from '../_entities/stock-movement.entity';
import { StockContent } from '../_entities/stock-content.entity';
import { StockMovementInDto, StockMovementType, StockMovementTransferDto, StockMovementOutDto } from '../_dto/stock-movement.dto'; import { StockMovementType } from '../_dto/stock-movement.dto';
@Injectable() @Injectable()
export class MovementRepository { export class MovementRepository {
constructor( constructor(
@InjectModel(StockMovement.name) @InjectModel(StockMovement.name)
private readonly model: Model<StockMovement>, private readonly model: Model<StockMovement>,
) {}
) { } findAll() {
return this.model
async findAll() { .find({ articleId: { $exists: true } })
return this.model.find().exec(); .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',
); );
} }
async log(
type: StockMovementType,
// =============================== content: StockContent,
// OUT quantity: number,
// =============================== session: ClientSession,
async logStockMoveOut(dto: StockMovementOutDto,result:any) { toStockId?: string,
toArea?: string,
return this.model.create({ ) {
stockId: new Types.ObjectId(dto.stockContentId), const [movement] = await this.model.create(
articleVariantId: new Types.ObjectId(result.articelVariantId), [
type: StockMovementType.OUT, {
quantity: dto.quantity, type,
}); articleId: content.articleId,
} stockId: content.stockId,
// ===============================
// 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, quantity,
batchId: content.batchId ?? undefined,
assetId: content.assetId ?? undefined,
toStockId: toStockId ? new Types.ObjectId(toStockId) : undefined,
meta: { meta: {
fromLocationId: new Types.ObjectId(fromStockId), fromArea: content.area,
toLocationId: new Types.ObjectId(toStockId), ...(toArea !== undefined ? { toArea } : {}),
}, },
}); },
],
{ session },
);
return movement;
} }
} }
@@ -1,43 +1,22 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { StockMovementsController } from '../_controllers/movements.controller';
import { StockMovementsService } from './movements.service';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { StockMovementsController } from '../_controllers/movements.controller';
import { MovementRepository } from './movement.repository'; import {
StockMovement,
import { StockContent, StockContentSchema } from '../_entities/stock-content.entity'; StockMovementSchema,
import { StockMovement, StockMovementSchema } from '../_entities/stock-movement.entity'; } 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 { StockContentModule } from '../stock-content/stock-content.module'; import { StockContentModule } from '../stock-content/stock-content.module';
import { StockContentRepository } from '../stock-content/stock-content.repository'; import { StockMovementsService } from './movements.service';
import { StockContentService } from '../stock-content/stock-content.service'; import { MovementRepository } from './movement.repository';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([ MongooseModule.forFeature([
{ name: StockContent.name, schema: StockContentSchema },
{ name: StockMovement.name, schema: StockMovementSchema }, { name: StockMovement.name, schema: StockMovementSchema },
{ name: Article.name, schema: ArticleSchema },
{ name: ArticleVariant.name, schema: ArticleVariantSchema },
]), ]),
CatalogModule, StockContentModule,
], ],
controllers: [StockMovementsController], controllers: [StockMovementsController],
providers: [ providers: [StockMovementsService, MovementRepository],
StockMovementsService,
StockContentService,
StockContentRepository,
MovementRepository,
],
}) })
export class MovementsModule { } export class MovementsModule {}
@@ -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',
);
});
});
@@ -1,48 +1,94 @@
import { Injectable, BadRequestException } from '@nestjs/common'; import {
import { StockMovementOutDto, StockMovementInDto, StockMovementTransferDto } from '../_dto/stock-movement.dto'; 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 { MovementRepository } from './movement.repository';
import { StockContentService } from '../stock-content/stock-content.service'; import { StockContentService } from '../stock-content/stock-content.service';
@Injectable() @Injectable()
export class StockMovementsService { export class StockMovementsService {
constructor( constructor(
private readonly movementRepo: MovementRepository, private readonly movementRepo: MovementRepository,
private readonly stockContentService: StockContentService private readonly stockContentService: StockContentService,
) { } @InjectConnection() private readonly connection: Connection,
) {}
findAll() { findAll() {
return this.movementRepo.findAll(); return this.movementRepo.findAll();
} }
remove(id: string) { remove(id: string) {
return this.movementRepo.remove(id); return this.movementRepo.remove(id);
} }
in(dto: StockMovementInDto) {
return this.book(async (session) => {
async in(dto: StockMovementInDto) { const content = await this.stockContentService.moveIn(dto, session);
this.validateIn(dto); return this.movementRepo.log(
StockMovementType.IN,
const result = this.stockContentService.moveIn(dto); content,
return await this.movementRepo.logStockMoveIn(dto); dto.quantity,
session,
);
});
} }
out(dto: StockMovementOutDto) {
async out(dto: StockMovementOutDto) { return this.book(async (session) => {
const outResult = await this.stockContentService.moveOut(dto); const content = await this.stockContentService.moveOut(dto, session);
return await this.movementRepo.logStockMoveOut(dto, outResult); return this.movementRepo.log(
StockMovementType.OUT,
content,
dto.quantity,
session,
);
});
} }
transfer(dto: StockMovementTransferDto) {
async transfer(dto: StockMovementTransferDto) { return this.book(async (session) => {
const result = await this.stockContentService.transfer(dto); const content = await this.stockContentService.transfer(dto, session);
return this.movementRepo.logStockContentTransfer(dto); return this.movementRepo.log(
StockMovementType.TRANSFER,
content,
dto.quantity,
session,
dto.toStockId,
dto.toArea ?? '',
);
});
} }
private async book<T>(
action: (session: ClientSession) => Promise<T>,
private validateIn(dto: StockMovementInDto) { ): Promise<T> {
if (dto.quantity <= 0) { try {
throw new BadRequestException('Menge muss > 0 sein'); 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;
} }
} }
} }
@@ -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();
}
}
@@ -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<Batch>,
@InjectModel(Asset.name) private readonly assets: Model<Asset>,
) {}
findBatches() {
return this.batches.find().populate('articleId').exec();
}
findAssets() {
return this.assets.find().populate('articleId').populate('stockId').exec();
}
}
@@ -0,0 +1,2 @@
export { InventoryRecordsController } from './inventory-records.controller';
export { InventoryRecordsService } from './inventory-records.service';
@@ -1,27 +1,39 @@
import { Module } from '@nestjs/common'; 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 { StockContentService } from './stock-content.service';
import { StockContentRepository } from './stock-content.repository';
import { StockContentController } from '../_controllers/stock-content.controller'; import { StockContentController } from '../_controllers/stock-content.controller';
import { StockSummaryQuery } from '../_queries/stock-summary.query'; import { StockSummaryQuery } from '../_queries/stock-summary.query';
import {
import { MongooseModule } from '@nestjs/mongoose'; InventoryRecordsController,
import { StockContent, StockContentSchema } from '../_entities/stock-content.entity'; InventoryRecordsService,
import { StockContentRepository } from './stock-content.repository'; } from '../records/inventory-records';
import { CatalogModule } from 'src/catalog/catalog.module';
import { StockModule } from '../stock/stock.module';
import { StockService } from '../stock/stock.service';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([ MongooseModule.forFeature([
{ name: StockContent.name, schema: StockContentSchema }, { 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], controllers: [StockContentController, InventoryRecordsController],
providers: [StockContentService, StockSummaryQuery,StockContentRepository], providers: [
exports: [StockContentService] StockContentService,
StockContentRepository,
StockSummaryQuery,
InventoryRecordsService,
],
exports: [StockContentService],
}) })
export class StockContentModule { } export class StockContentModule {}
@@ -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<T>(value: T) {
return {
session: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(value),
};
}
function setup(article: Partial<Article> = {}) {
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<StockContent>,
articles as unknown as Model<Article>,
stocks as unknown as Model<Stock>,
batches as unknown as Model<Batch>,
assets as unknown as Model<Asset>,
);
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 }),
);
});
});
@@ -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 { import {
StockContentConsumableInDto, BadRequestException,
StockContentNonConsumableInDto, ConflictException,
StockContentFindConsumableDto, Injectable,
StockContentFindNonConsumableDto NotFoundException,
} from '../_dto/stock-content.dto'; } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { StockMovementOutDto, StockMovementTransferDto } from '../_dto/stock-movement.dto'; import { ClientSession, Model, Types } from 'mongoose';
import { ArticleVariantService } from 'src/catalog/article-variant/article-variant.service'; 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() @Injectable()
export class StockContentRepository { export class StockContentRepository {
constructor( constructor(
@InjectModel(StockContent.name) @InjectModel(StockContent.name) private readonly model: Model<StockContent>,
private readonly model: Model<StockContent>, @InjectModel(Article.name) private readonly articles: Model<Article>,
//private readonly articleService: ArticleVariantService, @InjectModel(Stock.name) private readonly stocks: Model<Stock>,
@InjectModel(Batch.name) private readonly batches: Model<Batch>,
@InjectModel(Asset.name) private readonly assets: Model<Asset>,
) {}
) { } 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) { if (article.trackingMode === TrackingMode.BATCH) {
return this.model.findByIdAndDelete(id); if (!dto.batchNumber?.trim())
} throw new BadRequestException('Chargennummer erforderlich');
const existing = await this.batches
async findById(stockId: string) {
return this.model.findById(stockId);
}
async findNonConsumable(dto: StockContentFindNonConsumableDto) {
return this.model
.findOne({ .findOne({
articleVariantId: dto.articleVariantId, articleId: article._id,
stockId: dto.stockId, batchNumber: dto.batchNumber.trim(),
batchNumber: null,
}) })
.session(session)
} .exec();
if (
async findConsumable(dto: StockContentFindConsumableDto) { article.tracksExpiryDate &&
const { articleVariantId, stockId, batchNumber } = dto; !dto.expiryDate &&
!existing?.expiryDate
return this.model ) {
.findOne({
articleVariantId,
stockId,
batchNumber,
})
}
/**
* Stock IN
*/
//--- Konsumierbare artikel
async moveConsumableIn(dto: StockContentConsumableInDto): Promise<StockContent> {
const { stockId, articleVariantId, batchNumber, quantity } = dto;
if (!batchNumber) {
throw new BadRequestException( throw new BadRequestException(
'Batch Nummer erfoderlich erforderlich', '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(
'Charge und Ablaufdatum sind nur bei Chargenführung erlaubt',
); );
} }
const stockContent = await this.findConsumable({ stockId, articleVariantId, batchNumber }); if (article.trackingMode === TrackingMode.INDIVIDUAL) {
if (dto.quantity !== 1 || !dto.inventoryNumber?.trim()) {
return await this.moveIn(dto, stockContent); throw new BadRequestException(
'Einzelstücke benötigen Menge 1 und eine Inventarnummer',
);
} }
const inventoryNumber = dto.inventoryNumber.trim();
const existing = await this.assets
// Nicht Konsumierbare artikel .findOne({ inventoryNumber })
async moveNonConsumableIn(dto: StockContentNonConsumableInDto): Promise<StockContent> { .session(session)
.exec();
const stockContent = await this.findNonConsumable({ if (existing) {
articleVariantId: dto.articleVariantId, if (
stockId: dto.stockId, existing.articleId.toString() !== article._id.toString() ||
}); existing.status !== 'withdrawn'
return this.moveIn(dto, stockContent);
}
private async moveIn(dto: StockContentConsumableInDto, stockContent?: StockContent | null): Promise<StockContent> {
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 (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,
}
if(toArea) data['area'] = toArea;
this.moveConsumableIn(data)
}
}
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 increaseOrCreate(
data: {
articleId: string;
locationId: string;
quantity: number;
expiryDate?: Date;
batchNumber?: string;
},
session?: ClientSession,
) { ) {
const filter: any = { throw new ConflictException(
articleId: data.articleId, 'Inventarnummer gehört zu einem anderen Artikel oder ist bereits eingelagert',
locationId: data.locationId, );
expiryDate: data.expiryDate ?? null, }
batchNumber: data.batchNumber ?? null, await this.assets.updateOne(
}; { _id: existing._id },
{
const stock = await this.model $set: {
.findOne(filter) status: 'in-stock',
.session(session ?? null); stockId: new Types.ObjectId(dto.stockId),
},
if (stock) { },
stock.quantity += data.quantity; { session },
await stock.save({ session }); );
assetId = existing._id;
} else { } else {
await this.model.create([data], { session }); 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;
} }
} 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();
}
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');
}
private async validateStock(
stockId: string,
area: string | undefined,
session: ClientSession,
) {
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');
}
}
@@ -1,234 +1,55 @@
import { Injectable, NotFoundException } from '@nestjs/common'; import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose'; import { ClientSession, Model, Types } from 'mongoose';
import { StockContent } from '../_entities/stock-content.entity'; 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 { StockContentRepository } from './stock-content.repository';
import { StockMovementInDto, StockMovementOutDto, StockMovementTransferDto } from '../_dto/stock-movement.dto'; import {
import { ArticleVariantService } from 'src/catalog/article-variant/article-variant.service'; StockMovementInDto,
import { StockService } from '../stock/stock.service'; StockMovementOutDto,
StockMovementTransferDto,
} from '../_dto/stock-movement.dto';
@Injectable() @Injectable()
export class StockContentService { export class StockContentService {
constructor( constructor(
@InjectModel(StockContent.name) private stockContentModel: Model<StockContent>, @InjectModel(StockContent.name) private readonly model: Model<StockContent>,
private readonly stockContentRepo: StockContentRepository, private readonly repository: StockContentRepository,
private readonly articleVariantService: ArticleVariantService, ) {}
// private readonly stockService: StockService findAll() {
return this.model
) { } .find({ articleId: { $exists: true } })
.populate('articleId')
async findAll() { .populate({ path: 'stockId', populate: { path: 'locationId' } })
let stockContent = await this.stockContentModel.aggregate<StockContent>([ .populate('batchId')
{ .populate('assetId')
$lookup: { .exec();
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<StockContentDto>([
{
$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) { async findOne(id: string) {
const item = await this.stockContentModel.findById(id); if (!Types.ObjectId.isValid(id))
if (!item) throw new NotFoundException('Stock Content nicht gefunden'); 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; return item;
} }
remove(_id: string): never {
throw new BadRequestException('Bestände nur über Auslagerungen verändern');
remove(id: string) {
return this.stockContentRepo.remove(id);
} }
moveIn(dto: StockMovementInDto, session: ClientSession) {
return this.repository.moveIn(dto, session);
//--- Stock IN
async moveIn(dto: StockMovementInDto): Promise<StockContent> {
const articleVariant = await this.articleVariantService.findOne(dto.articleVariantId);
const avId = articleVariant._id.toString();
const isConsumable = articleVariant.article.category.isConsumable;
let moveData = {
...dto,
articleVariantId: avId,
} }
moveOut(dto: StockMovementOutDto, session: ClientSession) {
if (isConsumable) { return this.repository.moveOut(dto, session);
return await this.stockContentRepo.moveConsumableIn(moveData);
} else {
return await this.stockContentRepo.moveNonConsumableIn(moveData);
} }
} transfer(dto: StockMovementTransferDto, session: ClientSession) {
return this.repository.transfer(dto, session);
//--- 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,
}
} }
} }
@@ -6,7 +6,7 @@ import { MongooseModule } from '@nestjs/mongoose';
import { Stock, StockSchema } from '../_entities/stock.entity'; import { Stock, StockSchema } from '../_entities/stock.entity';
import { StockController } from '../_controllers/stock.controller'; import { StockController } from '../_controllers/stock.controller';
import { StockService } from './stock.service'; import { StockService } from './stock.service';
import { LocationsModule } from 'src/locations/locations.module'; import { LocationsModule } from '../../locations/locations.module';
@Module({ @Module({
@@ -5,7 +5,7 @@ import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose'; import { Model, Types } from 'mongoose';
import { Stock } from '../_entities/stock.entity'; import { Stock } from '../_entities/stock.entity';
import { StockCreateDto, StockDto, StockRowDto, StockUpdateDto } from '../_dto/stock.dto'; import { StockCreateDto, StockDto, StockRowDto, StockUpdateDto } from '../_dto/stock.dto';
import { LocationsService } from 'src/locations/locations.service'; import { LocationsService } from '../../locations/locations.service';
@Injectable() @Injectable()
+11 -11
View File
@@ -5,7 +5,7 @@ import { Types } from 'mongoose';
export class LocationCreateDto { export class LocationCreateDto {
@IsString() @IsString()
name: string; name!: string;
@IsOptional() @IsOptional()
@IsString() @IsString()
@@ -20,32 +20,32 @@ export class LocationUpdateDto extends PartialType(LocationCreateDto) { }
export class LocationNodeDto { export class LocationNodeDto {
@IsString() @IsString()
_id: Types.ObjectId; _id!: Types.ObjectId;
@IsString() @IsString()
name: string; name!: string;
parentLocationId: Types.ObjectId; parentLocationId?: Types.ObjectId;
children: LocationNodeDto[]; children!: LocationNodeDto[];
} }
export class LocationDto { export class LocationDto {
id: string; id!: string;
name: string; name!: string;
parentLocation?: LocationViewDto; parentLocation?: LocationViewDto;
children?: LocationViewDto[]; children?: LocationViewDto[];
} }
export class LocationViewDto { export class LocationViewDto {
id: string; id!: string;
name: string; name!: string;
parentLocation?: string; parentLocation?: string;
} }
export class LocationRawDto { export class LocationRawDto {
_id: string; _id!: string;
name: string; name!: string;
parentLocationId?: Types.ObjectId; parentLocationId?: Types.ObjectId;
} }
@@ -4,13 +4,13 @@ import { Document, Types } from 'mongoose';
@Schema({ timestamps: true }) @Schema({ timestamps: true })
export class Location extends Document { export class Location extends Document {
@Prop({ required: true }) @Prop({ required: true })
name: string; name!: string;
@Prop() @Prop()
description?: string; description?: string;
@Prop({ type: Types.ObjectId, ref: 'Location' }) @Prop({ type: Types.ObjectId, ref: 'Location' })
parentLocationId: Types.ObjectId parentLocationId?: Types.ObjectId
} }
@@ -17,7 +17,7 @@ export class LocationsService {
return this.locationModel.create({ return this.locationModel.create({
name, name,
parentLocationId: new Types.ObjectId(parentLocationId), ...(parentLocationId ? { parentLocationId: new Types.ObjectId(parentLocationId) } : {}),
description description
}); });
} }
@@ -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) {}
@@ -4,17 +4,17 @@ import { ArticleDto } from './article.dto';
import { PartialType } from '@nestjs/mapped-types'; import { PartialType } from '@nestjs/mapped-types';
export class ArticleVariantDto { export class ArticleVariantDto {
_id: Types.ObjectId; _id!: Types.ObjectId;
article: ArticleDto; article!: ArticleDto;
manufacturer: ManufacturerDto; manufacturer!: ManufacturerDto;
supplierArticleNumber?: string; supplierArticleNumber?: string;
packagingUnit?: string; packagingUnit?: string;
extra?: Record<string, any>; extra?: Record<string, any>;
} }
export class ArticleVariantCreateDto { export class ArticleVariantCreateDto {
articleId: Types.ObjectId; articleId!: Types.ObjectId;
manufacturerId: Types.ObjectId; manufacturerId!: Types.ObjectId;
supplierArticleNumber?: string; supplierArticleNumber?: string;
packagingUnit?: string; packagingUnit?: string;
extra?: Record<string, any>; extra?: Record<string, any>;
@@ -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<string, string | number | boolean>;
@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;
}
@@ -2,8 +2,8 @@ import { PartialType } from "@nestjs/mapped-types";
import { Types } from "mongoose"; import { Types } from "mongoose";
export class CategoryCreateDto { export class CategoryCreateDto {
name: string; name!: string;
isConsumable: boolean; isConsumable!: boolean;
description?: string; description?: string;
requiredAttributes?: Record<string, any>; requiredAttributes?: Record<string, any>;
parentCategoryId?: Types.ObjectId; parentCategoryId?: Types.ObjectId;
@@ -13,9 +13,9 @@ export class CategoryCreateDto {
export class CategoryUpdateDto extends PartialType(CategoryCreateDto) {} export class CategoryUpdateDto extends PartialType(CategoryCreateDto) {}
export class CategoryDto { export class CategoryDto {
_id: Types.ObjectId; _id!: Types.ObjectId;
name: string; name!: string;
isConsumable: boolean; isConsumable!: boolean;
description?: string; description?: string;
requiredAttributes?: Record<string, any>; requiredAttributes?: Record<string, any>;
parentCategoryId?: Types.ObjectId; parentCategoryId?: Types.ObjectId;
@@ -3,17 +3,17 @@ import { Types } from "mongoose";
export class ManufacturerCreateDto { export class ManufacturerCreateDto {
@IsString() @IsString()
name: string; name!: string;
} }
export class ManufacturerDto { export class ManufacturerDto {
_id: Types.ObjectId; _id!: Types.ObjectId;
name: string; name!: string;
} }
export class ManufacturerUpdateDto { export class ManufacturerUpdateDto {
@IsOptional() @IsOptional()
@IsString() @IsString()
name: string; name?: string;
} }
@@ -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<string, unknown>;
deleted?: boolean;
}
@@ -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);
@@ -4,10 +4,10 @@ import { Document, Types } from 'mongoose';
@Schema() @Schema()
export class ArticleVariant extends Document { export class ArticleVariant extends Document {
@Prop({ type: Types.ObjectId, ref: 'Article', required: true }) @Prop({ type: Types.ObjectId, ref: 'Article', required: true })
articleId: Types.ObjectId; articleId!: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'Manufacturer', required: true }) @Prop({ type: Types.ObjectId, ref: 'Manufacturer', required: true })
manufacturerId: Types.ObjectId; manufacturerId!: Types.ObjectId;
@Prop() @Prop()
supplierArticleNumber?: string; supplierArticleNumber?: string;
@@ -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<string, string | number | boolean>;
@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 });
@@ -5,13 +5,13 @@ import { Document, Types } from 'mongoose';
@Schema({ timestamps: true }) @Schema({ timestamps: true })
export class Category extends Document { export class Category extends Document {
@Prop({ required: true }) @Prop({ required: true })
name: string; name!: string;
@Prop() @Prop()
description?: string; description?: string;
@Prop({ default: true }) @Prop({ default: true })
isConsumable: boolean; isConsumable!: boolean;
@Prop({ type: Map, of: String }) @Prop({ type: Map, of: String })
requiredAttributes?: Map<string, string>; requiredAttributes?: Map<string, string>;
@@ -5,7 +5,7 @@ import { Document, Types } from 'mongoose';
@Schema() @Schema()
export class Manufacturer extends Document { export class Manufacturer extends Document {
@Prop({ required: true }) @Prop({ required: true })
name: string; name!: string;
} }
@@ -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);
}
}
@@ -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 {}
@@ -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<ArticleGroup>,
) {}
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();
}
}
@@ -1,10 +1,10 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose'; import { Model, Types } from 'mongoose';
import { ArticleVariantCreateDto, ArticleVariantDto, ArticleVariantUpdateDto } from 'src/catalog/_dto/article-variant.dto'; import { ArticleVariantCreateDto, ArticleVariantDto, ArticleVariantUpdateDto } from '../../_dto/article-variant.dto';
import { ArticleVariant } from 'src/catalog/_entities/article-variant.entity'; import { ArticleVariant } from '../../_entities/article-variant.entity';
import { articleVariantGetQuery } from '../querys/article-variant-get.query'; 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'; import { BulkWriteResult } from 'mongodb';
@Injectable() @Injectable()
@@ -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<Article>,
{} 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<Article>,
{} 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<Article>,
connection as unknown as Connection,
);
jest.spyOn(repository, 'findOne').mockResolvedValue(current);
await expect(
repository.update(current._id, { baseUnit: 'kg' }),
).rejects.toBeInstanceOf(ConflictException);
});
});
@@ -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 { 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'; import { ArticleUpsertDto } from '../_dto/upsert-article.dto';
@Controller('articles') @Controller('articles')
export class ArticlesController { export class ArticlesController {
constructor( constructor(private readonly articlesService: ArticlesService) {}
private readonly articlesService: ArticlesService,
) { }
@Post() @Post()
create(@Body() dto: ArticleCreateDto) { create(@Body() dto: ArticleCreateDto) {
console.log('Create Artikel') console.log('Create Artikel');
return this.articlesService.create(dto); return this.articlesService.create(dto);
} }
@@ -22,23 +27,24 @@ export class ArticlesController {
return this.articlesService.findAll(); return this.articlesService.findAll();
} }
@Get('migration-status')
migrationStatus() {
return this.articlesService.migrationStatus();
}
@Get(':id') @Get(':id')
findOne(@Param('id') id: string) { findOne(@Param('id') id: string) {
console.log('Find one') console.log('Find one');
return this.articlesService.findOne(id); return this.articlesService.findOne(id);
} }
@Patch(':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); return this.articlesService.update(id, updateArticleDto);
} }
@Delete(':id') @Delete(':id')
remove(@Param('id') id: string) { remove(@Param('id') id: string) {
return this.articlesService.remove(id); return this.articlesService.remove(id);
} }
} }
@@ -1,22 +1,16 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ArticlesService } from './articles.service';
import { ArticlesController } from './articles.controller';
import { MongooseModule } from '@nestjs/mongoose'; import { MongooseModule } from '@nestjs/mongoose';
import { Article, ArticleSchema } from '../_entities/article.entity'; 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'; import { ArticleRepository } from './repository/article.repository';
@Module({ @Module({
imports: [ imports: [
MongooseModule.forFeature([ MongooseModule.forFeature([{ name: Article.name, schema: ArticleSchema }]),
{ name: Article.name, schema: ArticleSchema },
]),
ArticleVariantModule
], ],
controllers: [ArticlesController], controllers: [ArticlesController],
providers: [ArticlesService,ArticleRepository], providers: [ArticlesService, ArticleRepository],
exports:[ArticlesService] exports: [ArticlesService],
}) })
export class ArticlesModule { } export class ArticlesModule {}
@@ -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);
}
}
@@ -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 } },
];
@@ -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<Article>,
@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<ArticleDto[]> {
return this.articleModel
.aggregate<ArticleDto>([
{ $match: { archivedAt: null, articleNumber: { $exists: true } } },
...articleGetQuery,
{ $sort: { name: 1, articleNumber: 1 } },
])
.exec();
}
async findOne(id: string): Promise<ArticleDto> {
this.validateId(id);
const [article] = await this.articleModel
.aggregate<ArticleDto>([
{
$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;
}
}
@@ -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 {}
@@ -2,10 +2,10 @@ import { IsString, IsEmail, IsOptional, IsInt, Min } from 'class-validator';
export class CreateUserDto { export class CreateUserDto {
@IsString() @IsString()
name: string; name!: string;
@IsEmail() @IsEmail()
email: string; email!: string;
@IsOptional() @IsOptional()
@IsInt() @IsInt()
@@ -4,10 +4,10 @@ import { Document } from 'mongoose';
@Schema() @Schema()
export class User extends Document { export class User extends Document {
@Prop({ required: true }) @Prop({ required: true })
name: string; name!: string;
@Prop({ required: true, unique: true }) @Prop({ required: true, unique: true })
email: string; email!: string;
} }
+1 -1
View File
@@ -1,4 +1,4 @@
{ {
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"] "exclude": ["node_modules", "test", "dist", "**/*spec.ts", "scripts"]
} }
+3 -1
View File
@@ -13,7 +13,9 @@
"target": "ES2023", "target": "ES2023",
"sourceMap": true, "sourceMap": true,
"outDir": "./dist", "outDir": "./dist",
"baseUrl": "./", "paths": {
"@/*": ["./src/*"]
},
"incremental": true, "incremental": true,
"skipLibCheck": true, "skipLibCheck": true,
"strictNullChecks": true, "strictNullChecks": true,
+12
View File
@@ -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"]
}
+80 -77
View File
@@ -1,94 +1,97 @@
'use server' 'use server';
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache';
import { Article, ArticleCreate, ArticleUpsert } from "@/apps/frontend/types/catalog"; import {
Article,
ArticleCreate,
ArticleGroup,
ArticleUpsert,
} from '../types/catalog';
import { sites } from '../_config/sites'; import { sites } from '../_config/sites';
import { endpoints } from '../_config/endpoints';
export async function articleCreate(data: ArticleCreate) { const api = endpoints.apiServer.url;
console.log(data);
const result = await fetch('http://192.168.50.205/api/articles', { async function mutate(
method: 'POST', url: string,
method: string,
data?: unknown,
): Promise<ActionResult> {
try {
const response = await fetch(`${api}${url}`, {
method,
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data), body: data === undefined ? undefined : JSON.stringify(data),
}) });
const result = await response.json();
const resultData = await result.json(); if (!response.ok) {
if (!result.ok) {
return { return {
success: false, success: false,
errors: resultData.message, // kommt aus NestJS errors: Array.isArray(result.message)
? result.message
: [result.message ?? 'Speichern fehlgeschlagen'],
}; };
} }
revalidatePath(sites.article.url);
return { success: true, data: result };
revalidatePath(sites.article.new.url) } catch {
}
export async function articleUpdate(id: string, data: ArticleUpsert): Promise<ActionResult> {
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 { return {
success: false, success: false,
errors: resultData.message, // kommt aus NestJS errors: [
'Der Artikelserver ist nicht erreichbar. Bitte erneut versuchen.',
],
}; };
} }
revalidatePath(sites.article.update.url + '/' + id);
return { success: true };
} }
export async function articleCreate(
data: ArticleCreate,
): Promise<ActionResult> {
return mutate('/articles', 'POST', data);
}
export async function articleUpdate(
id: string,
data: ArticleUpsert,
): Promise<ActionResult> {
const result = await mutate(`/articles/${id}`, 'PATCH', data);
if (result.success) revalidatePath(`${sites.article.update.url}/${id}`);
return result;
}
export async function articleFindAll(): Promise<Article[]> { export async function articleFindAll(): Promise<Article[]> {
const response = await fetch(`${api}/articles`, { cache: 'no-store' });
const result = await fetch(`http://192.168.50.205/api/articles`, { if (!response.ok) throw new Error('Artikel konnten nicht geladen werden');
method: 'GET', return response.json();
headers: { 'Content-Type': 'application/json' } }
}) export async function articleFindById(id: string): Promise<Article | null> {
const data = await result.json() as Article[]; const response = await fetch(`${api}/articles/${id}`, { cache: 'no-store' });
if (response.status === 404) return null;
return data; if (!response.ok) throw new Error('Artikel konnte nicht geladen werden');
return response.json();
}
export async function articleDelete(
id: string,
revalidateUrl?: string,
): Promise<ActionResult> {
const result = await mutate(`/articles/${id}`, 'DELETE');
if (result.success && revalidateUrl) revalidatePath(revalidateUrl);
return result;
}
export async function articleGroupsFindAll(): Promise<ArticleGroup[]> {
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<ActionResult> {
return mutate('/article-groups', 'POST', { name });
} }
export async function articleFindById(id: string): Promise<any> { export async function articleMigrationStatus(): Promise<{
pendingLegacyArticles: number;
const result = await fetch(`http://192.168.50.205/api/articles/${id}`, { }> {
method: 'GET', const response = await fetch(`${api}/articles/migration-status`, {
headers: { 'Content-Type': 'application/json' } cache: 'no-store',
}) });
const data = await result.json() as Article if (!response.ok)
console.log('getArticle', data) throw new Error('Migrationsstatus konnte nicht geladen werden');
return data; return response.json();
}
export async function articleDelete(id: string,revalidateUrl?:string): Promise<ActionResult> {
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 };
} }
+69 -84
View File
@@ -1,94 +1,79 @@
'use server' 'use server';
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache';
import { sites } from '../_config/sites'; 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<ActionResult> {
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) { export async function stockCreate(data: StockCreate) {
return mutate('/stock', 'POST', data);
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)
} }
export async function stockUpdate(id: string, data: StockUpdate) {
export async function stockUpdate(id: string, data: StockUpdate): Promise<ActionResult> { return mutate(`/stock/${id}`, 'PATCH', data);
}
const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, { export async function stockDelete(id: string) {
method: 'PATCH', return mutate(`/stock/${id}`, 'DELETE');
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 stockFindAll(): Promise<Stock[]> { export async function stockFindAll(): Promise<Stock[]> {
const response = await fetch(`${api}/stock`, { cache: 'no-store' });
const result = await fetch(`http://192.168.50.205/api/stocks`, { if (!response.ok) throw new Error('Lager konnten nicht geladen werden');
method: 'GET', return response.json();
headers: { 'Content-Type': 'application/json' }
})
const data = await result.json() as Stock[];
return data;
} }
export async function stockFindById(id: string) {
export async function stockFindById(id: string): Promise<any> { const response = await fetch(`${api}/stock/${id}`, { cache: 'no-store' });
if (!response.ok) throw new Error('Lager konnte nicht geladen werden');
const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, { return response.json();
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})
const data = await result.json() as Stock
console.log('getArticle', data)
return data;
} }
export async function stockContentFindAll(): Promise<StockContent[]> {
const response = await fetch(`${api}/stock-content`, { cache: 'no-store' });
export async function stockDelete(id: string,revalidateUrl?:string): Promise<ActionResult> { if (!response.ok) throw new Error('Bestände konnten nicht geladen werden');
return response.json();
}
const result = await fetch(`http://192.168.50.205/api/stocks/${id}`, { export async function stockMoveIn(data: StockMovementIn) {
method: 'DELETE', return mutate('/stock-movements/in', 'POST', data);
headers: { 'Content-Type': 'application/json' } }
}) export async function stockMoveOut(data: StockMovementOut) {
return mutate('/stock-movements/out', 'POST', data);
const resultData = await result.json(); }
export async function stockTransfer(data: StockMovementTransfer) {
if (!result.ok) { return mutate('/stock-movements/transfer', 'POST', data);
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
if(revalidateUrl) revalidatePath(revalidateUrl);
return { success: true };
} }
+35 -32
View File
@@ -1,37 +1,40 @@
import Link from "next/link"; import Link from 'next/link';
import { sites } from "../../../../_config/sites"; import { sites } from '../../../../_config/sites';
import { articleFindById } from "../../../../actions/article.actions"; import {
import { ArticleMainForm } from "../../../../components/article/articleMain.form"; articleFindById,
import { categoryFindAll } from "../../../../actions/category.actions"; articleGroupsFindAll,
import { manufacturerFindAll } from "../../../../actions/manufacturer.actions"; } from '../../../../actions/article.actions';
import { ArticleMainForm } from '../../../../components/article/articleMain.form';
interface PageProps { import { categoryFindAll } from '../../../../actions/category.actions';
params: Promise<{ id: string }> import { manufacturerFindAll } from '../../../../actions/manufacturer.actions';
}
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 (<div>
<div>Artikel nicht gefunden</div>
<div>
<Link className="cursor-pointer p-2 border-1 border-sky-500 bg-sky-500 text-white rounded-full m-1 hover:bg-sky-700 " href={sites.article.url}>zurück1</Link>
</div>
</div>)
}
const {name,category,variants} = article;
console.log('Varianten:',article.variants)
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 ( return (
<div className="h-screen"> <div>
<ArticleMainForm initData={article} categories={cats} manufacturer={manufacturer}></ArticleMainForm> {article ? (
<Link className="cursor-pointer p-2 border-1 border-sky-500 bg-sky-500 text-white rounded-full m-1 hover:bg-sky-700 " href={sites.article.url}>zurück</Link> <ArticleMainForm
initData={article}
categories={categories}
manufacturer={manufacturer}
groups={groups}
/>
) : (
<p>Artikel nicht gefunden.</p>
)}
<Link className="text-sky-700 p-6" href={sites.article.url}>
Zurück zu den Artikeln
</Link>
</div> </div>
); );
} }
+23 -24
View File
@@ -1,27 +1,26 @@
import { manufacturerFindAll } from "../../../../actions/manufacturer.actions"; import { manufacturerFindAll } from '../../../../actions/manufacturer.actions';
import { categoryFindAll } from "../../../../actions/category.actions"; import { categoryFindAll } from '../../../../actions/category.actions';
import { ArticleMainForm } from "../../../../components/article/articleMain.form"; import { articleGroupsFindAll } from '../../../../actions/article.actions';
import { articleCreate, articleFindAll } from "../../../../actions/article.actions"; import { ArticleMainForm } from '../../../../components/article/articleMain.form';
import Link from "next/link"; import Link from 'next/link';
import { sites } from "../../../../../../apps/frontend/_config/sites"; import { sites } from '../../../../_config/sites';
//import { sites } from "@/";
interface Props {
}
export default async function ArticlePage({ }: Props) {
const cats = await categoryFindAll();
const manufacturer = await manufacturerFindAll();
const artikel = await articleFindAll();
if(!manufacturer) return <div>Keine Hersteller gefunden</div>
return <>
<ArticleMainForm categories={cats} manufacturer={manufacturer}></ArticleMainForm>
<Link href={`${sites.article.url}`} className="text-sky-300">zurück</Link>
export default async function ArticleNewPage() {
const [categories, manufacturer, groups] = await Promise.all([
categoryFindAll(),
manufacturerFindAll(),
articleGroupsFindAll(),
]);
return (
<>
<ArticleMainForm
categories={categories}
manufacturer={manufacturer}
groups={groups}
/>
<Link className="text-sky-700 p-6" href={sites.article.url}>
Zurück zu den Artikeln
</Link>
</> </>
);
} }
+31 -24
View File
@@ -1,26 +1,33 @@
import { manufacturerFindAll } from "../../../actions/manufacturer.actions"; import {
import { articleFindAll } from "../../../actions/article.actions"; articleFindAll,
import Link from "next/link"; articleMigrationStatus,
import { sites } from "../../../../../apps/frontend/_config/sites"; } from '../../../actions/article.actions';
import { ArticleList } from "../../../components/article/articleList"; import Link from 'next/link';
import { Icon, CirclePlus } from "lucide-react"; 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 <div>Keine Hersteller gefunden</div>
return <div className="p-4 mb-4">
<div className="">
<Link href={`${sites.article.new.url}`} className="text-sky-300 text-black"><CirclePlus color="green" />neu </Link>
</div>
<ArticleList articles={artikel}></ArticleList>
<Link href={`${sites.main.url}`} className="text-sky-300">zurück</Link>
</div>
export default async function ArticlePage() {
const [articles, migration] = await Promise.all([
articleFindAll(),
articleMigrationStatus(),
]);
return (
<main className="p-6">
<h1 className="text-xl mb-4">Artikel</h1>
<Link className="text-sky-700" href={sites.article.new.url}>
Artikel anlegen
</Link>
{migration.pendingLegacyArticles > 0 && (
<p role="status" className="border rounded p-3 my-3">
Es gibt noch {migration.pendingLegacyArticles} bisherige Artikel, die
vor ihrer Nutzung in die neue Artikelstruktur übernommen werden
müssen.
</p>
)}
<ArticleList articles={articles} />
<Link className="text-sky-700" href={sites.main.url}>
Zurück
</Link>
</main>
);
} }
+27 -23
View File
@@ -1,27 +1,31 @@
import Link from "next/link"; import Link from 'next/link';
import { sites } from "../../../../_config/sites"; import { sites } from '../../../../_config/sites';
import { LocationForm } from "../../../../components/location/location.form"; import { articleFindAll } from '../../../../actions/article.actions';
import { articleFindAll } from "../../../../actions/article.actions"; import { locationTree } from '../../../../actions/location.actions';
import { locationFindAll, locationTree } from "../../../../actions/location.actions"; import {
import { StockForm } from "../../../../components/stock/stock.form"; stockContentFindAll,
import { categoryFindAll } from "../../../../actions/category.actions"; 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();
export default async function StockMovementPage() {
const [article, orte, stocks, contents] = await Promise.all([
articleFindAll(),
locationTree(),
stockFindAll(),
stockContentFindAll(),
]);
return ( return (
<div className="h-screen flex flex-col gap-4"> <main>
<div> <StockForm
{sites.location.new.name} article={article}
<StockForm article={artikel} orte={orte} categories={kategorien}></StockForm> orte={orte}
</div> stocks={stocks}
contents={contents}
<Link href={sites.location.url}>zurück zu {sites.location.name}</Link> />
</div> <Link className="text-sky-700 p-6" href={sites.main.url}>
Zurück
</Link>
</main>
); );
} }
@@ -1,26 +1,131 @@
"use client"; 'use client';
import { ArticleCreate, ArticleUpsert, Category } from "../../types/catalog" import {
import { useFormContext } from "react-hook-form" ArticleCreate,
import { InputTextR } from "../ui/inputTextR"; ArticleGroup,
import ComboBoxR from "../ui/ComboBoxR"; Category,
Manufacturer,
} from '../../types/catalog';
import { useFormContext } from 'react-hook-form';
import { InputTextR } from '../ui/inputTextR';
interface Props {
interface Params { categories: Category[];
categories: Category[] manufacturer: Manufacturer[];
groups: ArticleGroup[];
} }
export const ArticleBaseForm = ({
export const ArticleBaseForm = ({ categories }: Params) => { categories,
manufacturer,
const { register, control } = useFormContext<ArticleUpsert>(); groups,
}: Props) => {
const values = categories.map((i) => ({ id: i._id, value: i.name })) const {
register,
watch,
setValue,
formState: { errors },
} = useFormContext<ArticleCreate>();
const trackingMode = watch('trackingMode');
return ( return (
<> <div className="grid gap-3 md:grid-cols-2">
<InputTextR label="Artikename" {...register("name", { required: "Pflichtfeld" })} /> <InputTextR
<ComboBoxR name="categoryId" control={control} options={values} placeholder="wählen..." /> label="Artikelnummer"
</> {...register('articleNumber', {
required: 'Artikelnummer erforderlich',
})}
) />
} <InputTextR
label="Artikelname"
{...register('name', { required: 'Name erforderlich' })}
/>
<InputTextR label="Beschreibung" {...register('description')} />
<label>
Kategorie
<select
className="block w-full border rounded p-1"
{...register('categoryId')}
>
<option value="">Keine Kategorie</option>
{categories.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Produktgruppe
<select
className="block w-full border rounded p-1"
{...register('groupId')}
>
<option value="">Keine Gruppe</option>
{groups.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Hersteller
<select
className="block w-full border rounded p-1"
{...register('manufacturerId')}
>
<option value="">Unbekannt / kein Hersteller</option>
{manufacturer.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<InputTextR
label="Herstellerartikelnummer"
{...register('manufacturerArticleNumber')}
/>
<InputTextR label="Barcode" {...register('barcode')} />
<InputTextR
label="Basiseinheit (z. B. Stück, kg, Liter)"
{...register('baseUnit', { required: 'Einheit erforderlich' })}
/>
<label>
Bestandsführung
<select
className="block w-full border rounded p-1"
{...register('trackingMode', {
onChange: (event) => {
if (event.target.value !== 'batch')
setValue('tracksExpiryDate', false);
if (event.target.value === 'individual')
setValue('baseUnit', 'Stück');
},
})}
>
<option value="quantity">Menge</option>
<option value="batch">Charge</option>
<option value="individual">Einzelstücke</option>
</select>
</label>
<label className="flex items-center gap-2">
<input type="checkbox" {...register('isConsumable')} />
Verbrauchsartikel
</label>
<label className="flex items-center gap-2">
<input
type="checkbox"
disabled={trackingMode !== 'batch'}
{...register('tracksExpiryDate')}
/>
Ablaufdatum je Charge erfassen
</label>
<p className="text-sm text-red-700 md:col-span-2" role="alert">
{Object.values(errors)
.map((error) => error?.message)
.filter(Boolean)
.join(' · ')}
</p>
</div>
);
};
@@ -1,57 +1,86 @@
"use client"; 'use client';
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation';
import { Article } from "../../types/catalog" import { useState } from 'react';
import { Article } from '../../types/catalog';
import { articleDelete } from "../../actions/article.actions"; import { articleDelete } from '../../actions/article.actions';
import { sites } from "../../_config/sites"; import { sites } from '../../_config/sites';
import Link from "next/link"; 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();
}
export const ArticleList = ({ articles }: { articles: Article[] }) => {
const router = useRouter();
const [error, setError] = useState('');
const [pendingId, setPendingId] = useState<string | null>(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 ( return (
<div className='p-4 '> <div className="overflow-auto">
{articles.map((a) => ( {error && (
<div key={a._id} className="flex gap-4 border-b-1 p-4 border-gray-200"> <p role="alert" className="text-red-700">
<div className='flex gap-4 wa'> {error}
<div className='w-32'> </p>
{a.name} )}
</div> <table className="w-full text-left">
<div className='w-8'> <thead>
<Link href={`${sites.article.update.url}/${a._id}`}> <tr>
<Eye className=''></Eye> <th>Nummer</th>
<th>Artikel</th>
<th>Hersteller</th>
<th>Einheit</th>
<th>Bestandsführung</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
{articles.map((article) => (
<tr key={article._id} className="border-b">
<td className="p-2">{article.articleNumber}</td>
<td className="p-2">
{article.name}
{article.group && (
<span className="block text-sm text-gray-500">
{article.group.name}
</span>
)}
</td>
<td className="p-2">{article.manufacturer?.name ?? '–'}</td>
<td className="p-2">{article.baseUnit}</td>
<td className="p-2">
{
{
quantity: 'Menge',
batch: 'Charge',
individual: 'Einzelstücke',
}[article.trackingMode]
}
</td>
<td className="p-2">
<Link
className="text-sky-700 mr-3"
href={`${sites.article.update.url}/${article._id}`}
>
Bearbeiten
</Link> </Link>
<button
disabled={pendingId !== null}
</div> onClick={() => archive(article._id)}
<div className='w-8 '> >
<button className='flex gap-2' onClick={() => handlerOnDelete(a._id)}> {pendingId === article._id ? 'Archiviert …' : 'Archivieren'}
<OctagonX className='' enableBackground={'green'} color='red'></OctagonX>
</button> </button>
</td>
</tr>
))}
</tbody>
</table>
{articles.length === 0 && (
<p className="py-4">Noch keine Artikel vorhanden.</p>
)}
</div> </div>
</div> );
</div>))} };
</div>
)
}
@@ -1,106 +1,329 @@
"use client"; 'use client';
import { emptyArticleDto, Article, ArticleCreate, Category, Manufacturer, ArticleUpsert } from "../../types/catalog" import {
import { FormProvider, useForm } from "react-hook-form" Article,
import { ArticleBaseForm } from "./articleBase.form"; ArticleAttributes,
import { ArticleVariantForm } from "./articleVariants.form"; ArticleCreate,
import { articleCreate, articleUpdate } from "../../actions/article.actions"; ArticleGroup,
import { useEffect, useState } from "react"; Category,
import Modal from "../ui/modal"; Manufacturer,
import { ManufactuererForm } from "../manufacturer/manufacturer.form"; 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 Props {
interface Params { categories: Category[];
categories: Category[] manufacturer: Manufacturer[];
manufacturer: Manufacturer[] groups: ArticleGroup[];
initData?: ArticleUpsert initData?: Article;
debug?: boolean
} }
function formValues(article?: Article): ArticleCreate {
if (!article) return emptyArticleDto;
export const ArticleMainForm = ({ categories, manufacturer, initData, debug }: Params) => { return {
articleNumber: article.articleNumber,
const methods = useForm<ArticleUpsert>({ defaultValues: emptyArticleDto }); name: article.name,
const [errMsg, setErrorMsg] = useState<string[]>([]) description: article.description ?? '',
const [error, setError] = useState(false) categoryId: article.categoryId ?? '',
const [creatManufacturer, setCreatManufacturer] = useState(-1); manufacturerId: article.manufacturerId ?? '',
const [hersteller,setHersteller] = useState<Manufacturer[]>([]) 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<ArticleCreate>({
defaultValues: formValues(initData),
});
const router = useRouter();
const [errors, setErrors] = useState<string[]>([]);
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(() => { useEffect(() => {
setHersteller(manufacturer); methods.reset(formValues(initData));
if (initData && initData._id) { setProperties(
Object.entries(initData?.attributes ?? {}).map(([key, value]) => ({
methods.reset(initData); key,
} value: String(value),
}, [initData]) type: typeof value as 'string' | 'number' | 'boolean',
})),
const handlerCreatManufacturer = (data: Manufacturer) => {
console.log('Create')
setHersteller((cur)=>([...cur,data]));
methods.setValue(
`variants.${creatManufacturer}.manufacturerId`,
data._id,
{ shouldDirty: true, shouldValidate: true }
); );
setCreatManufacturer(-1) }, [initData, methods]);
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;
}
attributes[key] = Number(property.value);
} else
attributes[key] =
property.type === 'boolean'
? property.value === 'true'
: property.value;
}
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();
}
};
const onSubmit = async (data: ArticleUpsert) => { const addGroup = async () => {
if (initData?._id) { if (!groupName.trim()) return;
setGroupSaving(true);
const result = await articleUpdate(initData._id, data) try {
const result = await articleGroupCreate(groupName.trim());
if (!result.success) { if (!result.success) {
setError(true) setErrors(result.errors);
setErrorMsg(() => result.errors) return;
console.log(result)
} else {
setError(false)
} }
} else { const group = result.data as ArticleGroup;
console.log('create') setProductGroups((current) => [...current, group]);
methods.setValue('groupId', group._id);
const { name, categoryId, variants, attributes } = data; setGroupOpen(false);
if (categoryId) { setGroupName('');
const create = { } finally {
name, setGroupSaving(false);
categoryId,
variants,
attributes
} }
articleCreate(create);
}
}
}; };
return ( return (
<div className="me-30 flex flex-col p-4 pt-10 ps-10" > <div className="max-w-4xl p-6">
<h1 className="text-xl mb-4">
{initData ? 'Artikel bearbeiten' : 'Artikel anlegen'}
</h1>
<FormProvider {...methods}> <FormProvider {...methods}>
{initData?._id && <div>{initData._id}</div>}
<form onSubmit={methods.handleSubmit(onSubmit)}> <form onSubmit={methods.handleSubmit(onSubmit)}>
<ArticleBaseForm categories={categories}></ArticleBaseForm> <ArticleBaseForm
<ArticleVariantForm manufacturer={hersteller} onOpenManufacturer={(index) => setCreatManufacturer(index)}></ArticleVariantForm> categories={categories}
manufacturer={manufacturers}
<div>{methods.watch("name")}</div> groups={productGroups}
<pre>{JSON.stringify(methods.watch(), null, 2)}</pre> />
<button type="submit">Absenden</button> <div className="flex gap-3 mt-3">
</form> <button
type="button"
</FormProvider> className="border rounded px-3 py-1"
<Modal open={creatManufacturer >= 0} onClose={() => setCreatManufacturer(-1)}> onClick={() => setManufacturerOpen(true)}
<ManufactuererForm onChangeData={(d) => handlerCreatManufacturer(d)}></ManufactuererForm> >
<button onClick={() => setCreatManufacturer(-1)}>Abbruch</button> Hersteller anlegen
</Modal> </button>
{error && <div className="border-1 border-red-400 bg-red-200"> <button
Error type="button"
{errMsg.map((msg, id) => (<div key={id}>{msg}</div>))} className="border rounded px-3 py-1"
</div>} onClick={() => setGroupOpen(true)}
>
Produktgruppe anlegen
</button>
</div> </div>
<fieldset className="border rounded p-3 mt-4">
<legend>Eigenschaften (optional)</legend>
{properties.map((property, index) => (
<div key={index} className="grid gap-2 md:grid-cols-4 mb-2">
<InputTextR
label="Eigenschaft"
value={property.key}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? { ...item, key: event.target.value }
: item,
),
) )
} }
/>
<label>
Typ
<select
className="block border rounded p-1"
value={property.type}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? {
...item,
type: event.target
.value as typeof property.type,
value:
event.target.value === 'boolean'
? 'false'
: '',
}
: item,
),
)
}
>
<option value="string">Text</option>
<option value="number">Zahl</option>
<option value="boolean">Ja / Nein</option>
</select>
</label>
{property.type === 'boolean' ? (
<label>
Wert
<select
className="block border rounded p-1"
value={property.value}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? { ...item, value: event.target.value }
: item,
),
)
}
>
<option value="true">Ja</option>
<option value="false">Nein</option>
</select>
</label>
) : (
<InputTextR
label="Wert"
type={property.type === 'number' ? 'number' : 'text'}
step="any"
value={property.value}
onChange={(event) =>
setProperties((current) =>
current.map((item, i) =>
i === index
? { ...item, value: event.target.value }
: item,
),
)
}
/>
)}
<button
type="button"
onClick={() =>
setProperties((current) =>
current.filter((_, i) => i !== index),
)
}
>
Entfernen
</button>
</div>
))}
<button
type="button"
className="border rounded px-3 py-1"
onClick={() =>
setProperties((current) => [
...current,
{ key: '', type: 'string', value: '' },
])
}
>
Eigenschaft hinzufügen
</button>
</fieldset>
<ArticlePackagingForm />
<button
className="bg-sky-700 text-white rounded px-4 py-2 mt-4"
type="submit"
disabled={
methods.formState.isSubmitting || Boolean(initData?.archivedAt)
}
>
{methods.formState.isSubmitting ? 'Speichert …' : 'Speichern'}
</button>
</form>
</FormProvider>
{errors.length > 0 && (
<ul role="alert" className="text-red-700 mt-3">
{errors.map((error, index) => (
<li key={index}>{error}</li>
))}
</ul>
)}
<Modal open={manufacturerOpen} onClose={() => setManufacturerOpen(false)}>
<ManufactuererForm
onChangeData={(item) => {
setManufacturers((current) => [...current, item]);
methods.setValue('manufacturerId', item._id);
setManufacturerOpen(false);
}}
/>
</Modal>
<Modal open={groupOpen} onClose={() => setGroupOpen(false)}>
<InputTextR
label="Gruppenname"
value={groupName}
onChange={(event) => setGroupName(event.target.value)}
/>
<button
type="button"
disabled={groupSaving || !groupName.trim()}
onClick={addGroup}
>
Gruppe speichern
</button>
</Modal>
</div>
);
};
@@ -1,85 +1,65 @@
"use client"; 'use client';
import { ArticleCreate, ArticleUpsert, Manufacturer } from "../../types/catalog" import { ArticleCreate } from '../../types/catalog';
import { useFieldArray, useFormContext } from "react-hook-form" import { useFieldArray, useFormContext } from 'react-hook-form';
import { InputTextR } from "../ui/inputTextR"; 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<ArticleUpsert>();
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 }))
export const ArticlePackagingForm = () => {
const {
control,
register,
watch,
formState: { errors },
} = useFormContext<ArticleCreate>();
const { fields, append, remove } = useFieldArray({
control,
name: 'packaging',
});
return ( return (
<div className="mt-4 border-1 rounded border-gray-200 p-2"> <fieldset className="border rounded p-3 mt-4">
<legend>Verpackungen (optional)</legend>
<div> <p className="text-sm mb-2">
<button type="button" onClick={() => append({ manufacturerId: "", packagingUnit: "1" })} className="bg-sky-400 rounded-md p-1 mt-2 mb-2 ps-2 pe-2"> Der Bestand wird in {watch('baseUnit') || 'der Basiseinheit'} geführt.
+ Neue Variante Hier hinterlegst du den Inhalt einer Verpackung.
</button> </p>
</div>
<div className="flex flex-col gap-2 mb-2">
<div className="grid grid-cols-12 gap-4 ">
<div className="col-span-4" >
Hersteller
</div>
<div className="col-span-3" >
Packungseinheit
</div>
<div className="col-span-3" >
Aktion
</div>
</div>
<div className="border-1"></div>
{fields.map((field, index) => ( {fields.map((field, index) => (
<div key={field.id} className="grid grid-cols-12 gap-4 "> <div key={field.id} className="grid gap-2 md:grid-cols-4 mb-3">
<div className="col-span-4" > <InputTextR
<ComboBoxRHF name={`variants.${index}.manufacturerId`} control={control} options={hersteller} placeholder="wählen..." /> label="Bezeichnung"
{...register(`packaging.${index}.name`, { required: true })}
<button onClick={() => onOpenManufacturer(index)}>+</button> />
</div> <InputTextR
<div className="col-span-3" > label="Inhalt in Basiseinheiten"
<InputTextR {...register(`variants.${index}.packagingUnit`)} /> type="number"
</div> step="any"
<div className="col-span-3" > min="0.000001"
<button type="button" onClick={() => handleRemove(index)} className={`bg-gray-200 rounded-md ps-2 pe-2 `}> {...register(`packaging.${index}.quantityInBaseUnits`, {
löschen valueAsNumber: true,
required: true,
min: Number.MIN_VALUE,
})}
/>
<InputTextR
label="Barcode"
{...register(`packaging.${index}.barcode`)}
/>
<button type="button" onClick={() => remove(index)}>
Verpackung entfernen
</button> </button>
</div> </div>
</div>
))} ))}
</div> {errors.packaging && (
<p role="alert" className="text-red-700">
</div> Jede Verpackung benötigt eine Bezeichnung und einen positiven Inhalt.
</p>
)}
) <button
} type="button"
className="border rounded px-3 py-1"
onClick={() => append({ name: '', quantityInBaseUnits: 1 })}
>
Verpackung hinzufügen
</button>
</fieldset>
);
};
+421 -93
View File
@@ -1,109 +1,437 @@
"use client"; 'use client';
import { emptyArticleDto, Article, ArticleCreate, Category, Manufacturer, ArticleVariant } from "../../types/catalog" import { Article } from '../../types/catalog';
import { FormProvider, useForm } from "react-hook-form" import { useForm } from 'react-hook-form';
import { articleCreate, articleUpdate } from "../../actions/article.actions"; import { useRouter } from 'next/navigation';
import { useEffect, useState } from "react"; import { useState } from 'react';
import Modal from "../ui/modal"; import { Stock } from '../../types/inventory/stock.types';
import { ManufactuererForm } from "../manufacturer/manufacturer.form"; import { StockContent } from '../../types/inventory/stockContent.types';
import { Location, LocationTreeNode } from "../../types/inventory"; import { StockMovementIn } from '../../types/inventory/stockMovement.types';
import { emptyStock, Stock, StockCreate } from "../../types/inventory/stockContent.types"; import { LocationTreeNode } from '../../types/inventory';
import { stockCreate, stockUpdate } from "../../actions/stock.actions"; import {
import { InputTextR } from "../ui/inputTextR"; stockCreate,
import { LocationView } from "../location/location.view"; stockMoveIn,
import { LocationTreeView } from "../location/location.treeView"; stockMoveOut,
stockTransfer,
} from '../../actions/stock.actions';
import { InputTextR } from '../ui/inputTextR';
import { LocationTreeView } from '../location/location.treeView';
import Modal from '../ui/modal';
interface Props {
interface Params { article: Article[];
categories: Category[] stocks: Stock[];
article: Article[], contents: StockContent[];
orte: LocationTreeNode[] orte: LocationTreeNode[];
initData?: Stock
debug?: boolean
} }
export const StockForm = ({ article, stocks, contents, orte }: Props) => {
const router = useRouter();
const {
register,
watch,
reset,
setValue,
handleSubmit,
formState: { isSubmitting, errors: formErrors },
} = useForm<StockMovementIn>({
shouldUnregister: true,
defaultValues: { articleId: '', stockId: '', quantity: 1 },
});
const selectedArticle = article.find(
(item) => item._id === watch('articleId'),
);
const [errors, setErrors] = useState<string[]>([]);
const [notice, setNotice] = useState('');
const [stockOpen, setStockOpen] = useState(false);
const [stockName, setStockName] = useState('');
const [location, setLocation] = useState<LocationTreeNode | null>(null);
const [busy, setBusy] = useState(false);
const [selectedContent, setSelectedContent] = useState<StockContent | null>(
null,
);
const [operation, setOperation] = useState<'out' | 'transfer'>('out');
const [quantity, setQuantity] = useState(1);
const [targetStock, setTargetStock] = useState('');
const [targetArea, setTargetArea] = useState('');
const feedback = (result: ActionResult) => {
export const StockForm = ({ article, categories, initData, orte, debug }: Params) => {
const { register, reset, formState: { errors }, handleSubmit } = useForm<StockCreate>({ defaultValues: emptyStock });
const [errMsg, setErrorMsg] = useState<string[]>([])
const [selectetCategory, setSelectedCategory] = useState<Category>()
const [selectetArticle, setSelectedArticle] = useState<Article>()
const [selectetArticleVariant, setSelectedArticleVariant] = useState<ArticleVariant>()
const [selectetOrt, setSelectedOrt] = useState<Location>()
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) { if (!result.success) {
setError(true) setErrors(result.errors);
setErrorMsg(() => result.errors) return false;
console.log(result)
} else {
setError(false)
} }
} else { setErrors([]);
console.log('create') setNotice('Gespeichert.');
router.refresh();
const { articleVariantId, locationId, quantity, expiryDate, batchNumber } = data; return true;
if (true) { };
const create = { const onSubmit = async (data: StockMovementIn) => {
articleVariantId, setNotice('');
locationId, const payload: StockMovementIn = {
quantity, articleId: data.articleId,
expiryDate, stockId: data.stockId,
batchNumber quantity: data.quantity,
area: data.area || undefined,
};
if (selectedArticle?.trackingMode === 'batch') {
payload.batchNumber = data.batchNumber;
if (selectedArticle.tracksExpiryDate && data.expiryDate)
payload.expiryDate = data.expiryDate;
} }
stockCreate(create); 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);
} }
}; };
const handleLocationSelect = (ort: LocationTreeNode) => {
setSelectedOrt(ort);
}
return ( return (
<div className="me-30 flex flex-col p-4 pt-10 ps-10" > <div className="max-w-5xl p-6">
<h1 className="text-xl mb-4">Lager und Bestände</h1>
{initData?.id && <div>{initData.id}</div>} <button
<form onSubmit={handleSubmit(onSubmit)}> className="border rounded px-3 py-1 mb-4"
type="button"
onClick={() => setStockOpen(true)}
>
Lager anlegen
</button>
<form
onSubmit={handleSubmit(onSubmit)}
className="grid gap-3 md:grid-cols-2"
>
<label>
Artikel
<select
className="block w-full border rounded p-1"
{...register('articleId', {
required: 'Artikel auswählen',
onChange: (event) => {
if (
article.find((item) => item._id === event.target.value)
?.trackingMode === 'individual'
)
setValue('quantity', 1);
},
})}
>
<option value="">Artikel auswählen</option>
{article.map((item) => (
<option key={item._id} value={item._id}>
{item.articleNumber} – {item.name}
</option>
))}
</select>
</label>
<label>
Lager
<select
className="block w-full border rounded p-1"
{...register('stockId', {
required: 'Lager auswählen',
onChange: () => setValue('area', ''),
})}
>
<option value="">Lager auswählen</option>
{stocks.map((item) => (
<option key={item._id} value={item._id}>
{item.name}
</option>
))}
</select>
</label>
<InputTextR
label={`Menge (${selectedArticle?.baseUnit ?? 'Basiseinheit'})`}
type="number"
step={selectedArticle?.trackingMode === 'individual' ? '1' : 'any'}
{...register('quantity', {
valueAsNumber: true,
required: true,
min: Number.MIN_VALUE,
validate: (value) =>
selectedArticle?.trackingMode !== 'individual' ||
value === 1 ||
'Einzelstücke benötigen Menge 1',
})}
/>
<label>
Lagerbereich
<select
className="block w-full border rounded p-1"
{...register('area')}
>
<option value="">Kein Bereich</option>
{stocks
.find((item) => item._id === watch('stockId'))
?.areas?.map((area) => (
<option key={area} value={area}>
{area}
</option>
))}
</select>
</label>
{selectedArticle?.trackingMode === 'batch' && (
<>
<InputTextR
label="Chargennummer"
{...register('batchNumber', {
validate: (value) =>
selectedArticle?.trackingMode !== 'batch' ||
Boolean(value?.trim()) ||
'Chargennummer erforderlich',
})}
/>
{selectedArticle.tracksExpiryDate && (
<InputTextR
label="Mindesthaltbar / Ablaufdatum"
type="date"
{...register('expiryDate')}
/>
)}
</>
)}
{selectedArticle?.trackingMode === 'individual' && (
<>
<InputTextR
label="Inventarnummer"
{...register('inventoryNumber', {
validate: (value) =>
selectedArticle?.trackingMode !== 'individual' ||
Boolean(value?.trim()) ||
'Inventarnummer erforderlich',
})}
/>
<InputTextR label="Seriennummer" {...register('serialNumber')} />
<InputTextR label="Zustand" {...register('condition')} />
<InputTextR label="Verwendung" {...register('purpose')} />
<InputTextR
label="Anschaffungsdatum"
type="date"
{...register('acquiredAt')}
/>
</>
)}
<p role="alert" className="text-red-700 md:col-span-2">
{Object.values(formErrors)
.map((error) => error.message)
.filter(Boolean)
.join(' · ')}
</p>
<button
className="bg-sky-700 text-white rounded p-2"
type="submit"
disabled={isSubmitting || stocks.length === 0 || article.length === 0}
>
{isSubmitting ? 'Bucht …' : 'Einlagern'}
</button>
</form>
{errors.length > 0 && (
<ul role="alert" className="text-red-700 mt-3">
{errors.map((error, index) => (
<li key={index}>{error}</li>
))}
</ul>
)}
{notice && (
<p role="status" className="mt-3">
{notice}
</p>
)}
<h2 className="text-lg mt-6 mb-3">Bestände</h2>
<div className="overflow-auto">
<table className="w-full text-left">
<thead>
<tr>
<th>Artikel</th>
<th>Lager</th>
<th>Menge</th>
<th>Charge / Exemplar</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
{contents.map((content) => (
<tr key={content._id} className="border-b">
<td className="p-2">
{content.articleId?.name ?? 'Artikel fehlt'}
</td>
<td className="p-2">
{content.stockId?.name ?? 'Lager fehlt'} {content.area}
</td>
<td className="p-2">
{content.quantity} {content.articleId?.baseUnit}
</td>
<td className="p-2">
{content.batchId?.batchNumber ??
content.assetId?.inventoryNumber ??
'–'}
{content.batchId?.expiryDate && (
<span className="block text-sm">
{new Date(content.batchId.expiryDate).toLocaleDateString(
'de-DE',
{ timeZone: 'UTC' },
)}
</span>
)}
</td>
<td className="p-2">
{(['out', 'transfer'] as const).map((action) => (
<button
key={action}
type="button"
className="text-sky-700 mr-3"
onClick={() => {
setSelectedContent(content);
setOperation(action);
setQuantity(content.assetId ? 1 : content.quantity);
setTargetStock('');
setTargetArea('');
}}
>
{action === 'out' ? 'Entnehmen' : 'Umlagern'}
</button>
))}
</td>
</tr>
))}
</tbody>
</table>
</div>
{contents.length === 0 && <p>Keine Bestände vorhanden.</p>}
<Modal open={stockOpen} onClose={() => setStockOpen(false)}>
<InputTextR
label="Lagername"
value={stockName}
onChange={(event) => setStockName(event.target.value)}
/>
<p>Lagerort auswählen: {location?.name}</p>
<LocationTreeView data={orte} onSelect={setLocation} />
<button
type="button"
disabled={busy || !location || !stockName.trim()}
onClick={addStock}
>
Lager speichern
</button>
</Modal>
<Modal
open={selectedContent !== null}
onClose={() => setSelectedContent(null)}
>
<h2>
{operation === 'out' ? 'Entnehmen' : 'Umlagern'}:{' '}
{selectedContent?.articleId?.name}
</h2>
<InputTextR <InputTextR
label="Menge" label="Menge"
{...register("quantity", { required: "Pflichtfeld" })} type="number"
error={errors.quantity?.message} step="any"
value={quantity}
onChange={(event) => setQuantity(Number(event.target.value))}
/> />
{operation === 'transfer' && (
<button type="submit">Absenden</button> <>
</form> <label>
<LocationTreeView data={orte} onSelect={(item) => handleLocationSelect(item)}></LocationTreeView> Ziellager
<select
{error && <div className="border-1 border-red-400 bg-red-200"> className="block border rounded p-1"
Error value={targetStock}
{errMsg.map((msg, id) => (<div key={id}>{msg}</div>))} onChange={(event) => {
</div>} setTargetStock(event.target.value);
{selectetOrt && <div>{selectetOrt.name}</div>} setTargetArea('');
}}
>
<option value="">Auswählen</option>
{stocks.map((stock) => (
<option key={stock._id} value={stock._id}>
{stock.name}
</option>
))}
</select>
</label>
<label>
Zielbereich
<select
className="block border rounded p-1"
value={targetArea}
onChange={(event) => setTargetArea(event.target.value)}
>
<option value="">Kein Bereich</option>
{stocks
.find((stock) => stock._id === targetStock)
?.areas?.map((area) => (
<option key={area} value={area}>
{area}
</option>
))}
</select>
</label>
</>
)}
<button
type="button"
disabled={
busy ||
!Number.isFinite(quantity) ||
quantity <= 0 ||
quantity > (selectedContent?.quantity ?? 0) ||
Boolean(selectedContent?.assetId && quantity !== 1) ||
(operation === 'transfer' && !targetStock)
}
onClick={book}
>
Buchen
</button>
</Modal>
</div> </div>
);
};
)
}
+47 -84
View File
@@ -1,93 +1,56 @@
import { Category } from "./category.types"; import { Category } from './category.types';
import {Manufacturer,emptyManufacturer} from "./manufacturer.types" import { Manufacturer } from './manufacturer.types';
export interface Article { export type TrackingMode = 'quantity' | 'batch' | 'individual';
_id: string, export type ArticleAttributes = Record<string, string | number | boolean>;
name: string, export interface ArticleGroup {
category: Category; _id: string;
attributes?: Record<string, any>; name: string;
variants: Variant[], description?: string;
}
export interface ArticlePackaging {
name: string;
quantityInBaseUnits: number;
barcode?: string;
} }
export interface ArticleCreate { export interface ArticleCreate {
articleNumber: string;
name: string; name: string;
categoryId: string; description?: string;
attributes?: Record<string, any>; categoryId?: string | null;
variants: Variant[], groupId?: string | null;
manufacturerId?: string | null;
manufacturerArticleNumber?: string;
barcode?: string;
baseUnit: string;
isConsumable: boolean;
trackingMode: TrackingMode;
tracksExpiryDate: boolean;
attributes?: ArticleAttributes;
packaging?: ArticlePackaging[];
} }
export type ArticleUpsert = ArticleCreate;
export interface Article extends ArticleCreate {
//--- Artikel Variante
export interface ArticleVariant {
_id: string; _id: string;
article: Article; category?: Category;
manufacturer: Manufacturer; manufacturer?: Manufacturer;
supplierArticleNumber?: string; group?: ArticleGroup;
packagingUnit?: string; archivedAt?: string | null;
extra?: Record<string, any>;
} }
export const emptyArticleDto: ArticleCreate = {
export interface ArticleVariantCreate { articleNumber: '',
articleId: string;
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}
export interface Variant {
_id?: string;
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}
export interface VariantCreate {
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
}
export const emptyArticle = {
name: '', name: '',
} description: '',
categoryId: null,
groupId: null,
manufacturerId: null,
export const emptyArticleVariant = { manufacturerArticleNumber: '',
article: emptyArticle, barcode: '',
manufacturer: emptyManufacturer baseUnit: 'Stück',
} isConsumable: false,
trackingMode: 'quantity',
tracksExpiryDate: false,
export const emptyArticleDto:ArticleCreate = { attributes: {},
name:'', packaging: [],
categoryId:'', };
variants:[]
}
//Upsert
export interface ArticleUpsert {
_id:string,
name: string;
categoryId?: string;
attributes?: Record<string, any>;
variants: VariantUpsert[],
}
export interface VariantUpsert {
_id?:string
manufacturerId: string;
supplierArticleNumber?: string;
packagingUnit?: string;
extra?: Record<string, any>;
deleted?:boolean;
}
+5 -9
View File
@@ -1,20 +1,16 @@
import { Location } from "./location.types";
export interface StockCreate { export interface StockCreate {
name: string; name: string;
locationId: string; locationId: string;
areas?:string[] areas?: string[];
} }
export interface StockUpdate { export interface StockUpdate {
name?: string; name?: string;
locationId?: string; locationId?: string;
areas?:string[] areas?: string[];
} }
export interface Stock { export interface Stock {
id: string _id: string;
name: string; name: string;
location: Location; locationId: string;
areas?:string[] areas?: string[];
} }
@@ -1,36 +1,25 @@
import { Article } from '../catalog';
import { Stock } from './stock.types';
export interface Batch {
export interface Stock { _id: string;
id: string batchNumber: string;
articleVariantId: string expiryDate?: string;
locationId: string
quantity: number
expiryDate?: Date
batchNumber: string
} }
export interface Asset {
_id: string;
export interface StockCreate { inventoryNumber: string;
articleVariantId: string serialNumber?: string;
locationId: string condition?: string;
quantity: number purpose?: string;
expiryDate?: Date acquiredAt?: string;
batchNumber: string
} }
export interface StockContent {
export interface StockUpdate { _id: string;
articleVariantId?: string articleId: Article;
locationId?: string stockId: Stock;
quantity?: number quantity: number;
expiryDate?: Date area: string;
batchNumber?: string batchId?: Batch | null;
} assetId?: Asset | null;
export const emptyStock:StockCreate = {
articleVariantId: '',
locationId: '',
quantity: 0,
expiryDate: new Date(),
batchNumber: '1'
} }
@@ -1,28 +1,21 @@
export interface StockMovementIn { export interface StockMovementIn {
stockId: string; stockId: string;
articleVariantId: string; articleId: string;
quantity: number; quantity: number;
batchNumber?: string; batchNumber?: string;
expiryDate?: Date; expiryDate?: string;
area?: string; area?: string;
inventoryNumber?: string;
serialNumber?: string;
condition?: string;
purpose?: string;
acquiredAt?: string;
} }
export interface StockMovementOut { export interface StockMovementOut {
stockContentId: string; stockContentId: string;
quantity: number; quantity: number;
} }
export interface StockMovementTransfer extends StockMovementOut {
export interface StockMovementTransfer {
articleVariantId: string;
fromStockId: string;
toStockId: string; toStockId: string;
toArea?: string; toArea?: string;
quantity: number;
batchNumber?: string;
} }
+134
View File
@@ -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.