- Campaigns: DM can archive/restore; owner can delete. Archived campaigns move off the main list and stop accepting invite codes. - Encounters: DM can archive/restore and delete, and arrange the campaign's own order; the list can also be sorted by name, status, type or date. Archived encounters are hidden from players' lists. - Account page with change password (POST /auth/password). - Seed is now additive (safe on a live database; --reset for the old wipe) and builds a fuller Aldenfell: earned weapons, item pool, spells, NPCs, and 28 battle/quest scenes with descriptions, DM notes and rewards. - Vite preview host config for the deployed site. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
208 lines
8.3 KiB
JavaScript
208 lines
8.3 KiB
JavaScript
// Seeds the Aldenfell campaign (seed-data/aldenfell.js) for the admin account.
|
|
//
|
|
// Safe to run against a live database: it only ever ADDS. The admin account is
|
|
// created if it is missing (an existing one, and its password, is left alone),
|
|
// and the campaign is added unless that account already owns an active
|
|
// campaign of the same name. To get a fresh copy, archive or delete the old
|
|
// one in the app and run the seed again.
|
|
//
|
|
// npx prisma db seed add what is missing
|
|
// npx prisma db seed -- --reset DESTRUCTIVE: delete every user, campaign,
|
|
// character, note, etc. first
|
|
//
|
|
// SEED_ADMIN_EMAIL / SEED_ADMIN_PASSWORD / SEED_ADMIN_NAME override the
|
|
// account that is created.
|
|
//
|
|
// Species/classes/skills are NOT seeded as rows — they're fixed game-rule
|
|
// tables ported into src/game/data/*.js, as is the default weapon/spell/monster
|
|
// library DMs pull from. The default weapons (seed-data/weapons.json) ARE
|
|
// seeded, into the campaign, since weapons are per-campaign in the schema.
|
|
const path = require('path');
|
|
const bcrypt = require('bcrypt');
|
|
const { PrismaClient } = require('@prisma/client');
|
|
const { generateInviteCode } = require('../src/utils/inviteCode');
|
|
const { SPELL_LIBRARY } = require('../src/game/data/library');
|
|
|
|
const prisma = new PrismaClient();
|
|
const defaultWeapons = require(path.join(__dirname, '..', 'seed-data', 'weapons.json'));
|
|
const aldenfell = require(path.join(__dirname, '..', 'seed-data', 'aldenfell.js'));
|
|
|
|
const ADMIN_EMAIL = process.env.SEED_ADMIN_EMAIL || 'joshua@crosscode.co.za';
|
|
const ADMIN_PASSWORD = process.env.SEED_ADMIN_PASSWORD || '12345678';
|
|
const ADMIN_NAME = process.env.SEED_ADMIN_NAME || 'Joshua';
|
|
const RESET = process.argv.includes('--reset');
|
|
|
|
async function resetDatabase() {
|
|
// Truncating the two roots cascades through every table that references them.
|
|
await prisma.$executeRawUnsafe('TRUNCATE TABLE "users", "campaigns" RESTART IDENTITY CASCADE');
|
|
}
|
|
|
|
// Notes list newest-first on screen, so they are stamped a second apart,
|
|
// backwards: the first entry in the seed data is the one at the top.
|
|
function bookOrder(index) {
|
|
return new Date(Date.now() - index * 1000);
|
|
}
|
|
|
|
function byName(rows) {
|
|
return new Map(rows.map((row) => [row.name, row]));
|
|
}
|
|
|
|
function lookup(map, name, what, encounterName) {
|
|
const row = map.get(name);
|
|
if (!row) throw new Error(`Encounter "${encounterName}" references unknown ${what} "${name}"`);
|
|
return row;
|
|
}
|
|
|
|
async function seedCampaign(db, admin) {
|
|
const campaign = await db.campaign.create({
|
|
data: {
|
|
...aldenfell.campaign,
|
|
inviteCode: generateInviteCode(),
|
|
ownerId: admin.id,
|
|
members: { create: { userId: admin.id, role: 'DM' } },
|
|
},
|
|
});
|
|
const campaignId = campaign.id;
|
|
|
|
await db.location.createMany({ data: aldenfell.locations.map((l) => ({ ...l, campaignId })) });
|
|
|
|
// Everyday weapons are what a new character picks from; the rest are earned.
|
|
await db.weapon.createMany({
|
|
data: [
|
|
...defaultWeapons.map((w) => ({ ...w, isStartingOption: true, campaignId })),
|
|
...aldenfell.weapons.map((w) => ({ ...w, campaignId })),
|
|
],
|
|
});
|
|
await db.item.createMany({
|
|
data: aldenfell.items.map(({ starting, ...item }) => ({ ...item, isStartingOption: Boolean(starting), campaignId })),
|
|
});
|
|
|
|
const spellRow = (isStartingOption) => (spellKey) => {
|
|
const template = SPELL_LIBRARY.find((s) => s.key === spellKey);
|
|
if (!template) throw new Error(`Unknown library spell "${spellKey}"`);
|
|
const { key, classes, ...spell } = template;
|
|
return { ...spell, isStartingOption, campaignId };
|
|
};
|
|
const spells = [...aldenfell.spells.starting.map(spellRow(true)), ...aldenfell.spells.earned.map(spellRow(false))];
|
|
await db.spell.createMany({ data: spells });
|
|
|
|
await db.monster.createMany({ data: aldenfell.monsters.map((m) => ({ ...m, campaignId })) });
|
|
await db.npc.createMany({ data: aldenfell.npcs.map((n) => ({ ...n, campaignId })) });
|
|
|
|
const monsters = byName(await db.monster.findMany({ where: { campaignId } }));
|
|
const npcs = byName(await db.npc.findMany({ where: { campaignId } }));
|
|
const weapons = byName(await db.weapon.findMany({ where: { campaignId } }));
|
|
const items = byName(await db.item.findMany({ where: { campaignId } }));
|
|
|
|
let rewardCount = 0;
|
|
for (const [index, enc] of aldenfell.encounters.entries()) {
|
|
const participants = [];
|
|
for (const [name, count, displayName] of enc.monsters || []) {
|
|
const monster = lookup(monsters, name, 'monster', enc.name);
|
|
const label = displayName || monster.name;
|
|
for (let i = 1; i <= count; i++) {
|
|
participants.push({
|
|
monsterId: monster.id,
|
|
displayName: count > 1 ? `${label} #${i}` : label,
|
|
currentHp: monster.maxHp,
|
|
maxHp: monster.maxHp,
|
|
isMonster: true,
|
|
});
|
|
}
|
|
}
|
|
for (const name of enc.npcs || []) {
|
|
const npc = lookup(npcs, name, 'NPC', enc.name);
|
|
// An NPC with no combat stats takes part with no hit points to track.
|
|
participants.push({ npcId: npc.id, displayName: npc.name, currentHp: npc.maxHp ?? 0, maxHp: npc.maxHp ?? 0, isMonster: false });
|
|
}
|
|
|
|
// Rewards list oldest-first, so these are stamped forwards.
|
|
const rewards = (enc.rewards || []).map(({ gold, weapon, item, quantity = 1, level, note }, i) => {
|
|
const createdAt = new Date(Date.now() + i);
|
|
if (gold) return { type: 'GOLD', gold, note, createdAt };
|
|
const entry = weapon ? lookup(weapons, weapon, 'weapon', enc.name) : lookup(items, item, 'item', enc.name);
|
|
return {
|
|
type: weapon ? 'WEAPON' : 'ITEM',
|
|
[weapon ? 'weaponId' : 'itemId']: entry.id,
|
|
quantity,
|
|
level: Math.max(level ?? entry.minLevel, entry.minLevel),
|
|
note,
|
|
createdAt,
|
|
};
|
|
});
|
|
rewardCount += rewards.length;
|
|
|
|
await db.encounter.create({
|
|
data: {
|
|
campaignId,
|
|
name: enc.name,
|
|
mode: enc.mode,
|
|
description: enc.description,
|
|
dmNotes: enc.dmNotes,
|
|
sortOrder: index,
|
|
participants: { create: participants },
|
|
rewards: { create: rewards },
|
|
},
|
|
});
|
|
}
|
|
|
|
const notes = [
|
|
...aldenfell.sharedNotes.map((body) => ({ body, visibility: 'SHARED' })),
|
|
...aldenfell.dmNotes.map((body) => ({ body, visibility: 'DM_ONLY' })),
|
|
];
|
|
await db.note.createMany({
|
|
data: notes.map((n, i) => ({ ...n, campaignId, authorId: admin.id, createdAt: bookOrder(i) })),
|
|
});
|
|
|
|
console.log(` Campaign: ${campaign.name} — invite code ${campaign.inviteCode}`);
|
|
console.log(
|
|
` ${defaultWeapons.length} starting + ${aldenfell.weapons.length} earned weapons, ${aldenfell.items.length} items, ` +
|
|
`${spells.length} spells, ${aldenfell.locations.length} locations`,
|
|
);
|
|
console.log(
|
|
` ${aldenfell.monsters.length} monsters, ${aldenfell.npcs.length} NPCs, ${aldenfell.encounters.length} encounters ` +
|
|
`(${rewardCount} rewards lined up), ${notes.length} notes`,
|
|
);
|
|
}
|
|
|
|
async function main() {
|
|
if (RESET) {
|
|
await resetDatabase();
|
|
console.log('Database reset: every user and campaign was deleted.');
|
|
}
|
|
|
|
let admin = await prisma.user.findUnique({ where: { email: ADMIN_EMAIL } });
|
|
if (admin) {
|
|
console.log(`Admin account ${ADMIN_EMAIL} already exists — left as it is.`);
|
|
} else {
|
|
admin = await prisma.user.create({
|
|
data: { email: ADMIN_EMAIL, passwordHash: await bcrypt.hash(ADMIN_PASSWORD, 12), displayName: ADMIN_NAME },
|
|
});
|
|
console.log(`Admin/DM login created: ${ADMIN_EMAIL} / ${ADMIN_PASSWORD}`);
|
|
console.log(' Change that password from the account page (click your name, top right) once you are logged in.');
|
|
}
|
|
|
|
const existing = await prisma.campaign.findFirst({
|
|
where: { ownerId: admin.id, name: aldenfell.campaign.name, archivedAt: null },
|
|
});
|
|
if (existing) {
|
|
console.log(`${ADMIN_EMAIL} already has an active "${existing.name}" campaign — nothing added.`);
|
|
console.log(' For a fresh copy, archive or delete it under Campaign Settings and run the seed again.');
|
|
return;
|
|
}
|
|
|
|
// One transaction, so a failed seed doesn't leave half a campaign behind.
|
|
console.log('Seeding campaign...');
|
|
await prisma.$transaction((tx) => seedCampaign(tx, admin), { timeout: 120000, maxWait: 20000 });
|
|
console.log('Seed complete.');
|
|
}
|
|
|
|
main()
|
|
.catch((err) => {
|
|
console.error(err);
|
|
process.exit(1);
|
|
})
|
|
.finally(async () => {
|
|
await prisma.$disconnect();
|
|
});
|