/** Read-only unless --apply is explicitly passed. Never imported by the application. */ import { readFileSync } from 'node:fs'; import mongoose, { Types } from 'mongoose'; type TrackingMode = 'quantity' | 'batch' | 'individual'; interface ArticleSettings { articleNumber: string; name?: string; manufacturerArticleNumber?: string; barcode?: string; baseUnit: string; isConsumable: boolean; trackingMode: TrackingMode; tracksExpiryDate: boolean; packaging?: { name: string; quantityInBaseUnits: number; barcode?: string }[]; } interface Review { articles: Record; movements?: Record; } interface LegacyArticle { _id: Types.ObjectId; name: string; categoryId?: Types.ObjectId; attributes?: Record; articleNumber?: string; } interface LegacyVariant { _id: Types.ObjectId; articleId: Types.ObjectId; manufacturerId?: Types.ObjectId; supplierArticleNumber?: string; packagingUnit?: string; extra?: Record; } interface LegacyContent { _id: Types.ObjectId; articleVariantId?: Types.ObjectId; stockId: Types.ObjectId; quantity: number; batchNumber?: string; expiryDate?: Date; area?: string; articleId?: Types.ObjectId; } interface LegacyMovement { _id: Types.ObjectId; articleVariantId?: Types.ObjectId; stockId: Types.ObjectId; type: string; meta?: { fromLocationId?: Types.ObjectId; toLocationId?: Types.ObjectId }; articleId?: Types.ObjectId; } interface ConcreteArticle extends ArticleSettings { _id: Types.ObjectId; categoryId?: Types.ObjectId; groupId?: Types.ObjectId; manufacturerId?: Types.ObjectId; manufacturerArticleNumber?: string; attributes: Record; archivedAt: null; } async function main() { const uri = process.env.MONGODB_URI; const reviewPath = process.argv .find((argument) => argument.startsWith('--review=')) ?.slice('--review='.length); if (!uri || !reviewPath) throw new Error( 'MONGODB_URI und --review=/pfad/review.json sind erforderlich', ); const review = JSON.parse(readFileSync(reviewPath, 'utf8')) as Review; if (!review.articles || typeof review.articles !== 'object') throw new Error('review.articles fehlt'); const apply = process.argv.includes('--apply'); await mongoose.connect(uri, { autoIndex: false }); try { const connection = mongoose.connection; const [articles, variants, contents, movements, stocks] = await Promise.all( [ connection.collection('articles').find().toArray(), connection .collection('articlevariants') .find() .toArray(), connection.collection('stockcontents').find().toArray(), connection .collection('stockmovements') .find() .toArray(), connection.collection('stocks').find().toArray(), ], ); const articleMap = new Map( articles.map((article) => [article._id.toString(), article]), ); const variantMap = new Map( variants.map((variant) => [variant._id.toString(), variant]), ); const stockIds = new Set(stocks.map((stock) => stock._id.toString())); const blockers: string[] = []; const plannedArticles: ConcreteArticle[] = []; const groups = new Map(); const plan = ( id: Types.ObjectId, parent: LegacyArticle, variant?: LegacyVariant, ) => { if (articleMap.get(id.toString())?.articleNumber) return; const settings = review.articles[id.toString()]; if (!settings) { blockers.push( `Artikel ${id}: Einheit und Bestandsregeln fehlen im Review (${parent.name})`, ); return; } if ( !settings.articleNumber?.trim() || !settings.baseUnit?.trim() || typeof settings.isConsumable !== 'boolean' || typeof settings.tracksExpiryDate !== 'boolean' || !['quantity', 'batch', 'individual'].includes(settings.trackingMode) || (settings.tracksExpiryDate && settings.trackingMode !== 'batch') ) { blockers.push(`Artikel ${id}: ungültige Einstellungen`); return; } if (settings.trackingMode === 'individual') { blockers.push( `Artikel ${id}: bestehende Einzelstücke müssen zuerst separat mit Inventarnummern zugeordnet werden; zunächst quantity verwenden`, ); return; } const attributes = { ...parent.attributes, ...variant?.extra, ...(variant?.supplierArticleNumber ? { legacySupplierArticleNumber: variant.supplierArticleNumber } : {}), }; if ( Object.entries(attributes).some( ([key, value]) => key.includes('.') || key.startsWith('$') || ['__proto__', 'constructor', 'prototype'].includes(key) || !['string', 'number', 'boolean'].includes(typeof value), ) ) { blockers.push( `Artikel ${id}: Eigenschaften müssen vor der Migration auf einfache Werte bereinigt werden`, ); } if ( settings.packaging?.some( (item) => !item.name?.trim() || !Number.isFinite(item.quantityInBaseUnits) || item.quantityInBaseUnits <= 0, ) ) { blockers.push(`Artikel ${id}: Verpackungen sind ungültig`); } if ( variant && articleMap.has(id.toString()) && !articleMap.get(id.toString())?.articleNumber ) { blockers.push( `Artikel ${id}: Varianten-ID kollidiert mit einer bisherigen Artikel-ID`, ); } if (variant) groups.set(parent._id.toString(), { _id: parent._id, name: parent.name, }); plannedArticles.push({ _id: id, articleNumber: settings.articleNumber.trim(), name: settings.name ?? parent.name, baseUnit: settings.baseUnit.trim(), isConsumable: settings.isConsumable, trackingMode: settings.trackingMode, tracksExpiryDate: settings.tracksExpiryDate, packaging: settings.packaging ?? [], categoryId: parent.categoryId, manufacturerArticleNumber: settings.manufacturerArticleNumber, barcode: settings.barcode, ...(variant ? { groupId: parent._id, manufacturerId: variant.manufacturerId } : {}), attributes, archivedAt: null, }); if (variant?.packagingUnit && !settings.packaging) { blockers.push( `Artikel ${id}: bisherige Verpackung "${variant.packagingUnit}" muss im Review strukturiert angegeben werden`, ); } }; for (const variant of variants) { const parent = articleMap.get(variant.articleId.toString()); if (!parent) blockers.push(`Variante ${variant._id}: übergeordneter Artikel fehlt`); else plan(variant._id, parent, variant); } const parentIds = new Set( variants.map((variant) => variant.articleId.toString()), ); for (const article of articles) { if (!article.articleNumber && !parentIds.has(article._id.toString())) plan(article._id, article); } const concrete = new Map([ ...articles .filter((article) => article.articleNumber) .map( (article) => [ article._id.toString(), article as unknown as ArticleSettings, ] as const, ), ...plannedArticles.map( (article) => [article._id.toString(), article] as const, ), ]); const numbers = new Set(); for (const settings of concrete.values()) { if (numbers.has(settings.articleNumber)) blockers.push(`Doppelte Artikelnummer ${settings.articleNumber}`); numbers.add(settings.articleNumber); } const batches = new Map< string, { _id: Types.ObjectId; articleId: Types.ObjectId; batchNumber: string; expiryDate?: Date; } >(); const migratedContent: { _id: Types.ObjectId; articleId: Types.ObjectId; batchId: Types.ObjectId | null; area: string; }[] = []; const positionKeys = new Set( contents .filter((content) => content.articleId) .map( (content) => `${content.articleId}:${content.stockId}:${(content as unknown as { batchId?: Types.ObjectId }).batchId ?? ''}:${content.area ?? ''}`, ), ); for (const content of contents) { if (content.articleId) continue; const id = content.articleVariantId; const settings = id && concrete.get(id.toString()); if ( !id || !settings || !stockIds.has(content.stockId.toString()) || !Number.isFinite(content.quantity) || content.quantity <= 0 ) { blockers.push( `Bestand ${content._id}: Referenz, Lager oder Menge ist ungültig`, ); continue; } let batchId: Types.ObjectId | null = null; if (settings.trackingMode === 'batch') { if ( !content.batchNumber?.trim() || (settings.tracksExpiryDate && !content.expiryDate) ) { blockers.push( `Bestand ${content._id}: Chargennummer oder Ablaufdatum fehlt`, ); continue; } if (content.expiryDate && !settings.tracksExpiryDate) { blockers.push( `Bestand ${content._id}: vorhandenes Ablaufdatum erfordert tracksExpiryDate=true`, ); continue; } const key = `${id}:${content.batchNumber.trim()}`; let batch = batches.get(key); if ( batch && batch.expiryDate?.getTime() !== content.expiryDate?.getTime() ) { blockers.push(`Charge ${key}: widersprüchliche Ablaufdaten`); continue; } if (!batch) { batch = { _id: new Types.ObjectId(), articleId: id, batchNumber: content.batchNumber.trim(), ...(settings.tracksExpiryDate ? { expiryDate: content.expiryDate } : {}), }; batches.set(key, batch); } batchId = batch._id; } else if (content.batchNumber || content.expiryDate) { blockers.push( `Bestand ${content._id}: vorhandene Chargeninformationen erfordern Chargenführung`, ); continue; } const positionKey = `${id}:${content.stockId}:${batchId ?? ''}:${content.area ?? ''}`; if (positionKeys.has(positionKey)) blockers.push( `Bestand ${content._id}: doppelte Bestandsposition; zuerst konsolidieren`, ); positionKeys.add(positionKey); migratedContent.push({ _id: content._id, articleId: id, batchId, area: content.area ?? '', }); } const migratedMovements: { _id: Types.ObjectId; articleId: Types.ObjectId; stockId: Types.ObjectId; toStockId?: Types.ObjectId; }[] = []; for (const movement of movements) { if (movement.articleId) continue; const override = review.movements?.[movement._id.toString()]; const articleId = override ? new Types.ObjectId(override.articleId) : movement.articleVariantId; const stockId = override ? new Types.ObjectId(override.stockId) : movement.stockId; if ( !articleId || !concrete.has(articleId.toString()) || !stockIds.has(stockId.toString()) || (!variantMap.has(articleId.toString()) && !override) ) { blockers.push( `Bewegung ${movement._id}: alte Referenzen sind ungültig; review.movements benötigt articleId und stockId`, ); continue; } const toStockId = movement.type === 'TRANSFER' ? movement.meta?.toLocationId : undefined; if ( movement.type === 'TRANSFER' && (!toStockId || !stockIds.has(toStockId.toString())) ) { blockers.push( `Bewegung ${movement._id}: Ziellager fehlt oder ist ungültig`, ); continue; } migratedMovements.push({ _id: movement._id, articleId, stockId, ...(toStockId ? { toStockId } : {}), }); } console.log( JSON.stringify( { mode: apply ? 'apply' : 'preview', articles: plannedArticles, groups: [...groups.values()], contents: migratedContent.length, movements: migratedMovements.length, blockers, }, null, 2, ), ); if (blockers.length) throw new Error( 'Migration blockiert. Review und bestehende Daten korrigieren; keine Änderungen ausgeführt.', ); if (!apply) return; await connection.transaction(async (session) => { for (const [collection, rows] of [ ['articles', articles], ['articlevariants', variants], ['stockcontents', contents], ['stockmovements', movements], ] as const) { for (const row of rows) await connection .collection(`migration_backup_${collection}`) .updateOne( { _id: row._id }, { $setOnInsert: row }, { upsert: true, session }, ); } for (const group of groups.values()) await connection .collection('articlegroups') .updateOne( { _id: group._id }, { $setOnInsert: group }, { upsert: true, session }, ); for (const group of groups.values()) await connection .collection('articles') .updateOne( { _id: group._id }, { $set: { legacyGrouping: true } }, { session }, ); for (const article of plannedArticles) { const { _id, ...values } = article; await connection .collection('articles') .updateOne({ _id }, { $set: values }, { upsert: true, session }); } for (const batch of batches.values()) await connection.collection('batches').insertOne(batch, { session }); for (const content of migratedContent) { const { _id, ...values } = content; await connection.collection('stockcontents').updateOne( { _id }, { $set: { ...values, assetId: null }, $unset: { articleVariantId: '', batchNumber: '', expiryDate: '' }, }, { session }, ); } for (const movement of migratedMovements) { const { _id, ...values } = movement; await connection.collection('stockmovements').updateOne( { _id }, { $set: values, $unset: { articleVariantId: '' }, }, { session }, ); } }); console.log( 'Migration abgeschlossen. Legacy-Datensätze und Sicherungskopien bleiben erhalten.', ); } finally { await mongoose.disconnect(); } } main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; });