Artikel DB struktur geändert von CODEX
This commit is contained in:
1 parent
0c0a678eaa
commit
9c18234efe
95 files changed
+3872
-2316
No files matched your search
@@ -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
|
||||
@@ -18,7 +18,8 @@
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||
"articles:migration": "ts-node --project tsconfig.scripts.json scripts/migrate-articles.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.1",
|
||||
|
||||
@@ -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": {}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
@@ -6,19 +6,21 @@ import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { LocationsModule } from './locations/locations.module';
|
||||
|
||||
import { UsersModule } from './users/users.module';
|
||||
import { CatalogModule } from './catalog/catalog.module';
|
||||
import { ProductsModule } from './products/products.module';
|
||||
import { InventoryModule } from './inventory/inventory.module';
|
||||
import { ChatGateway } from './chat.gateway';
|
||||
|
||||
@Module({
|
||||
imports: [MongooseModule.forRoot('mongodb://192.168.50.206/nest'),
|
||||
CatalogModule,
|
||||
imports: [
|
||||
MongooseModule.forRoot(
|
||||
process.env.MONGODB_URI ?? 'mongodb://192.168.50.206/nest',
|
||||
),
|
||||
ProductsModule,
|
||||
InventoryModule,
|
||||
UsersModule,
|
||||
LocationsModule,
|
||||
LocationsModule,
|
||||
],
|
||||
//controllers: [AppController],
|
||||
providers: [ChatGateway,LocationsModule],
|
||||
providers: [ChatGateway, LocationsModule],
|
||||
})
|
||||
export class AppModule { }
|
||||
|
||||
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 { }
|
||||
@@ -13,7 +13,7 @@ import { Server } from 'socket.io';
|
||||
})
|
||||
export class ChatGateway {
|
||||
@WebSocketServer()
|
||||
server: Server; // 👈 DAS fehlt dir gerade
|
||||
server!: Server; // 👈 DAS fehlt dir gerade
|
||||
|
||||
@SubscribeMessage('message')
|
||||
handleMessage(@MessageBody() data: string) {
|
||||
|
||||
@@ -1,62 +1,62 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DrawContainer } from 'src/graphics/lib/draw';
|
||||
import { DrawEllipse } from 'src/graphics/lib/drawEllipse';
|
||||
import { DrawGroup } from 'src/graphics/lib/drawGroup';
|
||||
import { DrawPath, PathCommand } from 'src/graphics/lib/drawPath';
|
||||
|
||||
@Injectable()
|
||||
export class DrawService {
|
||||
constructor() { }
|
||||
|
||||
async ellypse() {
|
||||
|
||||
const raster = 4;
|
||||
const scale = 2.0;
|
||||
const x0 = 0;
|
||||
const y0 = 0;
|
||||
|
||||
const l1 = 40 * raster * scale
|
||||
const h1 = 2 * raster * scale
|
||||
|
||||
const r = h1 / 2;
|
||||
|
||||
const deck: PathCommand[] = [
|
||||
{ type: "M", x: r, y: y0 },
|
||||
{ type: "H", x: l1 - r }, // --
|
||||
{ type: "A", rx: r, ry: r,
|
||||
xAxisRotation: 0,
|
||||
largeArcFlag: 0,
|
||||
sweepFlag: 1, x: l1 - r, y: h1 }, // >
|
||||
|
||||
{ type: "H", x: x0 + r }, // --
|
||||
{ type: "A", rx: r, ry: r,
|
||||
xAxisRotation: 0,
|
||||
largeArcFlag: 0,
|
||||
sweepFlag: 1, x: r, y: y0 }, // <
|
||||
{ type: "Z" }
|
||||
];
|
||||
|
||||
const c1 = new DrawGroup({});
|
||||
const c2 = new DrawGroup({});
|
||||
|
||||
const rtc = new DrawPath(deck);
|
||||
const ely1 = new DrawEllipse( { cx: 10, cy: 10, rx: 5, ry: 5});
|
||||
c2.add(ely1);
|
||||
|
||||
c1.add(rtc);
|
||||
c1.add(c2);
|
||||
c1.add(rtc);
|
||||
|
||||
return c1.getChildString(false,0)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DrawContainer } from '../graphics/lib/draw';
|
||||
import { DrawEllipse } from '../graphics/lib/drawEllipse';
|
||||
import { DrawGroup } from '../graphics/lib/drawGroup';
|
||||
import { DrawPath, PathCommand } from '../graphics/lib/drawPath';
|
||||
|
||||
@Injectable()
|
||||
export class DrawService {
|
||||
constructor() { }
|
||||
|
||||
async ellypse() {
|
||||
|
||||
const raster = 4;
|
||||
const scale = 2.0;
|
||||
const x0 = 0;
|
||||
const y0 = 0;
|
||||
|
||||
const l1 = 40 * raster * scale
|
||||
const h1 = 2 * raster * scale
|
||||
|
||||
const r = h1 / 2;
|
||||
|
||||
const deck: PathCommand[] = [
|
||||
{ type: "M", x: r, y: y0 },
|
||||
{ type: "H", x: l1 - r }, // --
|
||||
{ type: "A", rx: r, ry: r,
|
||||
xAxisRotation: 0,
|
||||
largeArcFlag: 0,
|
||||
sweepFlag: 1, x: l1 - r, y: h1 }, // >
|
||||
|
||||
{ type: "H", x: x0 + r }, // --
|
||||
{ type: "A", rx: r, ry: r,
|
||||
xAxisRotation: 0,
|
||||
largeArcFlag: 0,
|
||||
sweepFlag: 1, x: r, y: y0 }, // <
|
||||
{ type: "Z" }
|
||||
];
|
||||
|
||||
const c1 = new DrawGroup({});
|
||||
const c2 = new DrawGroup({});
|
||||
|
||||
const rtc = new DrawPath(deck);
|
||||
const ely1 = new DrawEllipse( { cx: 10, cy: 10, rx: 5, ry: 5});
|
||||
c2.add(ely1);
|
||||
|
||||
c1.add(rtc);
|
||||
c1.add(c2);
|
||||
c1.add(rtc);
|
||||
|
||||
return c1.getChildString(false,0)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,45 +1,27 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
|
||||
import { StockMovementsService } from '../movements/movements.service';
|
||||
import { StockMovementInDto,StockMovementOutDto,StockMovementTransferDto } from '../_dto/stock-movement.dto';
|
||||
|
||||
import {
|
||||
StockMovementInDto,
|
||||
StockMovementOutDto,
|
||||
StockMovementTransferDto,
|
||||
} from '../_dto/stock-movement.dto';
|
||||
|
||||
@Controller('stock-movements')
|
||||
export class StockMovementsController {
|
||||
constructor(
|
||||
|
||||
private readonly stockMovementsService: StockMovementsService
|
||||
) { console.log('movement controller');}
|
||||
|
||||
@Post('in')
|
||||
async stockIn(@Body() dto: StockMovementInDto) {
|
||||
|
||||
return this.stockMovementsService.in(dto);
|
||||
constructor(private readonly service: StockMovementsService) {}
|
||||
@Post('in') stockIn(@Body() dto: StockMovementInDto) {
|
||||
return this.service.in(dto);
|
||||
}
|
||||
|
||||
@Post('out')
|
||||
async stockOut(@Body() dto: StockMovementOutDto) {
|
||||
return this.stockMovementsService.out(dto);
|
||||
@Post('out') stockOut(@Body() dto: StockMovementOutDto) {
|
||||
return this.service.out(dto);
|
||||
}
|
||||
|
||||
@Post('transfer')
|
||||
async transfer(@Body() dto: StockMovementTransferDto) {
|
||||
return this.stockMovementsService.transfer(dto);
|
||||
@Post('transfer') transfer(@Body() dto: StockMovementTransferDto) {
|
||||
return this.service.transfer(dto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
async findx() {
|
||||
return "Hello from movement";
|
||||
@Get() findAll() {
|
||||
return this.service.findAll();
|
||||
}
|
||||
|
||||
|
||||
@Get()
|
||||
async findAll() {
|
||||
return this.stockMovementsService.findAll();
|
||||
}
|
||||
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.stockMovementsService.remove(id);
|
||||
@Delete(':id') remove(@Param('id') id: string) {
|
||||
return this.service.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,12 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
} from '@nestjs/common';
|
||||
import { StockContentService } from '../stock-content/stock-content.service';
|
||||
import { StockSummaryQuery } from '../_queries/stock-summary.query';
|
||||
|
||||
@@ -7,8 +15,7 @@ export class StockContentController {
|
||||
constructor(
|
||||
private readonly stockService: StockContentService,
|
||||
private readonly stockSummaryQuery: StockSummaryQuery,
|
||||
) { }
|
||||
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
findAll() {
|
||||
@@ -20,13 +27,12 @@ export class StockContentController {
|
||||
return this.stockService.findOne(id);
|
||||
}
|
||||
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.stockService.remove(id);
|
||||
}
|
||||
|
||||
@Get('summary/by-variant')
|
||||
@Get(['summary/by-article', 'summary/by-variant'])
|
||||
getStockByVariant() {
|
||||
return this.stockSummaryQuery.byArticle();
|
||||
}
|
||||
|
||||
@@ -1,50 +1,12 @@
|
||||
import { PartialType } from "@nestjs/mapped-types";
|
||||
import { StockDto } from "./stock.dto";
|
||||
import { ArticleVariantDto } from "src/catalog/_dto/article.dto";
|
||||
import { ArticleDto } from '../../products/_dto/article.dto';
|
||||
import { StockDto } from './stock.dto';
|
||||
|
||||
|
||||
export class StockContentDto {
|
||||
id:string
|
||||
stock: StockDto;
|
||||
articleVariant: ArticleVariantDto;
|
||||
batchNumber?: string;
|
||||
area?:string;
|
||||
quantity:number
|
||||
export interface StockContentDto {
|
||||
id: string;
|
||||
stock: StockDto;
|
||||
article: ArticleDto;
|
||||
batchId?: string;
|
||||
assetId?: string;
|
||||
area?: string;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
export class StockContentCreateDto {
|
||||
stock: StockDto;
|
||||
articleVariant: ArticleVariantDto;
|
||||
batchNumber?: string;
|
||||
area?:string;
|
||||
quantity:number
|
||||
}
|
||||
|
||||
export class StockContentFindConsumableDto {
|
||||
stockId: string;
|
||||
articleVariantId: string;
|
||||
batchNumber: string;
|
||||
}
|
||||
|
||||
export class StockContentFindNonConsumableDto {
|
||||
stockId: string;
|
||||
articleVariantId: string;
|
||||
}
|
||||
|
||||
export class StockContentConsumableInDto {
|
||||
stockId: string;
|
||||
articleVariantId: string;
|
||||
quantity: number;
|
||||
expiryDate?: Date;
|
||||
batchNumber?: string;
|
||||
area?: string;
|
||||
}
|
||||
|
||||
export class StockContentNonConsumableInDto{
|
||||
stockId: string;
|
||||
articleVariantId: string;
|
||||
quantity: number;
|
||||
area?: string;
|
||||
}
|
||||
|
||||
export class StockContentUpdateDto extends PartialType(StockContentConsumableInDto) { }
|
||||
@@ -1,4 +1,13 @@
|
||||
import { IsDate, IsMongoId, IsNumber, IsOptional, IsString } from "class-validator";
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsDate,
|
||||
IsMongoId,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
|
||||
export enum StockMovementType {
|
||||
IN = 'IN',
|
||||
@@ -7,66 +16,53 @@ export enum StockMovementType {
|
||||
}
|
||||
|
||||
export class StockMovementInDto {
|
||||
@IsString()
|
||||
@IsMongoId()
|
||||
stockId: string;
|
||||
|
||||
@IsString()
|
||||
stockId!: string;
|
||||
@IsMongoId()
|
||||
articleVariantId: string;
|
||||
|
||||
articleId!: string;
|
||||
@IsNumber()
|
||||
quantity: number;
|
||||
|
||||
@IsString()
|
||||
@Min(Number.MIN_VALUE)
|
||||
quantity!: number;
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
batchNumber?: string;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Date)
|
||||
@IsDate()
|
||||
@IsOptional()
|
||||
expiryDate?: Date;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
area?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
inventoryNumber?: string;
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
serialNumber?: string;
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
condition?: string;
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
purpose?: string;
|
||||
@IsOptional()
|
||||
@Type(() => Date)
|
||||
@IsDate()
|
||||
acquiredAt?: Date;
|
||||
}
|
||||
|
||||
export class StockMovementOutDto {
|
||||
@IsString()
|
||||
@IsMongoId()
|
||||
stockContentId: string;
|
||||
|
||||
stockContentId!: string;
|
||||
@IsNumber()
|
||||
quantity: number;
|
||||
|
||||
@Min(Number.MIN_VALUE)
|
||||
quantity!: number;
|
||||
}
|
||||
|
||||
export class StockMovementTransferDto {
|
||||
@IsString()
|
||||
export class StockMovementTransferDto extends StockMovementOutDto {
|
||||
@IsMongoId()
|
||||
articleVariantId: string;
|
||||
|
||||
@IsString()
|
||||
@IsMongoId()
|
||||
fromStockId: string;
|
||||
|
||||
@IsString()
|
||||
@IsMongoId()
|
||||
toStockId: string;
|
||||
|
||||
@IsString()
|
||||
toStockId!: string;
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
toArea?: string;
|
||||
|
||||
@IsNumber()
|
||||
quantity: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
batchNumber?: string;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { IsMongoId, IsOptional, IsString, IsArray } from "class-validator";
|
||||
import { Types } from "mongoose";
|
||||
import { LocationDto } from "src/locations/dto/location.dto";
|
||||
import { LocationDto } from "../../locations/dto/location.dto";
|
||||
|
||||
export class StockCreateDto {
|
||||
@IsString()
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
@IsString()
|
||||
@IsMongoId()
|
||||
locationId: string;
|
||||
locationId!: string;
|
||||
|
||||
@IsArray()
|
||||
@IsOptional()
|
||||
@@ -32,15 +32,15 @@ export class StockUpdateDto {
|
||||
}
|
||||
|
||||
export class StockRowDto {
|
||||
_id: string
|
||||
name: string;
|
||||
locationId: Types.ObjectId;
|
||||
_id!: string
|
||||
name!: string;
|
||||
locationId!: Types.ObjectId;
|
||||
areas?:string[]
|
||||
}
|
||||
|
||||
export class StockDto {
|
||||
id: string
|
||||
name: string;
|
||||
location: LocationDto;
|
||||
id!: string
|
||||
name!: string;
|
||||
location!: LocationDto;
|
||||
areas?:string[]
|
||||
}
|
||||
@@ -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 })
|
||||
export class StockContent extends Document {
|
||||
@Prop({ type: Types.ObjectId, ref: 'Stock', required: true })
|
||||
stockId: Types.ObjectId;
|
||||
stockId!: Types.ObjectId;
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'ArticleVariant', required: true })
|
||||
articleVariantId: Types.ObjectId;
|
||||
@Prop({ type: Types.ObjectId, ref: 'Article', required: true })
|
||||
articleId!: Types.ObjectId;
|
||||
|
||||
@Prop({required:false})
|
||||
batchNumber?: string;
|
||||
@Prop({ type: Types.ObjectId, ref: 'Batch', default: null })
|
||||
batchId?: Types.ObjectId | null;
|
||||
|
||||
@Prop({ required: true })
|
||||
quantity: number;
|
||||
@Prop({ type: Types.ObjectId, ref: 'Asset', default: null })
|
||||
assetId?: Types.ObjectId | null;
|
||||
|
||||
@Prop()
|
||||
expiryDate?: Date;
|
||||
|
||||
@Prop()
|
||||
area?: string;
|
||||
@Prop({ required: true, min: 0 })
|
||||
quantity!: number;
|
||||
|
||||
@Prop({ default: '' })
|
||||
area!: string;
|
||||
}
|
||||
|
||||
export const StockContentSchema = SchemaFactory.createForClass(StockContent);
|
||||
StockContentSchema.index(
|
||||
{ articleId: 1, stockId: 1, batchId: 1, assetId: 1, area: 1 },
|
||||
{
|
||||
unique: true,
|
||||
partialFilterExpression: { articleId: { $type: 'objectId' } },
|
||||
},
|
||||
);
|
||||
@@ -2,30 +2,23 @@ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
|
||||
import { Document, Types } from 'mongoose';
|
||||
import { StockMovementType } from '../_dto/stock-movement.dto';
|
||||
|
||||
|
||||
|
||||
@Schema({ timestamps: true })
|
||||
export class StockMovement extends Document {
|
||||
@Prop({ type: Types.ObjectId, ref: 'Stock', required: true })
|
||||
stockId: Types.ObjectId;
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'ArticleVariant', required: true })
|
||||
articleVariantId: Types.ObjectId;
|
||||
|
||||
|
||||
@Prop({ type: String, enum: StockMovementType, required: true, })
|
||||
type: StockMovementType;
|
||||
|
||||
@Prop({ required: true, min: 1 })
|
||||
quantity: number;
|
||||
|
||||
stockId!: Types.ObjectId;
|
||||
@Prop({ type: Types.ObjectId, ref: 'Article', required: true })
|
||||
articleId!: Types.ObjectId;
|
||||
@Prop({ type: String, enum: StockMovementType, required: true })
|
||||
type!: StockMovementType;
|
||||
@Prop({ required: true, min: Number.MIN_VALUE })
|
||||
quantity!: number;
|
||||
@Prop({ type: Types.ObjectId, ref: 'Stock' })
|
||||
toStockId?: Types.ObjectId;
|
||||
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'Batch' })
|
||||
batchId?: Types.ObjectId;
|
||||
@Prop({ type: Types.ObjectId, ref: 'Asset' })
|
||||
assetId?: Types.ObjectId;
|
||||
@Prop({ type: Object })
|
||||
meta?: Record<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 })
|
||||
export class Stock extends Document {
|
||||
@Prop({ required: true })
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'Location', required: true })
|
||||
locationId: Types.ObjectId;
|
||||
locationId!: Types.ObjectId;
|
||||
|
||||
@Prop({ })
|
||||
areas: Types.Array<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 { Model } from 'mongoose';
|
||||
import { StockContent } from '../_entities/stock-content.entity'
|
||||
import { StockContent } from '../_entities/stock-content.entity';
|
||||
|
||||
@Injectable()
|
||||
export class StockSummaryQuery {
|
||||
constructor(
|
||||
@InjectModel(StockContent.name)
|
||||
private readonly stockModel: Model<StockContent>,
|
||||
) { }
|
||||
|
||||
async byArticle() {
|
||||
console.log('get');
|
||||
const x = await this.stockModel.aggregate<{id_:string,articleVariantId:string,articleName:string,manufacturer:string,totalQuantity:number}>([
|
||||
{
|
||||
$group: {
|
||||
_id: '$articleVariantId',
|
||||
totalQuantity: { $sum: '$quantity' },
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
$lookup: {
|
||||
from: 'articlevariants',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'variant',
|
||||
}
|
||||
},
|
||||
|
||||
{ $unwind: '$variant' },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'articles',
|
||||
localField: 'variant.articleId',
|
||||
foreignField: '_id',
|
||||
as: 'article',
|
||||
},
|
||||
},
|
||||
{ $unwind: '$article' },
|
||||
// 4️⃣ Hersteller holen
|
||||
{
|
||||
$lookup: {
|
||||
from: 'manufacturers',
|
||||
localField: 'variant.manufacturerId',
|
||||
foreignField: '_id',
|
||||
as: 'manufacturer',
|
||||
},
|
||||
},
|
||||
{ $unwind: '$manufacturer' },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
articleVariantId: '$_id',
|
||||
articleName: '$article.name',
|
||||
manufacturer: '$manufacturer.name',
|
||||
totalQuantity: 1,
|
||||
},
|
||||
}
|
||||
|
||||
]);
|
||||
console.log(x[0].articleName + ' von ' + x[0].manufacturer);
|
||||
return x;
|
||||
}
|
||||
|
||||
async byArticle2() {
|
||||
return this.stockModel.aggregate([
|
||||
{
|
||||
$group: {
|
||||
_id: '$articleVariantId',
|
||||
totalQuantity: { $sum: '$quantity' },
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'articlevariants',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'variant',
|
||||
},
|
||||
},
|
||||
{ $unwind: '$variant' },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'articles',
|
||||
localField: 'variant.articleId',
|
||||
foreignField: '_id',
|
||||
as: 'article',
|
||||
},
|
||||
},
|
||||
{ $unwind: '$article' },
|
||||
]);
|
||||
}
|
||||
}
|
||||
constructor(
|
||||
@InjectModel(StockContent.name) private readonly model: Model<StockContent>,
|
||||
) {}
|
||||
byArticle() {
|
||||
return this.model
|
||||
.aggregate([
|
||||
{ $match: { articleId: { $exists: true } } },
|
||||
{ $group: { _id: '$articleId', totalQuantity: { $sum: '$quantity' } } },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'articles',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'article',
|
||||
},
|
||||
},
|
||||
{ $unwind: '$article' },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
articleId: '$_id',
|
||||
articleName: '$article.name',
|
||||
baseUnit: '$article.baseUnit',
|
||||
totalQuantity: 1,
|
||||
},
|
||||
},
|
||||
])
|
||||
.exec();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
|
||||
import { MovementsModule } from './movements/movements.module';
|
||||
import { StockContentModule } from './stock-content/stock-content.module';
|
||||
import { StockModule } from './stock/stock.module';
|
||||
import { LocationsModule } from 'src/locations/locations.module';
|
||||
import { LocationsModule } from '../locations/locations.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
|
||||
@@ -1,76 +1,53 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model, Types } from 'mongoose';
|
||||
import { ClientSession, Model, Types } from 'mongoose';
|
||||
import { StockMovement } from '../_entities/stock-movement.entity';
|
||||
|
||||
import { StockMovementInDto, StockMovementType, StockMovementTransferDto, StockMovementOutDto } from '../_dto/stock-movement.dto';
|
||||
|
||||
import { StockContent } from '../_entities/stock-content.entity';
|
||||
import { StockMovementType } from '../_dto/stock-movement.dto';
|
||||
|
||||
@Injectable()
|
||||
export class MovementRepository {
|
||||
constructor(
|
||||
@InjectModel(StockMovement.name)
|
||||
private readonly model: Model<StockMovement>,
|
||||
|
||||
) { }
|
||||
|
||||
async findAll() {
|
||||
return this.model.find().exec();
|
||||
) {}
|
||||
findAll() {
|
||||
return this.model
|
||||
.find({ articleId: { $exists: true } })
|
||||
.sort({ createdAt: -1 })
|
||||
.exec();
|
||||
}
|
||||
|
||||
remove(id: string) {
|
||||
return this.model.findByIdAndDelete(id);
|
||||
}
|
||||
|
||||
// ===============================
|
||||
// IN
|
||||
// ===============================
|
||||
async logStockMoveIn(dto: StockMovementInDto) {
|
||||
const { articleVariantId, stockId, quantity } = dto;
|
||||
return this.model.create(
|
||||
{
|
||||
articleVariantId,
|
||||
stockId,
|
||||
type: StockMovementType.IN,
|
||||
quantity
|
||||
}
|
||||
remove(_id: string): never {
|
||||
throw new BadRequestException(
|
||||
'Buchungsprotokolle können nicht gelöscht werden',
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// ===============================
|
||||
// OUT
|
||||
// ===============================
|
||||
async logStockMoveOut(dto: StockMovementOutDto,result:any) {
|
||||
|
||||
return this.model.create({
|
||||
stockId: new Types.ObjectId(dto.stockContentId),
|
||||
articleVariantId: new Types.ObjectId(result.articelVariantId),
|
||||
type: StockMovementType.OUT,
|
||||
quantity: dto.quantity,
|
||||
});
|
||||
async log(
|
||||
type: StockMovementType,
|
||||
content: StockContent,
|
||||
quantity: number,
|
||||
session: ClientSession,
|
||||
toStockId?: string,
|
||||
toArea?: string,
|
||||
) {
|
||||
const [movement] = await this.model.create(
|
||||
[
|
||||
{
|
||||
type,
|
||||
articleId: content.articleId,
|
||||
stockId: content.stockId,
|
||||
quantity,
|
||||
batchId: content.batchId ?? undefined,
|
||||
assetId: content.assetId ?? undefined,
|
||||
toStockId: toStockId ? new Types.ObjectId(toStockId) : undefined,
|
||||
meta: {
|
||||
fromArea: content.area,
|
||||
...(toArea !== undefined ? { toArea } : {}),
|
||||
},
|
||||
},
|
||||
],
|
||||
{ session },
|
||||
);
|
||||
return movement;
|
||||
}
|
||||
|
||||
// ===============================
|
||||
// TRANSFER
|
||||
// ===============================
|
||||
async logStockContentTransfer(dto: StockMovementTransferDto) {
|
||||
const { articleVariantId, quantity, fromStockId, toStockId } = dto;
|
||||
|
||||
|
||||
return this.model.create({
|
||||
articleVariantId: new Types.ObjectId(articleVariantId),
|
||||
stockId:fromStockId,
|
||||
type: StockMovementType.TRANSFER,
|
||||
quantity,
|
||||
meta: {
|
||||
fromLocationId: new Types.ObjectId(fromStockId),
|
||||
toLocationId: new Types.ObjectId(toStockId),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,43 +1,22 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { StockMovementsController } from '../_controllers/movements.controller';
|
||||
import { StockMovementsService } from './movements.service';
|
||||
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
|
||||
import { MovementRepository } from './movement.repository';
|
||||
|
||||
import { StockContent, StockContentSchema } from '../_entities/stock-content.entity';
|
||||
import { StockMovement, StockMovementSchema } from '../_entities/stock-movement.entity';
|
||||
import { Article, ArticleSchema } from 'src/catalog/_entities/article.entity';
|
||||
import { ArticleVariant, ArticleVariantSchema } from 'src/catalog/_entities/article-variant.entity';
|
||||
import { CatalogModule } from 'src/catalog/catalog.module';
|
||||
import { StockMovementsController } from '../_controllers/movements.controller';
|
||||
import {
|
||||
StockMovement,
|
||||
StockMovementSchema,
|
||||
} from '../_entities/stock-movement.entity';
|
||||
import { StockContentModule } from '../stock-content/stock-content.module';
|
||||
import { StockContentRepository } from '../stock-content/stock-content.repository';
|
||||
import { StockContentService } from '../stock-content/stock-content.service';
|
||||
|
||||
|
||||
import { StockMovementsService } from './movements.service';
|
||||
import { MovementRepository } from './movement.repository';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MongooseModule.forFeature([
|
||||
{ name: StockContent.name, schema: StockContentSchema },
|
||||
{ name: StockMovement.name, schema: StockMovementSchema },
|
||||
{ name: Article.name, schema: ArticleSchema },
|
||||
{ name: ArticleVariant.name, schema: ArticleVariantSchema },
|
||||
|
||||
]),
|
||||
CatalogModule,
|
||||
|
||||
],
|
||||
|
||||
controllers: [StockMovementsController],
|
||||
providers: [
|
||||
StockMovementsService,
|
||||
StockContentService,
|
||||
StockContentRepository,
|
||||
MovementRepository,
|
||||
MongooseModule.forFeature([
|
||||
{ name: StockMovement.name, schema: StockMovementSchema },
|
||||
]),
|
||||
StockContentModule,
|
||||
],
|
||||
|
||||
controllers: [StockMovementsController],
|
||||
providers: [StockMovementsService, MovementRepository],
|
||||
})
|
||||
export class MovementsModule { }
|
||||
export class MovementsModule {}
|
||||
@@ -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 { StockMovementOutDto, StockMovementInDto, StockMovementTransferDto } from '../_dto/stock-movement.dto';
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectConnection } from '@nestjs/mongoose';
|
||||
import { ClientSession, Connection } from 'mongoose';
|
||||
import {
|
||||
StockMovementInDto,
|
||||
StockMovementOutDto,
|
||||
StockMovementTransferDto,
|
||||
StockMovementType,
|
||||
} from '../_dto/stock-movement.dto';
|
||||
import { MovementRepository } from './movement.repository';
|
||||
import { StockContentService } from '../stock-content/stock-content.service';
|
||||
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class StockMovementsService {
|
||||
constructor(
|
||||
private readonly movementRepo: MovementRepository,
|
||||
private readonly stockContentService: StockContentService
|
||||
) { }
|
||||
|
||||
findAll() {
|
||||
return this.movementRepo.findAll();
|
||||
constructor(
|
||||
private readonly movementRepo: MovementRepository,
|
||||
private readonly stockContentService: StockContentService,
|
||||
@InjectConnection() private readonly connection: Connection,
|
||||
) {}
|
||||
findAll() {
|
||||
return this.movementRepo.findAll();
|
||||
}
|
||||
remove(id: string) {
|
||||
return this.movementRepo.remove(id);
|
||||
}
|
||||
in(dto: StockMovementInDto) {
|
||||
return this.book(async (session) => {
|
||||
const content = await this.stockContentService.moveIn(dto, session);
|
||||
return this.movementRepo.log(
|
||||
StockMovementType.IN,
|
||||
content,
|
||||
dto.quantity,
|
||||
session,
|
||||
);
|
||||
});
|
||||
}
|
||||
out(dto: StockMovementOutDto) {
|
||||
return this.book(async (session) => {
|
||||
const content = await this.stockContentService.moveOut(dto, session);
|
||||
return this.movementRepo.log(
|
||||
StockMovementType.OUT,
|
||||
content,
|
||||
dto.quantity,
|
||||
session,
|
||||
);
|
||||
});
|
||||
}
|
||||
transfer(dto: StockMovementTransferDto) {
|
||||
return this.book(async (session) => {
|
||||
const content = await this.stockContentService.transfer(dto, session);
|
||||
return this.movementRepo.log(
|
||||
StockMovementType.TRANSFER,
|
||||
content,
|
||||
dto.quantity,
|
||||
session,
|
||||
dto.toStockId,
|
||||
dto.toArea ?? '',
|
||||
);
|
||||
});
|
||||
}
|
||||
private async book<T>(
|
||||
action: (session: ClientSession) => Promise<T>,
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await this.connection.transaction(action);
|
||||
} catch (error) {
|
||||
if (
|
||||
error &&
|
||||
typeof error === 'object' &&
|
||||
'code' in error &&
|
||||
error.code === 20
|
||||
) {
|
||||
throw new ServiceUnavailableException(
|
||||
'Lagerbuchungen benötigen MongoDB als Replica Set oder Sharded Cluster',
|
||||
);
|
||||
}
|
||||
if (
|
||||
error &&
|
||||
typeof error === 'object' &&
|
||||
'code' in error &&
|
||||
error.code === 11000
|
||||
) {
|
||||
throw new ConflictException(
|
||||
'Inventarnummer oder Bestandsposition ist bereits vergeben; Buchung erneut prüfen',
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
remove(id: string) {
|
||||
return this.movementRepo.remove(id);
|
||||
}
|
||||
|
||||
|
||||
async in(dto: StockMovementInDto) {
|
||||
this.validateIn(dto);
|
||||
|
||||
const result = this.stockContentService.moveIn(dto);
|
||||
return await this.movementRepo.logStockMoveIn(dto);
|
||||
}
|
||||
|
||||
async out(dto: StockMovementOutDto) {
|
||||
const outResult = await this.stockContentService.moveOut(dto);
|
||||
return await this.movementRepo.logStockMoveOut(dto, outResult);
|
||||
}
|
||||
|
||||
async transfer(dto: StockMovementTransferDto) {
|
||||
const result = await this.stockContentService.transfer(dto);
|
||||
return this.movementRepo.logStockContentTransfer(dto);
|
||||
}
|
||||
|
||||
|
||||
private validateIn(dto: StockMovementInDto) {
|
||||
if (dto.quantity <= 0) {
|
||||
throw new BadRequestException('Menge muss > 0 sein');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 { MongooseModule } from '@nestjs/mongoose';
|
||||
import {
|
||||
StockContent,
|
||||
StockContentSchema,
|
||||
} from '../_entities/stock-content.entity';
|
||||
import { Stock, StockSchema } from '../_entities/stock.entity';
|
||||
import { Batch, BatchSchema } from '../_entities/batch.entity';
|
||||
import { Asset, AssetSchema } from '../_entities/asset.entity';
|
||||
import { Article, ArticleSchema } from '../../products/_entities/article.entity';
|
||||
import { StockContentService } from './stock-content.service';
|
||||
import { StockContentRepository } from './stock-content.repository';
|
||||
import { StockContentController } from '../_controllers/stock-content.controller';
|
||||
import { StockSummaryQuery } from '../_queries/stock-summary.query';
|
||||
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { StockContent, StockContentSchema } from '../_entities/stock-content.entity';
|
||||
import { StockContentRepository } from './stock-content.repository';
|
||||
import { CatalogModule } from 'src/catalog/catalog.module';
|
||||
import { StockModule } from '../stock/stock.module';
|
||||
import { StockService } from '../stock/stock.service';
|
||||
|
||||
|
||||
import {
|
||||
InventoryRecordsController,
|
||||
InventoryRecordsService,
|
||||
} from '../records/inventory-records';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MongooseModule.forFeature([
|
||||
{ name: StockContent.name, schema: StockContentSchema },
|
||||
{ name: Stock.name, schema: StockSchema },
|
||||
{ name: Article.name, schema: ArticleSchema },
|
||||
{ name: Batch.name, schema: BatchSchema },
|
||||
{ name: Asset.name, schema: AssetSchema },
|
||||
]),
|
||||
CatalogModule,
|
||||
|
||||
],
|
||||
controllers: [StockContentController],
|
||||
providers: [StockContentService, StockSummaryQuery,StockContentRepository],
|
||||
exports: [StockContentService]
|
||||
controllers: [StockContentController, InventoryRecordsController],
|
||||
providers: [
|
||||
StockContentService,
|
||||
StockContentRepository,
|
||||
StockSummaryQuery,
|
||||
InventoryRecordsService,
|
||||
],
|
||||
exports: [StockContentService],
|
||||
})
|
||||
export class StockContentModule { }
|
||||
export class StockContentModule {}
|
||||
@@ -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 {
|
||||
StockContentConsumableInDto,
|
||||
StockContentNonConsumableInDto,
|
||||
StockContentFindConsumableDto,
|
||||
StockContentFindNonConsumableDto
|
||||
} from '../_dto/stock-content.dto';
|
||||
|
||||
import { StockMovementOutDto, StockMovementTransferDto } from '../_dto/stock-movement.dto';
|
||||
import { ArticleVariantService } from 'src/catalog/article-variant/article-variant.service';
|
||||
|
||||
|
||||
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { ClientSession, Model, Types } from 'mongoose';
|
||||
import { Article, TrackingMode } from '../../products/_entities/article.entity';
|
||||
import { StockContent } from '../_entities/stock-content.entity';
|
||||
import { Stock } from '../_entities/stock.entity';
|
||||
import { Batch } from '../_entities/batch.entity';
|
||||
import { Asset } from '../_entities/asset.entity';
|
||||
import {
|
||||
StockMovementInDto,
|
||||
StockMovementOutDto,
|
||||
StockMovementTransferDto,
|
||||
} from '../_dto/stock-movement.dto';
|
||||
|
||||
@Injectable()
|
||||
export class StockContentRepository {
|
||||
constructor(
|
||||
@InjectModel(StockContent.name)
|
||||
private readonly model: Model<StockContent>,
|
||||
//private readonly articleService: ArticleVariantService,
|
||||
@InjectModel(StockContent.name) private readonly model: Model<StockContent>,
|
||||
@InjectModel(Article.name) private readonly articles: Model<Article>,
|
||||
@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) {
|
||||
return this.model.findByIdAndDelete(id);
|
||||
}
|
||||
|
||||
async findById(stockId: string) {
|
||||
return this.model.findById(stockId);
|
||||
}
|
||||
|
||||
async findNonConsumable(dto: StockContentFindNonConsumableDto) {
|
||||
return this.model
|
||||
.findOne({
|
||||
articleVariantId: dto.articleVariantId,
|
||||
stockId: dto.stockId,
|
||||
batchNumber: null,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
async findConsumable(dto: StockContentFindConsumableDto) {
|
||||
const { articleVariantId, stockId, batchNumber } = dto;
|
||||
|
||||
return this.model
|
||||
.findOne({
|
||||
articleVariantId,
|
||||
stockId,
|
||||
batchNumber,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Stock IN
|
||||
*/
|
||||
|
||||
//--- Konsumierbare artikel
|
||||
async moveConsumableIn(dto: StockContentConsumableInDto): Promise<StockContent> {
|
||||
|
||||
const { stockId, articleVariantId, batchNumber, quantity } = dto;
|
||||
|
||||
if (!batchNumber) {
|
||||
if (article.trackingMode === TrackingMode.BATCH) {
|
||||
if (!dto.batchNumber?.trim())
|
||||
throw new BadRequestException('Chargennummer erforderlich');
|
||||
const existing = await this.batches
|
||||
.findOne({
|
||||
articleId: article._id,
|
||||
batchNumber: dto.batchNumber.trim(),
|
||||
})
|
||||
.session(session)
|
||||
.exec();
|
||||
if (
|
||||
article.tracksExpiryDate &&
|
||||
!dto.expiryDate &&
|
||||
!existing?.expiryDate
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Ablaufdatum für diese Charge erforderlich',
|
||||
);
|
||||
}
|
||||
if (!article.tracksExpiryDate && dto.expiryDate)
|
||||
throw new BadRequestException('Dieser Artikel führt keine Ablaufdaten');
|
||||
if (existing) {
|
||||
if (
|
||||
dto.expiryDate &&
|
||||
existing.expiryDate?.getTime() !== dto.expiryDate.getTime()
|
||||
) {
|
||||
throw new ConflictException(
|
||||
'Ablaufdatum weicht von der bestehenden Charge ab',
|
||||
);
|
||||
}
|
||||
batchId = existing._id;
|
||||
} else {
|
||||
const [batch] = await this.batches.create(
|
||||
[
|
||||
{
|
||||
articleId: article._id,
|
||||
batchNumber: dto.batchNumber.trim(),
|
||||
expiryDate: dto.expiryDate,
|
||||
},
|
||||
],
|
||||
{ session },
|
||||
);
|
||||
batchId = batch._id;
|
||||
}
|
||||
} else if (dto.batchNumber || dto.expiryDate) {
|
||||
throw new BadRequestException(
|
||||
'Batch Nummer erfoderlich erforderlich',
|
||||
'Charge und Ablaufdatum sind nur bei Chargenführung erlaubt',
|
||||
);
|
||||
}
|
||||
|
||||
const stockContent = await this.findConsumable({ stockId, articleVariantId, batchNumber });
|
||||
|
||||
return await this.moveIn(dto, stockContent);
|
||||
|
||||
}
|
||||
|
||||
|
||||
// Nicht Konsumierbare artikel
|
||||
async moveNonConsumableIn(dto: StockContentNonConsumableInDto): Promise<StockContent> {
|
||||
|
||||
const stockContent = await this.findNonConsumable({
|
||||
articleVariantId: dto.articleVariantId,
|
||||
stockId: dto.stockId,
|
||||
});
|
||||
|
||||
return this.moveIn(dto, stockContent);
|
||||
|
||||
}
|
||||
|
||||
private async moveIn(dto: StockContentConsumableInDto, stockContent?: StockContent | null): Promise<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 (article.trackingMode === TrackingMode.INDIVIDUAL) {
|
||||
if (dto.quantity !== 1 || !dto.inventoryNumber?.trim()) {
|
||||
throw new BadRequestException(
|
||||
'Einzelstücke benötigen Menge 1 und eine Inventarnummer',
|
||||
);
|
||||
}
|
||||
if (dto.area) create['area'] = dto.area;
|
||||
if (dto.batchNumber) create['batchNumber'] = dto.batchNumber;
|
||||
if (dto.expiryDate) create['expiryDate'] = dto.expiryDate;
|
||||
|
||||
result = await this.model.create(create);
|
||||
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Move from Stock OUT
|
||||
*/
|
||||
async moveOut(dto: StockMovementOutDto) {
|
||||
|
||||
let stockContent = await this.findById(dto.stockContentId);
|
||||
if (!stockContent) throw new BadRequestException('consumeStock: Stock Content nicht gefunden');
|
||||
|
||||
|
||||
|
||||
let result = {
|
||||
stockId: stockContent._id,
|
||||
articleVariantId: stockContent.articleVariantId,
|
||||
quantity: dto.quantity,
|
||||
empty: false
|
||||
}
|
||||
|
||||
stockContent.quantity -= dto.quantity;
|
||||
|
||||
if (stockContent.quantity < 0) {
|
||||
throw new BadRequestException('Negativer Bestand');
|
||||
}
|
||||
|
||||
if (stockContent.quantity === 0) {
|
||||
result.empty = true;
|
||||
await stockContent.deleteOne();
|
||||
} else {
|
||||
await stockContent.save();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// =================================
|
||||
// TRANSFER
|
||||
// =================================
|
||||
|
||||
|
||||
|
||||
async transfer(dto: StockMovementTransferDto, isConsumable: boolean) {
|
||||
const { articleVariantId, quantity, fromStockId, toStockId } = dto;
|
||||
//const articleVariant = await this.articleService.findOne(articleVariantId);
|
||||
//const isConsumable = articleVariant.article.category.isConsumable;
|
||||
|
||||
if (isConsumable && !dto.batchNumber) throw new BadRequestException('Batch Nummer muss für Konsumierbare Artikel zum Verschieben vorhanden sein');
|
||||
//if (!articleVariant) throw new BadRequestException('Artikel Variante nicht gefunden');
|
||||
|
||||
if (isConsumable && dto.batchNumber) {
|
||||
this.handelTransferConsumable(dto)
|
||||
} else {
|
||||
this.handelTransferNonConsumable(articleVariantId, fromStockId, toStockId, quantity)
|
||||
}
|
||||
|
||||
let retValue = {
|
||||
//articleVariant,
|
||||
isConsumable,
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private async handelTransferConsumable(dto: StockMovementTransferDto) {
|
||||
const { articleVariantId, fromStockId, batchNumber, quantity, toStockId, toArea } = dto;
|
||||
|
||||
if (!batchNumber) throw new BadRequestException('handelTransferConsumable: Batch Nummer muss vorhanden sein');
|
||||
|
||||
//--- StockContent -- FROM
|
||||
const stockContentFrom = await this.findConsumable({ articleVariantId, stockId: fromStockId, batchNumber });
|
||||
|
||||
if (!stockContentFrom) throw new BadRequestException('handelTransferConsumable: stockContentFrom nicht gefunden');
|
||||
if (stockContentFrom.quantity < quantity) throw new BadRequestException('handelTransferConsumable: Menge überschreitet Lagerbestand im Quell Lager');
|
||||
|
||||
//--- StockContent -- TO
|
||||
const stockContetTo = await this.findConsumable({ articleVariantId, stockId: toStockId, batchNumber });
|
||||
|
||||
// From Content aktualisieren
|
||||
stockContentFrom.quantity -= quantity;
|
||||
if (stockContentFrom.quantity == 0) {
|
||||
// Lager ist leergeräumt
|
||||
await this.remove(fromStockId);
|
||||
} else {
|
||||
// neuer lagerbestand speichern
|
||||
await stockContentFrom.save();
|
||||
}
|
||||
|
||||
if (stockContetTo) {
|
||||
// Besteand vom exisitierenden Lagerbestand erhöhen
|
||||
stockContetTo.quantity += quantity;
|
||||
await stockContetTo.save();
|
||||
} else {
|
||||
// Besteand im Ziellager neu anlegen
|
||||
let data = {
|
||||
stockId: toStockId,
|
||||
articleVariantId,
|
||||
quantity,
|
||||
batchNumber,
|
||||
const inventoryNumber = dto.inventoryNumber.trim();
|
||||
const existing = await this.assets
|
||||
.findOne({ inventoryNumber })
|
||||
.session(session)
|
||||
.exec();
|
||||
if (existing) {
|
||||
if (
|
||||
existing.articleId.toString() !== article._id.toString() ||
|
||||
existing.status !== 'withdrawn'
|
||||
) {
|
||||
throw new ConflictException(
|
||||
'Inventarnummer gehört zu einem anderen Artikel oder ist bereits eingelagert',
|
||||
);
|
||||
}
|
||||
await this.assets.updateOne(
|
||||
{ _id: existing._id },
|
||||
{
|
||||
$set: {
|
||||
status: 'in-stock',
|
||||
stockId: new Types.ObjectId(dto.stockId),
|
||||
},
|
||||
},
|
||||
{ session },
|
||||
);
|
||||
assetId = existing._id;
|
||||
} else {
|
||||
const [asset] = await this.assets.create(
|
||||
[
|
||||
{
|
||||
articleId: article._id,
|
||||
inventoryNumber,
|
||||
serialNumber: dto.serialNumber,
|
||||
condition: dto.condition,
|
||||
purpose: dto.purpose,
|
||||
acquiredAt: dto.acquiredAt,
|
||||
stockId: dto.stockId,
|
||||
},
|
||||
],
|
||||
{ session },
|
||||
);
|
||||
assetId = asset._id;
|
||||
}
|
||||
if(toArea) data['area'] = toArea;
|
||||
this.moveConsumableIn(data)
|
||||
} else if (
|
||||
dto.inventoryNumber ||
|
||||
dto.serialNumber ||
|
||||
dto.condition ||
|
||||
dto.purpose ||
|
||||
dto.acquiredAt
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Exemplardaten sind nur bei Einzelstückführung erlaubt',
|
||||
);
|
||||
}
|
||||
|
||||
return this.model
|
||||
.findOneAndUpdate(
|
||||
{
|
||||
articleId: article._id,
|
||||
stockId: dto.stockId,
|
||||
batchId,
|
||||
assetId,
|
||||
area: dto.area ?? '',
|
||||
},
|
||||
{ $inc: { quantity: dto.quantity } },
|
||||
{ new: true, upsert: true, runValidators: true, session },
|
||||
)
|
||||
.exec();
|
||||
}
|
||||
|
||||
private async handelTransferNonConsumable(articleVariantId: string, fromStockId: string, toStockId: string, quantity: number) {
|
||||
|
||||
const stockContentFrom = await this.findNonConsumable({ articleVariantId, stockId: fromStockId, });
|
||||
if (!stockContentFrom) throw new BadRequestException('from StockContent not found');
|
||||
|
||||
const stockContetTo = await this.findNonConsumable({ articleVariantId, stockId: toStockId, });
|
||||
if (stockContentFrom.quantity < quantity) throw new BadRequestException('Menge überschreitet Lagerbestand im Quell Lager');
|
||||
|
||||
stockContentFrom.quantity -= quantity;
|
||||
if (stockContentFrom.quantity == 0) {
|
||||
// Lager ist leergeräumt
|
||||
await this.remove(fromStockId);
|
||||
} else {
|
||||
// neuer lagerbestand speichern
|
||||
await stockContentFrom.save();
|
||||
}
|
||||
|
||||
if (stockContetTo) {
|
||||
// Besteand vom exisitierenden Lagerbestand erhöhen
|
||||
stockContetTo.quantity += quantity;
|
||||
await stockContetTo.save();
|
||||
} else {
|
||||
// Besteand im Ziellager neu anlegen
|
||||
this.moveNonConsumableIn({
|
||||
stockId: toStockId,
|
||||
articleVariantId,
|
||||
quantity
|
||||
})
|
||||
}
|
||||
|
||||
async moveOut(dto: StockMovementOutDto, session: ClientSession) {
|
||||
this.positive(dto.quantity);
|
||||
const content = await this.model
|
||||
.findOneAndUpdate(
|
||||
{
|
||||
_id: dto.stockContentId,
|
||||
articleId: { $exists: true },
|
||||
quantity: { $gte: dto.quantity },
|
||||
},
|
||||
{ $inc: { quantity: -dto.quantity } },
|
||||
{ new: true, session },
|
||||
)
|
||||
.exec();
|
||||
if (!content)
|
||||
throw new BadRequestException(
|
||||
'Bestand nicht gefunden oder Menge überschreitet Bestand',
|
||||
);
|
||||
if (content.assetId && dto.quantity !== 1)
|
||||
throw new BadRequestException(
|
||||
'Einzelstücke können nur vollständig entnommen werden',
|
||||
);
|
||||
if (content.quantity === 0)
|
||||
await this.model.deleteOne({ _id: content._id }, { session });
|
||||
if (content.assetId)
|
||||
await this.assets.updateOne(
|
||||
{ _id: content.assetId },
|
||||
{
|
||||
$set: { status: 'withdrawn', stockId: null },
|
||||
},
|
||||
{ session },
|
||||
);
|
||||
return content;
|
||||
}
|
||||
|
||||
async transfer(dto: StockMovementTransferDto, session: ClientSession) {
|
||||
this.positive(dto.quantity);
|
||||
const source = await this.model
|
||||
.findById(dto.stockContentId)
|
||||
.session(session)
|
||||
.exec();
|
||||
if (!source?.articleId)
|
||||
throw new NotFoundException('Bestand nicht gefunden');
|
||||
await this.validateStock(dto.toStockId, dto.toArea, session);
|
||||
if (
|
||||
source.stockId.toString() === dto.toStockId &&
|
||||
source.area === (dto.toArea ?? '')
|
||||
) {
|
||||
throw new BadRequestException('Quelle und Ziel sind identisch');
|
||||
}
|
||||
const content = await this.moveOut(dto, session);
|
||||
await this.model
|
||||
.findOneAndUpdate(
|
||||
{
|
||||
articleId: source.articleId,
|
||||
stockId: dto.toStockId,
|
||||
batchId: source.batchId ?? null,
|
||||
assetId: source.assetId ?? null,
|
||||
area: dto.toArea ?? '',
|
||||
},
|
||||
{ $inc: { quantity: dto.quantity } },
|
||||
{ new: true, upsert: true, runValidators: true, session },
|
||||
)
|
||||
.exec();
|
||||
if (source.assetId)
|
||||
await this.assets.updateOne(
|
||||
{ _id: source.assetId },
|
||||
{
|
||||
$set: {
|
||||
status: 'in-stock',
|
||||
stockId: new Types.ObjectId(dto.toStockId),
|
||||
},
|
||||
},
|
||||
{ session },
|
||||
);
|
||||
return content;
|
||||
}
|
||||
|
||||
}
|
||||
private positive(quantity: number) {
|
||||
if (!Number.isFinite(quantity) || quantity <= 0)
|
||||
throw new BadRequestException('Menge muss größer als 0 sein');
|
||||
}
|
||||
|
||||
/*
|
||||
async increaseOrCreate(
|
||||
data: {
|
||||
articleId: string;
|
||||
locationId: string;
|
||||
quantity: number;
|
||||
expiryDate?: Date;
|
||||
batchNumber?: string;
|
||||
},
|
||||
session?: ClientSession,
|
||||
private async validateStock(
|
||||
stockId: string,
|
||||
area: string | undefined,
|
||||
session: ClientSession,
|
||||
) {
|
||||
const filter: any = {
|
||||
articleId: data.articleId,
|
||||
locationId: data.locationId,
|
||||
expiryDate: data.expiryDate ?? null,
|
||||
batchNumber: data.batchNumber ?? null,
|
||||
};
|
||||
|
||||
const stock = await this.model
|
||||
.findOne(filter)
|
||||
.session(session ?? null);
|
||||
|
||||
if (stock) {
|
||||
stock.quantity += data.quantity;
|
||||
await stock.save({ session });
|
||||
} else {
|
||||
await this.model.create([data], { session });
|
||||
}
|
||||
const stock = await this.stocks.findById(stockId).session(session).exec();
|
||||
if (!stock) throw new NotFoundException('Lager nicht gefunden');
|
||||
if (area && !stock.areas?.includes(area))
|
||||
throw new BadRequestException('Lagerbereich ist nicht vorhanden');
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -1,234 +1,55 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { ClientSession, Model, Types } from 'mongoose';
|
||||
import { StockContent } from '../_entities/stock-content.entity';
|
||||
import { StockContentConsumableInDto, StockContentNonConsumableInDto, StockContentFindConsumableDto, StockContentFindNonConsumableDto, StockContentDto } from '../_dto/stock-content.dto';
|
||||
import { StockContentRepository } from './stock-content.repository';
|
||||
import { StockMovementInDto, StockMovementOutDto, StockMovementTransferDto } from '../_dto/stock-movement.dto';
|
||||
import { ArticleVariantService } from 'src/catalog/article-variant/article-variant.service';
|
||||
import { StockService } from '../stock/stock.service';
|
||||
import {
|
||||
StockMovementInDto,
|
||||
StockMovementOutDto,
|
||||
StockMovementTransferDto,
|
||||
} from '../_dto/stock-movement.dto';
|
||||
|
||||
@Injectable()
|
||||
export class StockContentService {
|
||||
|
||||
constructor(
|
||||
@InjectModel(StockContent.name) private stockContentModel: Model<StockContent>,
|
||||
private readonly stockContentRepo: StockContentRepository,
|
||||
private readonly articleVariantService: ArticleVariantService,
|
||||
// private readonly stockService: StockService
|
||||
|
||||
) { }
|
||||
|
||||
async findAll() {
|
||||
let stockContent = await this.stockContentModel.aggregate<StockContent>([
|
||||
{
|
||||
$lookup: {
|
||||
from: 'articlevariants',
|
||||
localField: 'articleVariantId',
|
||||
foreignField: '_id',
|
||||
as: 'articleVariant',
|
||||
pipeline: [
|
||||
{
|
||||
$addFields: { id: "$_id" }
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'articles',
|
||||
localField: 'articleId',
|
||||
foreignField: '_id',
|
||||
as: 'article',
|
||||
pipeline: [
|
||||
{
|
||||
$addFields: { id: "$_id" }
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
__v: 0,
|
||||
_id: 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
$unwind: {
|
||||
path: "$article",
|
||||
preserveNullAndEmptyArrays: true
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
$project: {
|
||||
articleId: 0,
|
||||
__v: 0,
|
||||
_id: 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
},
|
||||
{
|
||||
$unwind: {
|
||||
path: "$articleVariant",
|
||||
preserveNullAndEmptyArrays: true
|
||||
}
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'stocks',
|
||||
localField: 'stockId',
|
||||
foreignField: '_id',
|
||||
as: 'stock',
|
||||
pipeline: [
|
||||
{
|
||||
$addFields: { id: "$_id" }
|
||||
},
|
||||
|
||||
{
|
||||
$lookup: {
|
||||
from: 'locations',
|
||||
localField: 'locationId',
|
||||
foreignField: '_id',
|
||||
as: 'location',
|
||||
pipeline: [
|
||||
{
|
||||
$addFields: { id: "$_id" }
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
__v: 0,
|
||||
_id: 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
$unwind: {
|
||||
path: "$location",
|
||||
preserveNullAndEmptyArrays: true
|
||||
}
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
// articleId:0,
|
||||
__v: 0,
|
||||
_id: 0,
|
||||
locationId:0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
},
|
||||
{
|
||||
$unwind: {
|
||||
path: "$stock",
|
||||
preserveNullAndEmptyArrays: true
|
||||
}
|
||||
},
|
||||
{
|
||||
$addFields: { id: "$_id" }
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
id: 1,
|
||||
_id: 0,
|
||||
stock: 1,
|
||||
batchNumber: 1,
|
||||
area: 1,
|
||||
quantity: 1,
|
||||
articleVariant: 1,
|
||||
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
return stockContent;
|
||||
return this.stockContentModel.aggregate<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) {
|
||||
const item = await this.stockContentModel.findById(id);
|
||||
if (!item) throw new NotFoundException('Stock Content nicht gefunden');
|
||||
return item;
|
||||
}
|
||||
|
||||
|
||||
remove(id: string) {
|
||||
return this.stockContentRepo.remove(id);
|
||||
}
|
||||
|
||||
|
||||
//--- Stock IN
|
||||
async moveIn(dto: StockMovementInDto): Promise<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,
|
||||
}
|
||||
|
||||
if (isConsumable) {
|
||||
return await this.stockContentRepo.moveConsumableIn(moveData);
|
||||
} else {
|
||||
return await this.stockContentRepo.moveNonConsumableIn(moveData);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
//--- Stock OUT
|
||||
moveOut(dto: StockMovementOutDto) {
|
||||
return this.stockContentRepo.moveOut(dto);
|
||||
}
|
||||
|
||||
|
||||
//--- Stock Transfer
|
||||
async transfer(dto: StockMovementTransferDto) {
|
||||
|
||||
const articleVariant = await this.articleVariantService.findOne(dto.articleVariantId);
|
||||
const avId = articleVariant._id.toString();
|
||||
const isConsumable = articleVariant.article.category.isConsumable;
|
||||
|
||||
this.stockContentRepo.transfer(dto, isConsumable);
|
||||
|
||||
return {
|
||||
articleVariant,
|
||||
isConsumable,
|
||||
}
|
||||
|
||||
}
|
||||
constructor(
|
||||
@InjectModel(StockContent.name) private readonly model: Model<StockContent>,
|
||||
private readonly repository: StockContentRepository,
|
||||
) {}
|
||||
findAll() {
|
||||
return this.model
|
||||
.find({ articleId: { $exists: true } })
|
||||
.populate('articleId')
|
||||
.populate({ path: 'stockId', populate: { path: 'locationId' } })
|
||||
.populate('batchId')
|
||||
.populate('assetId')
|
||||
.exec();
|
||||
}
|
||||
async findOne(id: string) {
|
||||
if (!Types.ObjectId.isValid(id))
|
||||
throw new BadRequestException('Ungültige Bestands-ID');
|
||||
const item = await this.model
|
||||
.findById(id)
|
||||
.populate('articleId')
|
||||
.populate('batchId')
|
||||
.populate('assetId')
|
||||
.exec();
|
||||
if (!item) throw new NotFoundException('Bestand nicht gefunden');
|
||||
return item;
|
||||
}
|
||||
remove(_id: string): never {
|
||||
throw new BadRequestException('Bestände nur über Auslagerungen verändern');
|
||||
}
|
||||
moveIn(dto: StockMovementInDto, session: ClientSession) {
|
||||
return this.repository.moveIn(dto, session);
|
||||
}
|
||||
moveOut(dto: StockMovementOutDto, session: ClientSession) {
|
||||
return this.repository.moveOut(dto, session);
|
||||
}
|
||||
transfer(dto: StockMovementTransferDto, session: ClientSession) {
|
||||
return this.repository.transfer(dto, session);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { Stock, StockSchema } from '../_entities/stock.entity';
|
||||
import { StockController } from '../_controllers/stock.controller';
|
||||
import { StockService } from './stock.service';
|
||||
import { LocationsModule } from 'src/locations/locations.module';
|
||||
import { LocationsModule } from '../../locations/locations.module';
|
||||
|
||||
|
||||
@Module({
|
||||
|
||||
@@ -5,7 +5,7 @@ import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model, Types } from 'mongoose';
|
||||
import { Stock } from '../_entities/stock.entity';
|
||||
import { StockCreateDto, StockDto, StockRowDto, StockUpdateDto } from '../_dto/stock.dto';
|
||||
import { LocationsService } from 'src/locations/locations.service';
|
||||
import { LocationsService } from '../../locations/locations.service';
|
||||
|
||||
|
||||
@Injectable()
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Types } from 'mongoose';
|
||||
|
||||
export class LocationCreateDto {
|
||||
@IsString()
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@@ -20,32 +20,32 @@ export class LocationUpdateDto extends PartialType(LocationCreateDto) { }
|
||||
|
||||
export class LocationNodeDto {
|
||||
@IsString()
|
||||
_id: Types.ObjectId;
|
||||
_id!: Types.ObjectId;
|
||||
|
||||
@IsString()
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
|
||||
parentLocationId: Types.ObjectId;
|
||||
children: LocationNodeDto[];
|
||||
parentLocationId?: Types.ObjectId;
|
||||
children!: LocationNodeDto[];
|
||||
}
|
||||
|
||||
export class LocationDto {
|
||||
id: string;
|
||||
name: string;
|
||||
id!: string;
|
||||
name!: string;
|
||||
parentLocation?: LocationViewDto;
|
||||
children?: LocationViewDto[];
|
||||
}
|
||||
|
||||
export class LocationViewDto {
|
||||
id: string;
|
||||
name: string;
|
||||
id!: string;
|
||||
name!: string;
|
||||
parentLocation?: string;
|
||||
}
|
||||
|
||||
export class LocationRawDto {
|
||||
_id: string;
|
||||
name: string;
|
||||
_id!: string;
|
||||
name!: string;
|
||||
parentLocationId?: Types.ObjectId;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@ import { Document, Types } from 'mongoose';
|
||||
@Schema({ timestamps: true })
|
||||
export class Location extends Document {
|
||||
@Prop({ required: true })
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
@Prop()
|
||||
description?: string;
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'Location' })
|
||||
parentLocationId: Types.ObjectId
|
||||
parentLocationId?: Types.ObjectId
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ export class LocationsService {
|
||||
|
||||
return this.locationModel.create({
|
||||
name,
|
||||
parentLocationId: new Types.ObjectId(parentLocationId),
|
||||
...(parentLocationId ? { parentLocationId: new Types.ObjectId(parentLocationId) } : {}),
|
||||
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) {}
|
||||
+5
-5
@@ -4,17 +4,17 @@ import { ArticleDto } from './article.dto';
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
|
||||
export class ArticleVariantDto {
|
||||
_id: Types.ObjectId;
|
||||
article: ArticleDto;
|
||||
manufacturer: ManufacturerDto;
|
||||
_id!: Types.ObjectId;
|
||||
article!: ArticleDto;
|
||||
manufacturer!: ManufacturerDto;
|
||||
supplierArticleNumber?: string;
|
||||
packagingUnit?: string;
|
||||
extra?: Record<string, any>;
|
||||
}
|
||||
|
||||
export class ArticleVariantCreateDto {
|
||||
articleId: Types.ObjectId;
|
||||
manufacturerId: Types.ObjectId;
|
||||
articleId!: Types.ObjectId;
|
||||
manufacturerId!: Types.ObjectId;
|
||||
supplierArticleNumber?: string;
|
||||
packagingUnit?: string;
|
||||
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;
|
||||
}
|
||||
+5
-5
@@ -2,8 +2,8 @@ import { PartialType } from "@nestjs/mapped-types";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
export class CategoryCreateDto {
|
||||
name: string;
|
||||
isConsumable: boolean;
|
||||
name!: string;
|
||||
isConsumable!: boolean;
|
||||
description?: string;
|
||||
requiredAttributes?: Record<string, any>;
|
||||
parentCategoryId?: Types.ObjectId;
|
||||
@@ -13,9 +13,9 @@ export class CategoryCreateDto {
|
||||
export class CategoryUpdateDto extends PartialType(CategoryCreateDto) {}
|
||||
|
||||
export class CategoryDto {
|
||||
_id: Types.ObjectId;
|
||||
name: string;
|
||||
isConsumable: boolean;
|
||||
_id!: Types.ObjectId;
|
||||
name!: string;
|
||||
isConsumable!: boolean;
|
||||
description?: string;
|
||||
requiredAttributes?: Record<string, any>;
|
||||
parentCategoryId?: Types.ObjectId;
|
||||
+4
-4
@@ -3,17 +3,17 @@ import { Types } from "mongoose";
|
||||
|
||||
export class ManufacturerCreateDto {
|
||||
@IsString()
|
||||
name: string;
|
||||
name!: string;
|
||||
}
|
||||
|
||||
export class ManufacturerDto {
|
||||
_id: Types.ObjectId;
|
||||
name: string;
|
||||
_id!: Types.ObjectId;
|
||||
name!: string;
|
||||
}
|
||||
|
||||
|
||||
export class ManufacturerUpdateDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name: string;
|
||||
name?: string;
|
||||
}
|
||||
@@ -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);
|
||||
+2
-2
@@ -4,10 +4,10 @@ import { Document, Types } from 'mongoose';
|
||||
@Schema()
|
||||
export class ArticleVariant extends Document {
|
||||
@Prop({ type: Types.ObjectId, ref: 'Article', required: true })
|
||||
articleId: Types.ObjectId;
|
||||
articleId!: Types.ObjectId;
|
||||
|
||||
@Prop({ type: Types.ObjectId, ref: 'Manufacturer', required: true })
|
||||
manufacturerId: Types.ObjectId;
|
||||
manufacturerId!: Types.ObjectId;
|
||||
|
||||
@Prop()
|
||||
supplierArticleNumber?: string;
|
||||
@@ -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 });
|
||||
+2
-2
@@ -5,13 +5,13 @@ import { Document, Types } from 'mongoose';
|
||||
@Schema({ timestamps: true })
|
||||
export class Category extends Document {
|
||||
@Prop({ required: true })
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
@Prop()
|
||||
description?: string;
|
||||
|
||||
@Prop({ default: true })
|
||||
isConsumable: boolean;
|
||||
isConsumable!: boolean;
|
||||
|
||||
@Prop({ type: Map, of: String })
|
||||
requiredAttributes?: Map<string, string>;
|
||||
+1
-1
@@ -5,7 +5,7 @@ import { Document, Types } from 'mongoose';
|
||||
@Schema()
|
||||
export class Manufacturer extends Document {
|
||||
@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();
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+3
-3
@@ -1,10 +1,10 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model, Types } from 'mongoose';
|
||||
import { ArticleVariantCreateDto, ArticleVariantDto, ArticleVariantUpdateDto } from 'src/catalog/_dto/article-variant.dto';
|
||||
import { ArticleVariant } from 'src/catalog/_entities/article-variant.entity';
|
||||
import { ArticleVariantCreateDto, ArticleVariantDto, ArticleVariantUpdateDto } from '../../_dto/article-variant.dto';
|
||||
import { ArticleVariant } from '../../_entities/article-variant.entity';
|
||||
import { articleVariantGetQuery } from '../querys/article-variant-get.query';
|
||||
import { ArticleVariantUpsertDto } from 'src/catalog/_dto/upsert-article.dto';
|
||||
import { ArticleVariantUpsertDto } from '../../_dto/upsert-article.dto';
|
||||
import { BulkWriteResult } from 'mongodb';
|
||||
|
||||
@Injectable()
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
+20
-14
@@ -1,19 +1,24 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
} from '@nestjs/common';
|
||||
import { ArticlesService } from './articles.service';
|
||||
|
||||
|
||||
import { ArticleCreateDto, ArticleUpdateDto } from '../_dto/article.dto';
|
||||
import { ArticleCreateDto, ArticleUpdateDto } from '../_dto/article.dto';
|
||||
import { ArticleUpsertDto } from '../_dto/upsert-article.dto';
|
||||
|
||||
@Controller('articles')
|
||||
export class ArticlesController {
|
||||
constructor(
|
||||
private readonly articlesService: ArticlesService,
|
||||
) { }
|
||||
constructor(private readonly articlesService: ArticlesService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() dto: ArticleCreateDto) {
|
||||
console.log('Create Artikel')
|
||||
console.log('Create Artikel');
|
||||
return this.articlesService.create(dto);
|
||||
}
|
||||
|
||||
@@ -22,23 +27,24 @@ export class ArticlesController {
|
||||
return this.articlesService.findAll();
|
||||
}
|
||||
|
||||
@Get('migration-status')
|
||||
migrationStatus() {
|
||||
return this.articlesService.migrationStatus();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
console.log('Find one')
|
||||
console.log('Find one');
|
||||
return this.articlesService.findOne(id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id') id: string, @Body() updateArticleDto: ArticleUpsertDto) {
|
||||
update(@Param('id') id: string, @Body() updateArticleDto: ArticleUpsertDto) {
|
||||
return this.articlesService.update(id, updateArticleDto);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.articlesService.remove(id);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+8
-14
@@ -1,22 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ArticlesService } from './articles.service';
|
||||
import { ArticlesController } from './articles.controller';
|
||||
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { Article, ArticleSchema } from '../_entities/article.entity';
|
||||
import { ArticleVariantModule } from '../article-variant/article-variant.module';
|
||||
import { ArticlesService } from './articles.service';
|
||||
import { ArticlesController } from './articles.controller';
|
||||
import { ArticleRepository } from './repository/article.repository';
|
||||
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MongooseModule.forFeature([
|
||||
{ name: Article.name, schema: ArticleSchema },
|
||||
]),
|
||||
ArticleVariantModule
|
||||
],
|
||||
imports: [
|
||||
MongooseModule.forFeature([{ name: Article.name, schema: ArticleSchema }]),
|
||||
],
|
||||
controllers: [ArticlesController],
|
||||
providers: [ArticlesService,ArticleRepository],
|
||||
exports:[ArticlesService]
|
||||
providers: [ArticlesService, ArticleRepository],
|
||||
exports: [ArticlesService],
|
||||
})
|
||||
export class ArticlesModule { }
|
||||
export class ArticlesModule {}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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 {
|
||||
@IsString()
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
@IsEmail()
|
||||
email: string;
|
||||
email!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -4,10 +4,10 @@ import { Document } from 'mongoose';
|
||||
@Schema()
|
||||
export class User extends Document {
|
||||
@Prop({ required: true })
|
||||
name: string;
|
||||
name!: string;
|
||||
|
||||
@Prop({ required: true, unique: true })
|
||||
email: string;
|
||||
email!: string;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts", "scripts"]
|
||||
}
|
||||
@@ -13,7 +13,9 @@
|
||||
"target": "ES2023",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": true,
|
||||
|
||||
@@ -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"]
|
||||
}
|
||||
Reference in new issue
Block a user