feat(server): add Program and Award database models

- Add Program and Award tables to Prisma schema
- Update program-config.service to support database with JSON fallback
- Update ProgramCard.vue display logic for dynamic teamName/performer
- Add seed script to import data from JSON config

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
empty
2026-02-03 22:26:47 +08:00
parent b5fa4c7086
commit 406a5afa33
5 changed files with 374 additions and 49 deletions

View File

@@ -60,12 +60,21 @@ const programNumber = computed(() => {
return num.toString().padStart(2, '0'); return num.toString().padStart(2, '0');
}); });
// From 显示:部门·表演者 // From 显示:根据数据动态显示
const fromDisplay = computed(() => { const fromDisplay = computed(() => {
if (props.performer) { const team = props.teamName?.trim();
return `${props.teamName || ''}·${props.performer}`; const performer = props.performer?.trim();
if (team && performer) {
return `${team}·${performer}`;
} }
return props.teamName || 'The Performer'; if (performer) {
return performer;
}
if (team) {
return team;
}
return '表演者';
}); });
// 当前选中奖项的备注(用于移动端引导) // 当前选中奖项的备注(用于移动端引导)

View File

@@ -11,7 +11,7 @@
"db:generate": "prisma generate", "db:generate": "prisma generate",
"db:migrate": "prisma migrate dev", "db:migrate": "prisma migrate dev",
"db:push": "prisma db push", "db:push": "prisma db push",
"db:seed": "tsx src/scripts/seed.ts", "db:seed": "tsx prisma/seed.ts",
"test": "vitest", "test": "vitest",
"test:load": "artillery run load-test/vote-load-test.yaml -e standard", "test:load": "artillery run load-test/vote-load-test.yaml -e standard",
"test:load:smoke": "artillery run load-test/vote-load-test.yaml -e smoke", "test:load:smoke": "artillery run load-test/vote-load-test.yaml -e smoke",

View File

