jagd-apps/nachsuche/backend/seed.js

115 lines
4.6 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const mongoose = require('mongoose');
const User = require('./models/User');
const Admin = require('./models/Admin');
const Config = require('./models/Config');
const config = require('./config/env');
const logger = require('./utils/logger');
// NOTE: Real handler data must be entered via the admin panel after first deployment.
// Seed only creates the admin account and app configuration.
// To avoid storing personal data in version control, this array is intentionally empty.
const users = [];
const seedDatabase = async () => {
try {
await mongoose.connect(config.mongoUri);
logger.info('MongoDB verbunden für Seeding...');
// Seed users - only if collection is empty (idempotent)
const existingUserCount = await User.countDocuments();
if (existingUserCount === 0) {
await User.insertMany(users);
logger.info(`${users.length} Nachsuchenführer wurden erstellt`);
} else {
logger.info(` Benutzer bereits vorhanden (${existingUserCount}), überspringe Seeding`);
}
// Seed admins (only if not exists)
const adminAccounts = [
{ username: 'admin', passwordEnvVar: 'ADMIN_PASSWORD', defaultPassword: process.env.ADMIN_PASSWORD || null },
{ username: 'ThorstenMeyer', passwordEnvVar: 'ADMIN_THORSTEN_PASSWORD', defaultPassword: process.env.ADMIN_THORSTEN_PASSWORD || null }
];
let adminId;
for (const account of adminAccounts) {
const existing = await Admin.findOne({ username: account.username });
if (!existing) {
const pw = process.env[account.passwordEnvVar] || account.defaultPassword;
if (!pw) {
logger.warn(`⚠️ Kein Passwort für ${account.username} konfiguriert, überspringe`);
continue;
}
const created = await Admin.create({ username: account.username, password: pw });
adminId = created._id;
logger.info(`✅ Admin-Benutzer erstellt: ${account.username}`);
} else {
adminId = existing._id;
logger.info(` Admin-Benutzer existiert bereits: ${account.username}`);
}
}
if (!adminId) {
const fallback = await Admin.findOne();
adminId = fallback?._id;
}
// Seed config - always update userTypes + sections + rules
const existingConfig = await Config.findOne();
const configData = {
userTypes: [
{ code: 'HS', label: 'Hannoverscher Schweißhund' },
{ code: 'BGS', label: 'Bayerischer Gebirgsschweißhund' },
{ code: 'SB', label: 'Schweißhund (allgemein)' },
{ code: 'LAB', label: 'Labrador' }
],
rules: [
"Verbreiten Sie den Standort und den Anschuss.",
"Vertreten Sie keine Pirschzeichen.",
"Versuchen Sie die Nachsuche möglichst nicht erst mit ungeübten Hunden.",
"Benachrichtigen Sie unverzüglich den Nachsuchenführer und die evtl. betroffenen Revierinhaber der Nachbarjagdbezirke.",
"Der Hundeführer gibt den Fangschuss auf das gestellte Stück ab.",
"Bei der Nachsuche hat der Hundeführer die Stellung eines Jagdleiters.",
"Der anfordernde Revierinhaber muss die betroffenen Nachbarreviere verständigen.",
"Auf Empfehlung der Jägerschaften Soltau und Fallingbostel ist bei Inanspruchnahme eine pauschale Aufwandsentschädigung an den Nachsuchenführer von 50,00 € zu entrichten."
],
appName: 'Nachsuchenstation Heidekreis',
sections: [
{
key: 'ueber-uns',
title: 'Die Nachsuchenstation Heidekreis',
content: '[Inhalt folgt wird durch den Admin ergänzt]'
},
{
key: 'anwendung',
title: 'Anwendung der App',
content: '[Erklärung für den Anwender folgt wird durch den Admin ergänzt]'
},
{
key: 'ansprechpartner',
title: 'Ansprechpartner und Koordination',
content: 'Ansprechpartner und Koordination der Nachsuchenstation Heidekreis\n\nMarc Sonnemann\nHamwiede 5 b\n29664 Walsrode\n\nTel. 01725170049 / 051684802922\nMail: nachsuchenstation-hk@jaegerschaft-fallingbostel.de'
}
],
updatedBy: adminId
};
if (!existingConfig) {
await Config.create(configData);
logger.info('✅ Konfiguration erstellt');
} else {
await Config.findOneAndUpdate({}, configData, { new: true });
logger.info('✅ Konfiguration aktualisiert');
}
logger.info('✅ Datenbank-Seeding abgeschlossen');
await mongoose.connection.close();
process.exit(0);
} catch (error) {
logger.error('❌ Fehler beim Seeding:', error);
await mongoose.connection.close();
process.exit(1);
}
};
seedDatabase();