jagd-apps/stoeberhunde/backend/seed.js

108 lines
3.8 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');
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} Stöberhundefü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: 'SH', label: 'Stöberhundleiter' },
{ code: 'BSH', label: 'Begleithund' },
{ code: 'SHK', label: 'Stöberhund kombiniert' }
],
rules: [
"Informieren Sie den Revierinhaber vor jedem Einsatz.",
"Der Stöberhundleiter ist verantwortlich für den sicheren Einsatz seines Hundes.",
"Halten Sie die vereinbarten Gebietsabgrenzungen ein.",
"Melden Sie das Ergebnis unverzüglich an den Revierinhaber.",
"Bei Inanspruchnahme ist eine pauschale Aufwandsentschädigung zu entrichten."
],
appName: 'Stöberhunde Heidekreis',
sections: [
{
key: 'ueber-uns',
title: 'Die Stöberhunde 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 folgt wird durch den Admin ergänzt]'
}
],
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();