feat(server): 添加节目配置文件管理
- 新增 programs.json 配置文件 - 新增 ProgramConfigService 服务 - 新增节目配置 API 接口 (GET/PUT /api/admin/programs) - 修改 AdminService 使用配置服务替代硬编码 - 添加单元测试
This commit is contained in:
56
packages/server/config/programs.json
Normal file
56
packages/server/config/programs.json
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"programs": [
|
||||||
|
{
|
||||||
|
"id": "p1",
|
||||||
|
"name": "龙腾四海",
|
||||||
|
"teamName": "市场部",
|
||||||
|
"order": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "p2",
|
||||||
|
"name": "金马奔腾",
|
||||||
|
"teamName": "技术部",
|
||||||
|
"order": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "p3",
|
||||||
|
"name": "春风得意",
|
||||||
|
"teamName": "人力资源部",
|
||||||
|
"order": 3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "p4",
|
||||||
|
"name": "鸿运当头",
|
||||||
|
"teamName": "财务部",
|
||||||
|
"order": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "p5",
|
||||||
|
"name": "马到成功",
|
||||||
|
"teamName": "运营部",
|
||||||
|
"order": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "p6",
|
||||||
|
"name": "一马当先",
|
||||||
|
"teamName": "产品部",
|
||||||
|
"order": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "p7",
|
||||||
|
"name": "万马奔腾",
|
||||||
|
"teamName": "设计部",
|
||||||
|
"order": 7
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "p8",
|
||||||
|
"name": "龙马精神",
|
||||||
|
"teamName": "销售部",
|
||||||
|
"order": 8
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"settings": {
|
||||||
|
"allowLateCatch": true,
|
||||||
|
"maxVotesPerUser": 7
|
||||||
|
}
|
||||||
|
}
|
||||||
59
packages/server/src/__tests__/program-config.test.ts
Normal file
59
packages/server/src/__tests__/program-config.test.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
/**
|
||||||
|
* 节目配置服务测试
|
||||||
|
*/
|
||||||
|
import { describe, it, expect, beforeAll } from 'vitest';
|
||||||
|
import { programConfigService } from '../services/program-config.service';
|
||||||
|
|
||||||
|
describe('节目配置服务测试', () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
await programConfigService.load();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('配置加载', () => {
|
||||||
|
it('应该能加载节目列表', () => {
|
||||||
|
const programs = programConfigService.getPrograms();
|
||||||
|
expect(programs).toBeDefined();
|
||||||
|
expect(programs.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该能加载设置', () => {
|
||||||
|
const settings = programConfigService.getSettings();
|
||||||
|
expect(settings).toBeDefined();
|
||||||
|
expect(typeof settings.allowLateCatch).toBe('boolean');
|
||||||
|
expect(typeof settings.maxVotesPerUser).toBe('number');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('节目操作', () => {
|
||||||
|
it('应该能按ID查找节目', () => {
|
||||||
|
const program = programConfigService.getProgramById('p1');
|
||||||
|
expect(program).toBeDefined();
|
||||||
|
expect(program?.id).toBe('p1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('查找不存在的节目应返回undefined', () => {
|
||||||
|
const program = programConfigService.getProgramById('non-existent');
|
||||||
|
expect(program).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该能获取带运行时字段的节目列表', () => {
|
||||||
|
const votingPrograms = programConfigService.getVotingPrograms();
|
||||||
|
expect(votingPrograms).toBeDefined();
|
||||||
|
expect(votingPrograms.length).toBeGreaterThan(0);
|
||||||
|
// 检查运行时字段
|
||||||
|
const first = votingPrograms[0];
|
||||||
|
expect(first.status).toBe('pending');
|
||||||
|
expect(first.votes).toBe(0);
|
||||||
|
expect(first.stamps).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('完整配置', () => {
|
||||||
|
it('应该能获取完整配置', () => {
|
||||||
|
const config = programConfigService.getFullConfig();
|
||||||
|
expect(config).toBeDefined();
|
||||||
|
expect(config.programs).toBeDefined();
|
||||||
|
expect(config.settings).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -6,6 +6,7 @@ import { initializeSocket } from './socket';
|
|||||||
import { loadLuaScripts } from './services/vote.service';
|
import { loadLuaScripts } from './services/vote.service';
|
||||||
import { loadVotingScripts } from './services/voting.engine';
|
import { loadVotingScripts } from './services/voting.engine';
|
||||||
import { prizeConfigService } from './services/prize-config.service';
|
import { prizeConfigService } from './services/prize-config.service';
|
||||||
|
import { programConfigService } from './services/program-config.service';
|
||||||
import { participantService } from './services/participant.service';
|
import { participantService } from './services/participant.service';
|
||||||
|
|
||||||
async function main(): Promise<void> {
|
async function main(): Promise<void> {
|
||||||
@@ -23,6 +24,10 @@ async function main(): Promise<void> {
|
|||||||
logger.info('Loading prize configuration...');
|
logger.info('Loading prize configuration...');
|
||||||
await prizeConfigService.load();
|
await prizeConfigService.load();
|
||||||
|
|
||||||
|
// Load program configuration
|
||||||
|
logger.info('Loading program configuration...');
|
||||||
|
await programConfigService.load();
|
||||||
|
|
||||||
// Restore participants from Redis
|
// Restore participants from Redis
|
||||||
logger.info('Restoring participants from Redis...');
|
logger.info('Restoring participants from Redis...');
|
||||||
await participantService.restoreFromRedis();
|
await participantService.restoreFromRedis();
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Router, IRouter } from 'express';
|
|||||||
import multer from 'multer';
|
import multer from 'multer';
|
||||||
import { participantService } from '../services/participant.service';
|
import { participantService } from '../services/participant.service';
|
||||||
import { prizeConfigService } from '../services/prize-config.service';
|
import { prizeConfigService } from '../services/prize-config.service';
|
||||||
|
import { programConfigService } from '../services/program-config.service';
|
||||||
|
|
||||||
const router: IRouter = Router();
|
const router: IRouter = Router();
|
||||||
const upload = multer({ storage: multer.memoryStorage() });
|
const upload = multer({ storage: multer.memoryStorage() });
|
||||||
@@ -73,6 +74,53 @@ router.put('/prizes', async (req, res, next) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/admin/programs
|
||||||
|
* Get program configuration
|
||||||
|
*/
|
||||||
|
router.get('/programs', async (_req, res, next) => {
|
||||||
|
try {
|
||||||
|
const config = programConfigService.getFullConfig();
|
||||||
|
return res.json({
|
||||||
|
success: true,
|
||||||
|
data: config,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PUT /api/admin/programs
|
||||||
|
* Update program configuration
|
||||||
|
*/
|
||||||
|
router.put('/programs', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { programs, settings } = req.body;
|
||||||
|
|
||||||
|
if (programs) {
|
||||||
|
const result = await programConfigService.updatePrograms(programs);
|
||||||
|
if (!result.success) {
|
||||||
|
return res.status(400).json({ success: false, error: result.error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (settings) {
|
||||||
|
const result = await programConfigService.updateSettings(settings);
|
||||||
|
if (!result.success) {
|
||||||
|
return res.status(400).json({ success: false, error: result.error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.json({
|
||||||
|
success: true,
|
||||||
|
data: programConfigService.getFullConfig(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/admin/draw/start
|
* POST /api/admin/draw/start
|
||||||
* Start a lucky draw
|
* Start a lucky draw
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { EventEmitter } from 'events';
|
|||||||
import { redis } from '../config/redis';
|
import { redis } from '../config/redis';
|
||||||
import { logger } from '../utils/logger';
|
import { logger } from '../utils/logger';
|
||||||
import { prizeConfigService } from './prize-config.service';
|
import { prizeConfigService } from './prize-config.service';
|
||||||
|
import { programConfigService } from './program-config.service';
|
||||||
import { participantService } from './participant.service';
|
import { participantService } from './participant.service';
|
||||||
import type {
|
import type {
|
||||||
AdminState,
|
AdminState,
|
||||||
@@ -18,7 +19,7 @@ import type {
|
|||||||
VotingProgram,
|
VotingProgram,
|
||||||
VoteStamp,
|
VoteStamp,
|
||||||
} from '@gala/shared/types';
|
} from '@gala/shared/types';
|
||||||
import { INITIAL_ADMIN_STATE, PRIZE_CONFIG, DEFAULT_PROGRAMS } from '@gala/shared/types';
|
import { INITIAL_ADMIN_STATE, PRIZE_CONFIG } from '@gala/shared/types';
|
||||||
|
|
||||||
const ADMIN_STATE_KEY = 'gala:admin:state';
|
const ADMIN_STATE_KEY = 'gala:admin:state';
|
||||||
|
|
||||||
@@ -45,10 +46,10 @@ class AdminService extends EventEmitter {
|
|||||||
voting: {
|
voting: {
|
||||||
...INITIAL_ADMIN_STATE.voting,
|
...INITIAL_ADMIN_STATE.voting,
|
||||||
...parsed.voting,
|
...parsed.voting,
|
||||||
// Ensure programs always has default values
|
// Ensure programs always has default values from config service
|
||||||
programs: parsed.voting?.programs?.length > 0
|
programs: parsed.voting?.programs?.length > 0
|
||||||
? parsed.voting.programs
|
? parsed.voting.programs
|
||||||
: DEFAULT_PROGRAMS,
|
: programConfigService.getVotingPrograms(),
|
||||||
},
|
},
|
||||||
lottery: {
|
lottery: {
|
||||||
...INITIAL_ADMIN_STATE.lottery,
|
...INITIAL_ADMIN_STATE.lottery,
|
||||||
@@ -502,7 +503,7 @@ class AdminService extends EventEmitter {
|
|||||||
if (scope === 'all' || scope === 'voting') {
|
if (scope === 'all' || scope === 'voting') {
|
||||||
this.state.voting = {
|
this.state.voting = {
|
||||||
...INITIAL_ADMIN_STATE.voting,
|
...INITIAL_ADMIN_STATE.voting,
|
||||||
programs: DEFAULT_PROGRAMS.map(p => ({ ...p, votes: 0, stamps: [] })),
|
programs: programConfigService.getVotingPrograms(),
|
||||||
};
|
};
|
||||||
// Clear voting data in Redis
|
// Clear voting data in Redis
|
||||||
await redis.del('gala:votes:*');
|
await redis.del('gala:votes:*');
|
||||||
|
|||||||
172
packages/server/src/services/program-config.service.ts
Normal file
172
packages/server/src/services/program-config.service.ts
Normal file
@@ -0,0 +1,172 @@
|
|||||||
|
/**
|
||||||
|
* Program Configuration Service
|
||||||
|
* Loads program config from JSON file and provides API for management
|
||||||
|
*/
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
import { logger } from '../utils/logger';
|
||||||
|
import type { VotingProgram } from '@gala/shared/types';
|
||||||
|
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
|
// Default config path
|
||||||
|
const CONFIG_PATH = path.join(__dirname, '../../config/programs.json');
|
||||||
|
|
||||||
|
export interface ProgramConfig {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
teamName: string;
|
||||||
|
order: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProgramSettings {
|
||||||
|
allowLateCatch: boolean;
|
||||||
|
maxVotesPerUser: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProgramConfigFile {
|
||||||
|
programs: ProgramConfig[];
|
||||||
|
settings: ProgramSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProgramConfigService {
|
||||||
|
private config: ProgramConfigFile | null = null;
|
||||||
|
private configPath: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.configPath = CONFIG_PATH;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load config from file
|
||||||
|
*/
|
||||||
|
async load(): Promise<void> {
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(this.configPath)) {
|
||||||
|
const content = fs.readFileSync(this.configPath, 'utf-8');
|
||||||
|
this.config = JSON.parse(content);
|
||||||
|
logger.info({
|
||||||
|
programCount: this.config?.programs.length,
|
||||||
|
configPath: this.configPath
|
||||||
|
}, 'Program config loaded');
|
||||||
|
} else {
|
||||||
|
logger.warn({ configPath: this.configPath }, 'Program config file not found, using defaults');
|
||||||
|
this.config = this.getDefaults();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error, configPath: this.configPath }, 'Failed to load program config');
|
||||||
|
this.config = this.getDefaults();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get default configuration
|
||||||
|
*/
|
||||||
|
private getDefaults(): ProgramConfigFile {
|
||||||
|
return {
|
||||||
|
programs: [
|
||||||
|
{ id: 'p1', name: '龙腾四海', teamName: '市场部', order: 1 },
|
||||||
|
{ id: 'p2', name: '金马奔腾', teamName: '技术部', order: 2 },
|
||||||
|
{ id: 'p3', name: '春风得意', teamName: '人力资源部', order: 3 },
|
||||||
|
{ id: 'p4', name: '鸿运当头', teamName: '财务部', order: 4 },
|
||||||
|
{ id: 'p5', name: '马到成功', teamName: '运营部', order: 5 },
|
||||||
|
{ id: 'p6', name: '一马当先', teamName: '产品部', order: 6 },
|
||||||
|
{ id: 'p7', name: '万马奔腾', teamName: '设计部', order: 7 },
|
||||||
|
{ id: 'p8', name: '龙马精神', teamName: '销售部', order: 8 },
|
||||||
|
],
|
||||||
|
settings: {
|
||||||
|
allowLateCatch: true,
|
||||||
|
maxVotesPerUser: 7,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all programs (for display/listing)
|
||||||
|
*/
|
||||||
|
getPrograms(): ProgramConfig[] {
|
||||||
|
return this.config?.programs || this.getDefaults().programs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert config programs to VotingProgram format (with runtime fields)
|
||||||
|
*/
|
||||||
|
getVotingPrograms(): VotingProgram[] {
|
||||||
|
const programs = this.getPrograms();
|
||||||
|
return programs.map(p => ({
|
||||||
|
...p,
|
||||||
|
status: 'pending' as const,
|
||||||
|
votes: 0,
|
||||||
|
stamps: [],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get program by id
|
||||||
|
*/
|
||||||
|
getProgramById(id: string): ProgramConfig | undefined {
|
||||||
|
return this.getPrograms().find(p => p.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get settings
|
||||||
|
*/
|
||||||
|
getSettings(): ProgramSettings {
|
||||||
|
return this.config?.settings || this.getDefaults().settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update programs and save to file
|
||||||
|
*/
|
||||||
|
async updatePrograms(programs: ProgramConfig[]): Promise<{ success: boolean; error?: string }> {
|
||||||
|
try {
|
||||||
|
if (!this.config) {
|
||||||
|
this.config = this.getDefaults();
|
||||||
|
}
|
||||||
|
this.config.programs = programs;
|
||||||
|
await this.saveToFile();
|
||||||
|
logger.info({ programCount: programs.length }, 'Programs updated');
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error }, 'Failed to update programs');
|
||||||
|
return { success: false, error: (error as Error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update settings and save to file
|
||||||
|
*/
|
||||||
|
async updateSettings(settings: Partial<ProgramSettings>): Promise<{ success: boolean; error?: string }> {
|
||||||
|
try {
|
||||||
|
if (!this.config) {
|
||||||
|
this.config = this.getDefaults();
|
||||||
|
}
|
||||||
|
this.config.settings = { ...this.config.settings, ...settings };
|
||||||
|
await this.saveToFile();
|
||||||
|
logger.info({ settings: this.config.settings }, 'Program settings updated');
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ error }, 'Failed to update settings');
|
||||||
|
return { success: false, error: (error as Error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save config to file
|
||||||
|
*/
|
||||||
|
private async saveToFile(): Promise<void> {
|
||||||
|
const content = JSON.stringify(this.config, null, 2);
|
||||||
|
fs.writeFileSync(this.configPath, content, 'utf-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get full config for API response
|
||||||
|
*/
|
||||||
|
getFullConfig(): ProgramConfigFile {
|
||||||
|
return this.config || this.getDefaults();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const programConfigService = new ProgramConfigService();
|
||||||
Reference in New Issue
Block a user