@@ -11,7 +11,6 @@ datasource db {
model User { model User {
id String @id @default(cuid()) id String @id @default(cuid())
name String @db.VarChar(100) name String @db.VarChar(100)
department String @db.VarChar(100)
avatar String? @db.VarChar(512) avatar String? @db.VarChar(512)
birthYear Int? @map("birth_year") birthYear Int? @map("birth_year")
zodiac String? @db.VarChar(20) zodiac String? @db.VarChar(20)
@@ -93,6 +92,37 @@ model DrawResult {
@@map("draw_results") @@map("draw_results")
} }
// Programs for voting
model Program {
id String @id @default(cuid())
name String @db.VarChar(100)
teamName String @default("") @map("team_name") @db.VarChar(100)
performer String @default("") @db.VarChar(200)
order Int @default(0)
remark String? @db.Text
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([order])
@@map("programs")
}
// Awards for voting
model Award {
id String @id @default(cuid())
name String @db.VarChar(100)
icon String @db.VarChar(20)
order Int @default(0)
remark String? @db.Text
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([order])
@@map("awards")
}
// Draw sessions // Draw sessions
model DrawSession { model DrawSession {
id String @id @default(cuid()) id String @id @default(cuid())

View File

@@ -0,0 +1,110 @@
/**
* Prisma Seed Script
* Populates initial program and award data from JSON config
*/
import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const prisma = new PrismaClient();
interface ProgramData {
id: string;
name: string;
teamName: string;
performer: string;
order: number;
remark: string;
}
interface AwardData {
id: string;
name: string;
icon: string;
order: number;
remark: string;
}
interface ConfigFile {
programs: ProgramData[];
awards: AwardData[];
}
async function main() {
console.log('Starting seed...');
// Load config from JSON file
const configPath = path.join(__dirname, '../config/programs.json');
if (!fs.existsSync(configPath)) {
console.error('Config file not found:', configPath);
process.exit(1);
}
const config: ConfigFile = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
// Seed programs
console.log(`Seeding ${config.programs.length} programs...`);
for (const p of config.programs) {
await prisma.program.upsert({
where: { id: p.id },
create: {
id: p.id,
name: p.name,
teamName: p.teamName || '',
performer: p.performer || '',
order: p.order,
remark: p.remark || null,
isActive: true,
},
update: {
name: p.name,
teamName: p.teamName || '',
performer: p.performer || '',
order: p.order,
remark: p.remark || null,
isActive: true,
},
});
console.log(` - ${p.name}`);
}
// Seed awards
console.log(`Seeding ${config.awards.length} awards...`);
for (const a of config.awards) {
await prisma.award.upsert({
where: { id: a.id },
create: {
id: a.id,
name: a.name,
icon: a.icon,
order: a.order,
remark: a.remark || null,
isActive: true,
},
update: {
name: a.name,
icon: a.icon,
order: a.order,
remark: a.remark || null,
isActive: true,
},
});
console.log(` - ${a.name}`);
}
console.log('Seed completed!');
}
main()
.catch((e) => {
console.error('Seed failed:', e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});

View File

@@ -1,26 +1,27 @@
/** /**
* Program Configuration Service * Program Configuration Service
* Loads program config from JSON file and provides API for management * Loads program config from database with JSON file fallback
*/ */
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import { logger } from '../utils/logger'; import { logger } from '../utils/logger';
import { prisma } from '../utils/prisma';
import type { VotingProgram } from '@gala/shared/types'; import type { VotingProgram } from '@gala/shared/types';
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
// Default config path // Default config path (fallback)
const CONFIG_PATH = path.join(__dirname, '../../config/programs.json'); const CONFIG_PATH = path.join(__dirname, '../../config/programs.json');
export interface ProgramConfig { export interface ProgramConfig {
id: string; id: string;
name: string; name: string;
teamName: string; teamName: string;
performer?: string; // 表演者 performer?: string;
order: number; order: number;
remark?: string; // 节目备注 remark?: string;
} }
export interface AwardConfig { export interface AwardConfig {
@@ -28,6 +29,7 @@ export interface AwardConfig {
name: string; name: string;
icon: string; icon: string;
order: number; order: number;
remark?: string;
} }
export interface ProgramSettings { export interface ProgramSettings {
@@ -44,15 +46,85 @@ export interface ProgramConfigFile {
class ProgramConfigService { class ProgramConfigService {
private config: ProgramConfigFile | null = null; private config: ProgramConfigFile | null = null;
private configPath: string; private configPath: string;
private useDatabase: boolean = true;
constructor() { constructor() {
this.configPath = CONFIG_PATH; this.configPath = CONFIG_PATH;
} }
/** /**
* Load config from file * Load config from database or file
*/ */
async load(): Promise<void> { async load(): Promise<void> {
try {
// Try loading from database first
const dbPrograms = await this.loadProgramsFromDb();
const dbAwards = await this.loadAwardsFromDb();
if (dbPrograms.length > 0 || dbAwards.length > 0) {
this.useDatabase = true;
this.config = {
programs: dbPrograms,
awards: dbAwards,
settings: this.getDefaultSettings(),
};
logger.info({
programCount: dbPrograms.length,
awardCount: dbAwards.length,
source: 'database'
}, 'Program config loaded from database');
return;
}
// Fallback to JSON file
this.useDatabase = false;
await this.loadFromFile();
} catch (error) {
logger.warn({ error }, 'Database not available, falling back to JSON file');
this.useDatabase = false;
await this.loadFromFile();
}
}
/**
* Load programs from database
*/
private async loadProgramsFromDb(): Promise<ProgramConfig[]> {
const programs = await prisma.program.findMany({
where: { isActive: true },
orderBy: { order: 'asc' },
});
return programs.map(p => ({
id: p.id,
name: p.name,
teamName: p.teamName,
performer: p.performer || undefined,
order: p.order,
remark: p.remark || undefined,
}));
}
/**
* Load awards from database
*/
private async loadAwardsFromDb(): Promise<AwardConfig[]> {
const awards = await prisma.award.findMany({
where: { isActive: true },
orderBy: { order: 'asc' },
});
return awards.map(a => ({
id: a.id,
name: a.name,
icon: a.icon,
order: a.order,
remark: a.remark || undefined,
}));
}
/**
* Load config from JSON file
*/
private async loadFromFile(): Promise<void> {
try { try {
if (fs.existsSync(this.configPath)) { if (fs.existsSync(this.configPath)) {
const content = fs.readFileSync(this.configPath, 'utf-8'); const content = fs.readFileSync(this.configPath, 'utf-8');
@@ -60,28 +132,28 @@ class ProgramConfigService {
logger.info({ logger.info({
programCount: this.config?.programs.length, programCount: this.config?.programs.length,
awardCount: this.config?.awards?.length || 0, awardCount: this.config?.awards?.length || 0,
configPath: this.configPath source: 'file'
}, 'Program config loaded'); }, 'Program config loaded from file');
// Validate: programs.length === awards.length
if (this.config?.programs && this.config?.awards) {
if (this.config.programs.length !== this.config.awards.length) {
logger.warn({
programCount: this.config.programs.length,
awardCount: this.config.awards.length
}, 'Warning: program count does not match award count');
}
}
} else { } else {
logger.warn({ configPath: this.configPath }, 'Program config file not found, using defaults'); logger.warn({ configPath: this.configPath }, 'Config file not found, using defaults');
this.config = this.getDefaults(); this.config = this.getDefaults();
} }
} catch (error) { } catch (error) {
logger.error({ error, configPath: this.configPath }, 'Failed to load program config'); logger.error({ error }, 'Failed to load config from file');
this.config = this.getDefaults(); this.config = this.getDefaults();
} }
} }
/**
* Get default settings
*/
private getDefaultSettings(): ProgramSettings {
return {
allowLateCatch: true,
maxVotesPerUser: 7,
};
}
/** /**
* Get default configuration * Get default configuration
*/ */
@@ -105,15 +177,12 @@ class ProgramConfigService {
{ id: 'craftsmanship', name: '匠心独韵奖', icon: '💎', order: 6 }, { id: 'craftsmanship', name: '匠心独韵奖', icon: '💎', order: 6 },
{ id: 'in_sync', name: '同频时代奖', icon: '📻', order: 7 }, { id: 'in_sync', name: '同频时代奖', icon: '📻', order: 7 },
], ],
settings: { settings: this.getDefaultSettings(),
allowLateCatch: true,
maxVotesPerUser: 7,
},
}; };
} }
/** /**
* Get all programs (for display/listing) * Get all programs
*/ */
getPrograms(): ProgramConfig[] { getPrograms(): ProgramConfig[] {
return this.config?.programs || this.getDefaults().programs; return this.config?.programs || this.getDefaults().programs;
@@ -134,7 +203,7 @@ class ProgramConfigService {
} }
/** /**
* Convert config programs to VotingProgram format (with runtime fields) * Convert config programs to VotingProgram format
*/ */
getVotingPrograms(): VotingProgram[] { getVotingPrograms(): VotingProgram[] {
const programs = this.getPrograms(); const programs = this.getPrograms();
@@ -157,21 +226,18 @@ class ProgramConfigService {
* Get settings * Get settings
*/ */
getSettings(): ProgramSettings { getSettings(): ProgramSettings {
return this.config?.settings || this.getDefaults().settings; return this.config?.settings || this.getDefaultSettings();
} }
/** /**
* Update programs and save to file * Update programs (database or file)
*/ */
async updatePrograms(programs: ProgramConfig[]): Promise<{ success: boolean; error?: string }> { async updatePrograms(programs: ProgramConfig[]): Promise<{ success: boolean; error?: string }> {
try { try {
if (!this.config) { if (this.useDatabase) {
this.config = this.getDefaults(); return await this.updateProgramsInDb(programs);
} }
this.config.programs = programs; return await this.updateProgramsInFile(programs);
await this.saveToFile();
logger.info({ programCount: programs.length }, 'Programs updated');
return { success: true };
} catch (error) { } catch (error) {
logger.error({ error }, 'Failed to update programs'); logger.error({ error }, 'Failed to update programs');
return { success: false, error: (error as Error).message }; return { success: false, error: (error as Error).message };
@@ -179,17 +245,69 @@ class ProgramConfigService {
} }
/** /**
* Update awards and save to file * Update programs in database
*/
private async updateProgramsInDb(programs: ProgramConfig[]): Promise<{ success: boolean; error?: string }> {
// Use transaction to update all programs
await prisma.$transaction(async (tx) => {
// Deactivate all existing programs
await tx.program.updateMany({
data: { isActive: false }
});
// Upsert each program
for (const p of programs) {
await tx.program.upsert({
where: { id: p.id },
create: {
id: p.id,
name: p.name,
teamName: p.teamName,
performer: p.performer || '',
order: p.order,
remark: p.remark,
isActive: true,
},
update: {
name: p.name,
teamName: p.teamName,
performer: p.performer || '',
order: p.order,
remark: p.remark,
isActive: true,
},
});
}
});
// Reload config
await this.load();
logger.info({ programCount: programs.length }, 'Programs updated in database');
return { success: true };
}
/**
* Update programs in file
*/
private async updateProgramsInFile(programs: ProgramConfig[]): Promise<{ success: boolean; error?: string }> {
if (!this.config) {
this.config = this.getDefaults();
}
this.config.programs = programs;
await this.saveToFile();
logger.info({ programCount: programs.length }, 'Programs updated in file');
return { success: true };
}
/**
* Update awards (database or file)
*/ */
async updateAwards(awards: AwardConfig[]): Promise<{ success: boolean; error?: string }> { async updateAwards(awards: AwardConfig[]): Promise<{ success: boolean; error?: string }> {
try { try {
if (!this.config) { if (this.useDatabase) {
this.config = this.getDefaults(); return await this.updateAwardsInDb(awards);
} }
this.config.awards = awards; return await this.updateAwardsInFile(awards);
await this.saveToFile();
logger.info({ awardCount: awards.length }, 'Awards updated');
return { success: true };
} catch (error) { } catch (error) {
logger.error({ error }, 'Failed to update awards'); logger.error({ error }, 'Failed to update awards');
return { success: false, error: (error as Error).message }; return { success: false, error: (error as Error).message };
@@ -197,7 +315,56 @@ class ProgramConfigService {
} }
/** /**
* Update settings and save to file * Update awards in database
*/
private async updateAwardsInDb(awards: AwardConfig[]): Promise<{ success: boolean; error?: string }> {
await prisma.$transaction(async (tx) => {
await tx.award.updateMany({
data: { isActive: false }
});
for (const a of awards) {
await tx.award.upsert({
where: { id: a.id },
create: {
id: a.id,
name: a.name,
icon: a.icon,
order: a.order,
remark: a.remark,
isActive: true,
},
update: {
name: a.name,
icon: a.icon,
order: a.order,
remark: a.remark,
isActive: true,
},
});
}
});
await this.load();
logger.info({ awardCount: awards.length }, 'Awards updated in database');
return { success: true };
}
/**
* Update awards in file
*/
private async updateAwardsInFile(awards: AwardConfig[]): Promise<{ success: boolean; error?: string }> {
if (!this.config) {
this.config = this.getDefaults();
}
this.config.awards = awards;
await this.saveToFile();
logger.info({ awardCount: awards.length }, 'Awards updated in file');
return { success: true };
}
/**
* Update settings
*/ */
async updateSettings(settings: Partial<ProgramSettings>): Promise<{ success: boolean; error?: string }> { async updateSettings(settings: Partial<ProgramSettings>): Promise<{ success: boolean; error?: string }> {
try { try {
@@ -205,7 +372,9 @@ class ProgramConfigService {
this.config = this.getDefaults(); this.config = this.getDefaults();
} }
this.config.settings = { ...this.config.settings, ...settings }; this.config.settings = { ...this.config.settings, ...settings };
await this.saveToFile(); if (!this.useDatabase) {
await this.saveToFile();
}
logger.info({ settings: this.config.settings }, 'Program settings updated'); logger.info({ settings: this.config.settings }, 'Program settings updated');
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
@@ -223,11 +392,18 @@ class ProgramConfigService {
} }
/** /**
* Get full config for API response * Get full config
*/ */
getFullConfig(): ProgramConfigFile { getFullConfig(): ProgramConfigFile {
return this.config || this.getDefaults(); return this.config || this.getDefaults();
} }
/**
* Check if using database
*/
isUsingDatabase(): boolean {
return this.useDatabase;
}
} }
export const programConfigService = new ProgramConfigService(); export const programConfigService = new ProgramConfigService();