refactor: migrate configuration to YAML-based system

This commit is contained in:
test
2026-03-07 11:30:09 +08:00
parent 48f1f51d76
commit c13be9e19a
27 changed files with 1716 additions and 1638 deletions

View File

@@ -1,21 +1,33 @@
/**
* Configuration Manager
* Configuration Manager (YAML Version)
*
* Manages application configuration stored in .env file
* Provides methods for reading, writing, and saving configuration values
* Manages application configuration using YAML format
* Provides type-safe access with Zod validation
*
* Note: ERP configuration is stored in database (dbo_BIPUsers table)
* and managed per-user, not in this config file.
*
* Configuration File Location:
* - Development: Project root directory (config.yaml)
* - Production (Installed & Portable): User data directory (AppData)
* This ensures config persists across app updates and is not exposed
*/
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
import { dirname } from 'path'
import { app } from 'electron'
import yaml from 'js-yaml'
import { z } from 'zod'
import { createLogger } from '../logger'
import type {
SettingsData,
DatabaseType,
MatchMode,
ValidationDataSource
} from '../../types/settings.types'
import {
fullConfigSchema,
type FullConfig,
type DatabaseType,
type MySqlConfig,
type SqlServerConfig
} from '../../types/config.schema'
const log = createLogger('ConfigManager')
@@ -23,30 +35,36 @@ const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
/**
* Default settings values
* 默认配置
*/
const DEFAULT_SETTINGS: SettingsData = {
const DEFAULT_CONFIG: FullConfig = {
erp: {
url: 'https://68.11.34.30:8082/',
username: '',
password: '',
headless: true,
ignoreHttpsErrors: true,
autoCloseBrowser: true
url: 'https://68.11.34.30:8082'
},
database: {
dbType: 'mysql',
server: '',
mysqlHost: '192.168.31.83',
mysqlPort: 3306,
database: 'BLD_DB',
username: 'remote_user',
password: ''
activeType: 'mysql',
mysql: {
host: 'localhost',
port: 3306,
database: 'erp_db',
username: 'root',
password: '',
charset: 'utf8mb4'
},
sqlserver: {
server: 'localhost',
port: 1433,
database: 'erp_db',
username: 'sa',
password: '',
driver: 'ODBC Driver 18 for SQL Server',
trustServerCertificate: true
}
},
paths: {
dataDir: 'D:/python/playwrite/data/',
defaultOutput: '离散备料计划维护_合并.xlsx',
validationOutput: '物料状态校验结果.xlsx'
dataDir: './data/',
defaultOutput: 'output.xlsx',
validationOutput: 'validation-result.xlsx'
},
extraction: {
batchSize: 100,
@@ -61,103 +79,44 @@ const DEFAULT_SETTINGS: SettingsData = {
matchMode: 'substring',
enableCrud: false,
defaultManager: ''
},
orderResolution: {
tableName: '',
productionIdField: '',
orderNumberField: ''
}
}
/**
* Check if value is a plain object
*/
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Deep merge two objects, only updating fields present in target
* Preserves all fields from source that are not in target
*/
function deepMerge<T>(source: T, target: Partial<T>): T {
const result = { ...source }
for (const key in target) {
if (key in target) {
const targetValue = target[key]
const sourceValue = result[key]
if (isObject(targetValue) && isObject(sourceValue)) {
result[key] = deepMerge(
sourceValue as T[Extract<keyof T, string>],
targetValue as Partial<T[Extract<keyof T, string>]>
)
} else if (targetValue !== undefined) {
result[key] = targetValue as T[Extract<keyof T, string>]
}
}
}
return result
}
/**
* UI editable field whitelist
* Fields that can be modified through the settings UI
* Note: ERP fields are no longer editable here - they are managed per-user in the database
*/
const UI_EDITABLE_FIELDS: string[] = [
// ERP fields removed - ERP config is now stored in dbo_BIPUsers table per user
// 'erp.url',
// 'erp.username',
// 'erp.password'
// Add more fields as UI expands
]
/**
* Validate that settings only contain editable fields
*/
function validateEditableFields(settings: Partial<SettingsData>): {
valid: boolean
invalidFields: string[]
} {
const invalidFields: string[] = []
for (const [section, values] of Object.entries(settings)) {
if (values && typeof values === 'object') {
for (const field of Object.keys(values)) {
const fieldPath = `${section}.${field}`
if (!UI_EDITABLE_FIELDS.includes(fieldPath)) {
invalidFields.push(fieldPath)
}
}
}
}
return {
valid: invalidFields.length === 0,
invalidFields
}
}
/**
* Configuration Manager Class
*/
export class ConfigManager {
private static instance: ConfigManager | null = null
private envPath!: string
private configPath!: string
private backupPath!: string
private configCache: Map<string, string> = new Map()
private config: FullConfig | null = null
private initialized: boolean = false
private constructor() {
if (this.initialized) {
return
if (this.initialized) return
// 检测是否为开发环境
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged
if (isDev) {
// 开发环境:配置文件放在项目根目录,方便编辑和调试
this.configPath = path.resolve(__dirname, '../../config.yaml')
this.backupPath = path.resolve(__dirname, '../../config.yaml.backup')
log.info('Running in development mode', { configPath: this.configPath })
} else {
// 生产环境(包括安装版和便携版):配置文件放在用户数据目录
// Windows: C:\Users\<user>\AppData\Roaming\erpauto\config.yaml
// 这样配置会在应用升级时保留,且不会暴露在应用目录中
this.configPath = path.join(app.getPath('userData'), 'config.yaml')
this.backupPath = path.join(app.getPath('userData'), 'config.yaml.backup')
log.info('Running in production mode', { configPath: this.configPath })
}
this.envPath = path.resolve(__dirname, '../../.env')
this.backupPath = path.resolve(__dirname, '../../.env.backup')
this.initialized = true
}
/**
* Get the singleton instance
*/
public static getInstance(): ConfigManager {
if (ConfigManager.instance === null) {
ConfigManager.instance = new ConfigManager()
@@ -166,478 +125,189 @@ export class ConfigManager {
}
/**
* Initialize configuration from .env file
* 初始化配置
* - 如果 config.yaml 不存在,创建默认配置
* - 加载并验证配置
*/
public async initialize(): Promise<void> {
await this.loadEnvFile()
if (!fs.existsSync(this.configPath)) {
log.info('Config file not found, creating default config.yaml')
await this.saveConfig(DEFAULT_CONFIG)
this.config = DEFAULT_CONFIG
return
}
await this.loadConfig()
}
/**
* Load .env file into cache
* 加载并验证 YAML 配置
*/
private async loadEnvFile(): Promise<void> {
private async loadConfig(): Promise<void> {
try {
// Clear cache before loading
this.configCache.clear()
const content = fs.readFileSync(this.configPath, 'utf-8')
const parsed = yaml.load(content) as Record<string, unknown>
if (fs.existsSync(this.envPath)) {
const content = fs.readFileSync(this.envPath, 'utf-8')
const lines = content.split('\n')
// Zod 验证
const validated = fullConfigSchema.parse(parsed)
this.config = validated
for (const line of lines) {
const trimmedLine = line.trim()
// Skip empty lines and comments
if (!trimmedLine || trimmedLine.startsWith('#')) {
continue
}
const [key, ...valueParts] = trimmedLine.split('=')
if (key && valueParts.length > 0) {
const value = valueParts.join('=').trim()
this.configCache.set(key.trim(), value)
}
}
}
log.info('Configuration loaded and validated successfully')
} catch (error) {
console.error('[ConfigManager] Failed to load .env file:', error)
if (error instanceof z.ZodError) {
const messages = error.issues.map((e: any) => `${e.path.join('.')}: ${e.message}`)
log.error('Configuration validation failed', { errors: messages })
throw new Error(`配置文件验证失败:\n${messages.join('\n')}`)
}
log.error('Failed to load configuration', { error })
throw error
}
}
/**
* Get a configuration value
* @param key - Configuration key
* @param defaultValue - Default value if key doesn't exist
* 保存配置到 YAML 文件
*/
public get(key: string): string | undefined
public get(key: string, defaultValue: string): string
public get(key: string, defaultValue?: string): string | undefined {
return this.configCache.get(key) ?? defaultValue
}
/**
* Get a boolean configuration value
*/
public getBoolean(key: string, defaultValue: boolean = false): boolean {
const value = this.get(key)
if (value === undefined) return defaultValue
return value.toLowerCase() === 'true'
}
/**
* Get a number configuration value
*/
public getNumber(key: string, defaultValue: number = 0): number {
const value = this.get(key)
if (value === undefined) return defaultValue
const parsed = parseInt(value, 10)
return isNaN(parsed) ? defaultValue : parsed
}
/**
* Set a configuration value in cache
*/
public set(key: string, value: string | number | boolean): void {
this.configCache.set(key, String(value))
}
/**
* Save configuration to .env file
*/
public async save(): Promise<boolean> {
private async saveConfig(config: FullConfig): Promise<boolean> {
try {
// Build .env content from cache
const lines: string[] = []
// 备份现有配置
if (fs.existsSync(this.configPath)) {
fs.copyFileSync(this.configPath, this.backupPath)
}
// ERP Configuration - REMOVED
// ERP parameters are now stored in the database (dbo_BIPUsers table)
// This section is kept for backward compatibility but values are not used
lines.push('# ===========================')
lines.push('# ERP 系统配置(已迁移到数据库)')
lines.push('# ===========================')
lines.push('# ERP_URL, ERP_USERNAME, ERP_PASSWORD 已从 .env 移除')
lines.push('# 这些参数现在存储在 dbo_BIPUsers 表中,每个用户可以有自己的 ERP 配置')
lines.push('')
// 转换为 YAML
const content = yaml.dump(config, {
indent: 2,
lineWidth: -1, // 不自动换行
noRefs: true, // 不使用引用
quotingType: '"',
forceQuotes: false
})
// Database Configuration - SQL Server
lines.push('# ===========================')
lines.push('# 数据库配置 - SQL Server')
lines.push('# ===========================')
lines.push(`# DB_TYPE=sqlserver`)
lines.push(`# DB_SERVER=${this.configCache.get('DB_SERVER') || ''}`)
lines.push(`# DB_NAME=${this.configCache.get('DB_NAME') || ''}`)
lines.push(`# DB_USERNAME=${this.configCache.get('DB_USERNAME') || ''}`)
lines.push(`# DB_PASSWORD=${this.configCache.get('DB_PASSWORD') || ''}`)
lines.push(`DB_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server`)
lines.push(`DB_TRUST_SERVER_CERTIFICATE=yes`)
lines.push('')
fs.writeFileSync(this.configPath, content, 'utf-8')
// Database Configuration - MySQL
lines.push('# ===========================')
lines.push('# 数据库配置 - MySQL (切换时使用)')
lines.push('# ===========================')
lines.push(`DB_TYPE=${this.configCache.get('DB_TYPE') || DEFAULT_SETTINGS.database.dbType}`)
lines.push(`DB_NAME=${this.configCache.get('DB_NAME') || DEFAULT_SETTINGS.database.database}`)
lines.push(
`DB_USERNAME=${this.configCache.get('DB_USERNAME') || DEFAULT_SETTINGS.database.username}`
)
lines.push(
`DB_PASSWORD=${this.configCache.get('DB_PASSWORD') || DEFAULT_SETTINGS.database.password}`
)
lines.push(
`DB_MYSQL_HOST=${this.configCache.get('DB_MYSQL_HOST') || DEFAULT_SETTINGS.database.mysqlHost}`
)
lines.push(
`DB_MYSQL_PORT=${this.configCache.get('DB_MYSQL_PORT') || DEFAULT_SETTINGS.database.mysqlPort}`
)
lines.push(`DB_MYSQL_CHARSET=utf8mb4`)
lines.push('')
// Order number parsing table configuration
lines.push('# 订单号解析表配置')
lines.push('# 表名:包含 productionID 和 生产订单号 映射关系的表')
lines.push(`DB_TABLE_NAME=productionContractData_26年压力表合同数据`)
lines.push('# 字段名:总排号 (对应 productionID)')
lines.push(`DB_FIELD_PRODUCTION_ID=总排号`)
lines.push('# 字段名:生产订单号 (对应生产订单号)')
lines.push(`DB_FIELD_ORDER_NUMBER=生产订单号`)
lines.push('')
// Path Configuration
lines.push('# ===========================')
lines.push('# 路径配置')
lines.push('# ===========================')
lines.push(
`PATH_DATA_DIR=${this.configCache.get('PATH_DATA_DIR') || DEFAULT_SETTINGS.paths.dataDir}`
)
lines.push(`PATH_PRODUCTION_ID_FILE=ProductionID.txt`)
lines.push(
`PATH_DEFAULT_OUTPUT=${this.configCache.get('PATH_DEFAULT_OUTPUT') || DEFAULT_SETTINGS.paths.defaultOutput}`
)
lines.push(
`PATH_VALIDATION_OUTPUT=${this.configCache.get('PATH_VALIDATION_OUTPUT') || DEFAULT_SETTINGS.paths.validationOutput}`
)
lines.push('')
// Data Extraction Configuration
lines.push('# ===========================')
lines.push('# 数据提取配置')
lines.push('# ===========================')
lines.push(
`EXTRACTION_BATCH_SIZE=${this.configCache.get('EXTRACTION_BATCH_SIZE') || DEFAULT_SETTINGS.extraction.batchSize}`
)
lines.push(
`EXTRACTION_VERBOSE=${this.configCache.get('EXTRACTION_VERBOSE') || DEFAULT_SETTINGS.extraction.verbose}`
)
lines.push(
`EXTRACTION_AUTO_CONVERT=${this.configCache.get('EXTRACTION_AUTO_CONVERT') || DEFAULT_SETTINGS.extraction.autoConvert}`
)
lines.push(
`EXTRACTION_MERGE_BATCHES=${this.configCache.get('EXTRACTION_MERGE_BATCHES') || DEFAULT_SETTINGS.extraction.mergeBatches}`
)
lines.push(
`EXTRACTION_ENABLE_DB_PERSISTENCE=${this.configCache.get('EXTRACTION_ENABLE_DB_PERSISTENCE') || DEFAULT_SETTINGS.extraction.enableDbPersistence}`
)
lines.push('')
// Validation Configuration
lines.push('# ===========================')
lines.push('# 校验配置')
lines.push('# ===========================')
lines.push(
`VALIDATION_DATA_SOURCE=${this.configCache.get('VALIDATION_DATA_SOURCE') || DEFAULT_SETTINGS.validation.dataSource}`
)
lines.push(
`VALIDATION_USE_DATABASE=${this.configCache.get('VALIDATION_USE_DATABASE') || true}`
)
lines.push(
`VALIDATION_BATCH_SIZE=${this.configCache.get('VALIDATION_BATCH_SIZE') || DEFAULT_SETTINGS.validation.batchSize}`
)
lines.push(
`VALIDATION_ENABLE_CRUD=${this.configCache.get('VALIDATION_ENABLE_CRUD') || DEFAULT_SETTINGS.validation.enableCrud}`
)
lines.push(
`VALIDATION_DEFAULT_MANAGER=${this.configCache.get('VALIDATION_DEFAULT_MANAGER') || DEFAULT_SETTINGS.validation.defaultManager}`
)
lines.push(
`VALIDATION_MATCH_MODE=${this.configCache.get('VALIDATION_MATCH_MODE') || DEFAULT_SETTINGS.validation.matchMode}`
)
lines.push('')
const content = lines.join('\n')
fs.writeFileSync(this.envPath, content, 'utf-8')
this.config = config
log.info('Configuration saved successfully')
return true
} catch (error) {
console.error('[ConfigManager] Failed to save .env file:', error)
log.error('Failed to save configuration', { error })
// 恢复备份
if (fs.existsSync(this.backupPath)) {
fs.copyFileSync(this.backupPath, this.configPath)
}
return false
}
}
/**
* Get all settings as SettingsData object
* Note: ERP configuration is now stored in database, not .env
* The ERP values here are for UI display only and will not be used for actual ERP operations
* 获取完整配置
*/
public getAllSettings(): SettingsData {
return {
erp: {
// ERP config is now from database, these are placeholder defaults for UI
url: DEFAULT_SETTINGS.erp.url,
username: DEFAULT_SETTINGS.erp.username,
password: DEFAULT_SETTINGS.erp.password,
headless: true,
ignoreHttpsErrors: true,
autoCloseBrowser: true
},
database: {
dbType:
(this.get('DB_TYPE', DEFAULT_SETTINGS.database.dbType) as DatabaseType) ||
DEFAULT_SETTINGS.database.dbType,
server: this.get('DB_SERVER', DEFAULT_SETTINGS.database.server),
mysqlHost: this.get('DB_MYSQL_HOST', DEFAULT_SETTINGS.database.mysqlHost),
mysqlPort: this.getNumber('DB_MYSQL_PORT', DEFAULT_SETTINGS.database.mysqlPort),
database: this.get('DB_NAME', DEFAULT_SETTINGS.database.database),
username: this.get('DB_USERNAME', DEFAULT_SETTINGS.database.username),
password: this.get('DB_PASSWORD', DEFAULT_SETTINGS.database.password)
},
paths: {
dataDir: this.get('PATH_DATA_DIR', DEFAULT_SETTINGS.paths.dataDir),
defaultOutput: this.get('PATH_DEFAULT_OUTPUT', DEFAULT_SETTINGS.paths.defaultOutput),
validationOutput: this.get(
'PATH_VALIDATION_OUTPUT',
DEFAULT_SETTINGS.paths.validationOutput
)
},
extraction: {
batchSize: this.getNumber('EXTRACTION_BATCH_SIZE', DEFAULT_SETTINGS.extraction.batchSize),
verbose: this.getBoolean('EXTRACTION_VERBOSE', DEFAULT_SETTINGS.extraction.verbose),
autoConvert: this.getBoolean(
'EXTRACTION_AUTO_CONVERT',
DEFAULT_SETTINGS.extraction.autoConvert
),
mergeBatches: this.getBoolean(
'EXTRACTION_MERGE_BATCHES',
DEFAULT_SETTINGS.extraction.mergeBatches
),
enableDbPersistence: this.getBoolean(
'EXTRACTION_ENABLE_DB_PERSISTENCE',
DEFAULT_SETTINGS.extraction.enableDbPersistence
)
},
validation: {
dataSource:
(this.get(
'VALIDATION_DATA_SOURCE',
DEFAULT_SETTINGS.validation.dataSource
) as ValidationDataSource) || DEFAULT_SETTINGS.validation.dataSource,
batchSize: this.getNumber('VALIDATION_BATCH_SIZE', DEFAULT_SETTINGS.validation.batchSize),
matchMode:
(this.get('VALIDATION_MATCH_MODE', DEFAULT_SETTINGS.validation.matchMode) as MatchMode) ||
DEFAULT_SETTINGS.validation.matchMode,
enableCrud: this.getBoolean(
'VALIDATION_ENABLE_CRUD',
DEFAULT_SETTINGS.validation.enableCrud
),
defaultManager: this.get(
'VALIDATION_DEFAULT_MANAGER',
DEFAULT_SETTINGS.validation.defaultManager
)
}
public getConfig(): FullConfig {
if (!this.config) {
throw new Error('Configuration not initialized. Call initialize() first.')
}
return this.config
}
/**
* Save settings from SettingsData object
* Note: ERP settings are NOT saved to .env anymore - they are stored in the database
* 获取当前激活的数据库配置
*/
public async saveAllSettings(settings: SettingsData): Promise<boolean> {
// ERP settings are now stored in the database (dbo_BIPUsers table)
// They are NOT saved to .env file anymore
public getActiveDatabaseConfig(): MySqlConfig | SqlServerConfig {
if (!this.config) {
throw new Error('Configuration not initialized')
}
// Database settings
this.set('DB_TYPE', settings.database.dbType)
this.set('DB_SERVER', settings.database.server)
this.set('DB_MYSQL_HOST', settings.database.mysqlHost)
this.set('DB_MYSQL_PORT', settings.database.mysqlPort)
this.set('DB_NAME', settings.database.database)
this.set('DB_USERNAME', settings.database.username)
this.set('DB_PASSWORD', settings.database.password)
// Path settings
this.set('PATH_DATA_DIR', settings.paths.dataDir)
this.set('PATH_DEFAULT_OUTPUT', settings.paths.defaultOutput)
this.set('PATH_VALIDATION_OUTPUT', settings.paths.validationOutput)
// Extraction settings
this.set('EXTRACTION_BATCH_SIZE', settings.extraction.batchSize)
this.set('EXTRACTION_VERBOSE', settings.extraction.verbose)
this.set('EXTRACTION_AUTO_CONVERT', settings.extraction.autoConvert)
this.set('EXTRACTION_MERGE_BATCHES', settings.extraction.mergeBatches)
this.set('EXTRACTION_ENABLE_DB_PERSISTENCE', settings.extraction.enableDbPersistence)
// Validation settings
this.set('VALIDATION_DATA_SOURCE', settings.validation.dataSource)
this.set('VALIDATION_BATCH_SIZE', settings.validation.batchSize)
this.set('VALIDATION_MATCH_MODE', settings.validation.matchMode)
this.set('VALIDATION_ENABLE_CRUD', settings.validation.enableCrud)
this.set('VALIDATION_DEFAULT_MANAGER', settings.validation.defaultManager)
return this.save()
const { activeType, mysql, sqlserver } = this.config.database
return activeType === 'mysql' ? mysql : sqlserver
}
/**
* Save partial settings (only update provided fields)
* Preserves all existing fields not included in the update
* 获取数据库类型
*/
public async savePartialSettings(
settings: Partial<SettingsData>
public getDatabaseType(): DatabaseType {
if (!this.config) {
throw new Error('Configuration not initialized')
}
return this.config.database.activeType
}
/**
* 更新部分配置(深合并)
*/
public async updateConfig(
updates: Partial<FullConfig>
): Promise<{ success: boolean; error?: string }> {
try {
// Step 1: Validate field whitelist
const validation = validateEditableFields(settings)
if (!validation.valid) {
log.warn('Attempted to save non-editable fields', {
invalidFields: validation.invalidFields
})
return {
success: false,
error: `包含不允许修改的字段:${validation.invalidFields.join(', ')}`
}
if (!this.config) {
await this.loadConfig()
}
// Step 2: Read current settings from .env file directly
// This avoids the cache key mismatch issue (ERP_URL vs erp.url)
await this.loadEnvFile()
const currentSettings = this.getAllSettings()
// 深合并
const merged = this.deepMerge(this.config!, updates)
log.info('Current settings before merge', {
erpUrl: currentSettings.erp.url,
dbType: currentSettings.database.dbType,
dbName: currentSettings.database.database
})
// 验证合并后的配置
const validated = fullConfigSchema.parse(merged)
// Step 3: Deep merge - only update provided fields
const mergedSettings = deepMerge(currentSettings, settings)
log.info('Settings after merge', {
erpUrl: mergedSettings.erp.url,
dbType: mergedSettings.database.dbType,
dbName: mergedSettings.database.database
})
// Step 4: Backup and save
const backupSuccess = await this.backupEnvFile()
if (!backupSuccess) {
log.warn('Failed to backup .env file, proceeding with caution')
const success = await this.saveConfig(validated)
if (!success) {
return { success: false, error: '保存配置失败' }
}
const saveSuccess = await this.saveAllSettings(mergedSettings)
if (!saveSuccess) {
// Save failed, attempt restore
await this.restoreBackup()
return {
success: false,
error: '保存配置失败,已恢复原配置'
}
}
// Step 5: Reload from disk to populate cache with correct keys (ERP_URL instead of erp.url)
await this.loadEnvFile()
log.info('Settings saved successfully', {
updatedFields: Object.keys(settings)
})
return { success: true }
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'
log.error('Error in savePartialSettings', { error: message })
await this.restoreBackup()
return {
success: false,
error: `保存配置时发生错误:${message}`
if (error instanceof z.ZodError) {
const messages = error.issues.map((e: any) => `${e.path.join('.')}: ${e.message}`)
return { success: false, error: `配置验证失败:\n${messages.join('\n')}` }
}
return { success: false, error: error instanceof Error ? error.message : '未知错误' }
}
}
/**
* Reset to default settings
* 深合并工具函数
*/
public resetToDefaults(): SettingsData {
// Clear cache and reload from defaults
this.configCache.clear()
// Set all defaults using underscore uppercase keys
this.set('ERP_URL', DEFAULT_SETTINGS.erp.url)
this.set('ERP_USERNAME', DEFAULT_SETTINGS.erp.username)
this.set('ERP_PASSWORD', DEFAULT_SETTINGS.erp.password)
this.set('DB_TYPE', DEFAULT_SETTINGS.database.dbType)
this.set('DB_SERVER', DEFAULT_SETTINGS.database.server)
this.set('DB_MYSQL_HOST', DEFAULT_SETTINGS.database.mysqlHost)
this.set('DB_MYSQL_PORT', DEFAULT_SETTINGS.database.mysqlPort)
this.set('DB_NAME', DEFAULT_SETTINGS.database.database)
this.set('DB_USERNAME', DEFAULT_SETTINGS.database.username)
this.set('DB_PASSWORD', DEFAULT_SETTINGS.database.password)
this.set('PATH_DATA_DIR', DEFAULT_SETTINGS.paths.dataDir)
this.set('PATH_DEFAULT_OUTPUT', DEFAULT_SETTINGS.paths.defaultOutput)
this.set('PATH_VALIDATION_OUTPUT', DEFAULT_SETTINGS.paths.validationOutput)
this.set('EXTRACTION_BATCH_SIZE', DEFAULT_SETTINGS.extraction.batchSize)
this.set('EXTRACTION_VERBOSE', DEFAULT_SETTINGS.extraction.verbose)
this.set('EXTRACTION_AUTO_CONVERT', DEFAULT_SETTINGS.extraction.autoConvert)
this.set('EXTRACTION_MERGE_BATCHES', DEFAULT_SETTINGS.extraction.mergeBatches)
this.set('EXTRACTION_ENABLE_DB_PERSISTENCE', DEFAULT_SETTINGS.extraction.enableDbPersistence)
this.set('VALIDATION_DATA_SOURCE', DEFAULT_SETTINGS.validation.dataSource)
this.set('VALIDATION_BATCH_SIZE', DEFAULT_SETTINGS.validation.batchSize)
this.set('VALIDATION_MATCH_MODE', DEFAULT_SETTINGS.validation.matchMode)
this.set('VALIDATION_ENABLE_CRUD', DEFAULT_SETTINGS.validation.enableCrud)
this.set('VALIDATION_DEFAULT_MANAGER', DEFAULT_SETTINGS.validation.defaultManager)
return DEFAULT_SETTINGS
}
/**
* Get default settings
*/
public getDefaultSettings(): SettingsData {
return DEFAULT_SETTINGS
}
/**
* Backup current .env file
*/
private async backupEnvFile(): Promise<boolean> {
try {
if (fs.existsSync(this.envPath)) {
fs.copyFileSync(this.envPath, this.backupPath)
log.debug('Backup created', { path: this.backupPath })
return true
private deepMerge<T extends Record<string, any>>(source: T, target: Partial<T>): T {
const result = { ...source }
for (const key in target) {
if (target[key] !== undefined) {
if (
typeof target[key] === 'object' &&
target[key] !== null &&
!Array.isArray(target[key])
) {
result[key] = this.deepMerge(result[key] as any, target[key] as any)
} else {
result[key] = target[key] as any
}
}
return false
} catch (error) {
log.error('Failed to backup .env file', { error })
return false
}
return result
}
/**
* Restore .env file from backup
* 重置为默认配置
*/
private async restoreBackup(): Promise<boolean> {
try {
if (fs.existsSync(this.backupPath)) {
fs.copyFileSync(this.backupPath, this.envPath)
await this.loadEnvFile()
log.debug('Restored from backup')
return true
}
return false
} catch (error) {
log.error('Failed to restore backup', { error })
return false
public async resetToDefaults(): Promise<boolean> {
return this.saveConfig(DEFAULT_CONFIG)
}
/**
* 获取默认配置
*/
public getDefaultConfig(): FullConfig {
return DEFAULT_CONFIG
}
/**
* 导出配置为 YAML 字符串(用于 UI 显示或导出)
*/
public exportToYaml(): string {
if (!this.config) {
throw new Error('Configuration not initialized')
}
return yaml.dump(this.config, {
indent: 2,
lineWidth: -1,
noRefs: true
})
}
}

View File

@@ -2,21 +2,23 @@
* TypeORM Data Source Configuration
*
* Provides a centralized database connection for TypeORM entities.
* Supports both MySQL and SQL Server based on DB_TYPE environment variable.
* Supports both MySQL and SQL Server based on configuration.
*
* Note: Configuration is now loaded from config.yaml via ConfigManager,
* not from environment variables.
*/
import 'reflect-metadata'
import { DataSource, DataSourceOptions } from 'typeorm'
import { ConfigManager } from '../config/config-manager'
/**
* Get database type from environment
* Get database type from config manager
*/
function getDatabaseType(): 'mysql' | 'mssql' {
const dbType = process.env.DB_TYPE?.toLowerCase()
if (dbType === 'sqlserver' || dbType === 'mssql') {
return 'mssql'
}
return 'mysql'
const configManager = ConfigManager.getInstance()
const dbType = configManager.getDatabaseType()
return dbType === 'sqlserver' ? 'mssql' : 'mysql'
}
/**
@@ -24,36 +26,40 @@ function getDatabaseType(): 'mysql' | 'mssql' {
*/
function buildDataSourceOptions(): DataSourceOptions {
const type = getDatabaseType()
const configManager = ConfigManager.getInstance()
const config = configManager.getConfig()
const commonOptions: Partial<DataSourceOptions> = {
entities: [__dirname + '/entities/*.{ts,js}'],
synchronize: false, // Never auto-sync in production
logging: process.env.NODE_ENV !== 'production'
logging: false
}
if (type === 'mssql') {
const dbConfig = config.database.sqlserver
return {
type: 'mssql',
host: process.env.DB_SERVER || 'localhost',
port: parseInt(process.env.DB_SQLSERVER_PORT || '1433', 10),
username: process.env.DB_USERNAME || 'sa',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || '',
host: dbConfig.server,
port: dbConfig.port,
username: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database,
options: {
encrypt: false,
trustServerCertificate: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
trustServerCertificate: dbConfig.trustServerCertificate
},
...commonOptions
} as DataSourceOptions
}
const dbConfig = config.database.mysql
return {
type: 'mysql',
host: process.env.DB_MYSQL_HOST || 'localhost',
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
username: process.env.DB_USERNAME || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || '',
host: dbConfig.host,
port: dbConfig.port,
username: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database,
...commonOptions
} as DataSourceOptions
}

View File

@@ -5,6 +5,7 @@
* Supports both MySQL and SQL Server databases.
*/
import { ConfigManager } from '../config/config-manager'
import { MySqlService } from './mysql'
import { SqlServerService } from './sql-server'
import type {
@@ -23,42 +24,43 @@ const log = createLogger('DatabaseFactory')
const instances: Map<DatabaseType, IDatabaseService> = new Map()
/**
* Get the current database type from environment
* Get the current database type from config manager
*/
export function getDatabaseType(): DatabaseType {
const dbType = process.env.DB_TYPE?.toLowerCase()
if (dbType === 'sqlserver' || dbType === 'mssql') {
return 'sqlserver'
}
return 'mysql'
const configManager = ConfigManager.getInstance()
return configManager.getDatabaseType()
}
/**
* Create MySQL configuration from environment variables
* Create MySQL configuration from config manager
*/
export function createMySqlConfig(): MySqlConfig {
const configManager = ConfigManager.getInstance()
const dbConfig = configManager.getConfig().database.mysql
return {
host: process.env.DB_MYSQL_HOST || 'localhost',
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
user: process.env.DB_USERNAME || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || ''
host: dbConfig.host,
port: dbConfig.port,
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database
}
}
/**
* Create SQL Server configuration from environment variables
* Create SQL Server configuration from config manager
*/
export function createSqlServerConfig(): SqlServerConfig {
const configManager = ConfigManager.getInstance()
const dbConfig = configManager.getConfig().database.sqlserver
return {
server: process.env.DB_SERVER || 'localhost',
port: parseInt(process.env.DB_SQLSERVER_PORT || '1433', 10),
user: process.env.DB_USERNAME || 'sa',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || '',
server: dbConfig.server,
port: dbConfig.port,
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database,
options: {
encrypt: false,
trustServerCertificate: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
trustServerCertificate: dbConfig.trustServerCertificate
}
}
}
@@ -68,7 +70,7 @@ export function createSqlServerConfig(): SqlServerConfig {
*
* Uses singleton pattern - returns cached instance if available.
*
* @param type - Optional database type override (defaults to DB_TYPE env var)
* @param type - Optional database type override (defaults to config)
* @returns Database service instance
*/
export async function create(type?: DatabaseType): Promise<IDatabaseService> {
@@ -105,7 +107,7 @@ export async function create(type?: DatabaseType): Promise<IDatabaseService> {
/**
* Get existing database service without creating new one
*
* @param type - Optional database type (defaults to DB_TYPE env var)
* @param type - Optional database type (defaults to config)
* @returns Database service instance or undefined
*/
export function get(type?: DatabaseType): IDatabaseService | undefined {

View File

@@ -7,14 +7,12 @@
* - productionID format: 2 digits + 1 letter + serial number (e.g., "22A1", "22A1234")
* - 生产订单号 format: SC + 14 digits (e.g., "SC70202602120085")
*
* Database table: productionContractData_26年压力表合同数据
* Fields: 总排号 (productionID), 生产订单号 (production order number)
* Database table and field names are loaded from config.yaml
*/
import type { IDatabaseService } from '../database'
import { SqlServerService } from '../database/sql-server'
import { ConfigManager } from '../config/config-manager'
import { createLogger } from '../logger'
import sql from 'mssql'
const log = createLogger('OrderResolver')
@@ -28,49 +26,52 @@ export interface OrderMapping {
productionId?: string
/** Final production order number to use */
orderNumber?: string
/** Whether this mapping is valid */
isValid: boolean
/** Error or warning message */
/** Whether the order number was successfully resolved */
resolved: boolean
/** Error message if resolution failed */
error?: string
/** Input type */
inputType: 'productionId' | 'orderNumber' | 'unknown'
}
/**
* Order number type recognition result
*/
export type OrderNumberType = 'productionId' | 'orderNumber' | 'unknown'
/**
* Resolution statistics
*/
export interface ResolutionStats {
totalInputs: number
recognizedAsProductionId: number
recognizedAsOrderNumber: number
validOrderNumbers: number
validProductionIds: number
resolvedCount: number
failedCount: number
unknownFormat: number
successfullyResolved: number
failedToResolve: number
notFoundInDatabase: number
}
/**
* Regular expression patterns
* ProductionID pattern: 2 digits + 1 letter + 1-4 digits
*/
export const ORDER_PATTERNS = {
/** productionID: 2 digits + 1 letter + serial number (1+) */
PRODUCTION_ID: /^\d{2}[A-Za-z]\d+$/,
/** 生产订单号:SC + 14 digits */
ORDER_NUMBER: /^SC\d{14}$/
} as const
const PRODUCTION_ID_PATTERN = /^\d{2}[A-Z]\d{1,4}$/i
/**
* Production order number pattern: SC + 14 digits
*/
const ORDER_NUMBER_PATTERN = /^SC\d{14}$/i
/**
* Database table and field names
* Can be overridden via environment variables:
* - DB_TABLE_NAME: Table name (default: 'productionContractData_26年压力表合同数据')
* - DB_FIELD_PRODUCTION_ID: Field name for productionID (default: '总排号')
* - DB_FIELD_ORDER_NUMBER: Field name for order number (default: '生产订单号')
* Loaded from config.yaml via ConfigManager
*/
export const DB_CONFIG = {
TABLE_NAME: process.env.DB_TABLE_NAME || 'productionContractData_26年压力表合同数据',
FIELD_PRODUCTION_ID: process.env.DB_FIELD_PRODUCTION_ID || '总排号',
FIELD_ORDER_NUMBER: process.env.DB_FIELD_ORDER_NUMBER || '生产订单号'
} as const
export function getDbConfig() {
const configManager = ConfigManager.getInstance()
const config = configManager.getConfig()
return {
TABLE_NAME: config.orderResolution.tableName || 'productionContractData_26 年压力表合同数据',
FIELD_PRODUCTION_ID: config.orderResolution.productionIdField || '总排号',
FIELD_ORDER_NUMBER: config.orderResolution.orderNumberField || '生产订单号'
}
}
/**
* Order Number Resolver Service
@@ -84,364 +85,201 @@ export class OrderNumberResolver {
/**
* Get table name based on database type
* Converts MySQL schema_tablename format to SQL Server [schema].[tablename] format
* e.g., productionContractData_26年压力表合同数据 -> [productionContractData].[26年压力表合同数据]
*/
private getTableName(mysqlTableName: string): string {
private getTableName(tableName: string): string {
if (this.dbService.type === 'sqlserver') {
const firstUnderscoreIndex = mysqlTableName.indexOf('_')
if (firstUnderscoreIndex > 0) {
const schema = mysqlTableName.substring(0, firstUnderscoreIndex)
const tableName = mysqlTableName.substring(firstUnderscoreIndex + 1)
return `[${schema}].[${tableName}]`
}
return `[dbo].[${mysqlTableName}]`
return `[dbo].[${tableName}]`
}
return mysqlTableName
return tableName
}
/**
* Recognize the type of an input string
* @param input - The input string to recognize
* @returns The recognized type
* Check if input matches productionID pattern
*/
recognizeType(input: string): 'productionId' | 'orderNumber' | 'unknown' {
const trimmed = input.trim()
if (ORDER_PATTERNS.ORDER_NUMBER.test(trimmed)) {
return 'orderNumber'
}
if (ORDER_PATTERNS.PRODUCTION_ID.test(trimmed)) {
return 'productionId'
}
return 'unknown'
isProductionId(input: string): boolean {
return PRODUCTION_ID_PATTERN.test(input)
}
/**
* Resolve a list of inputs to production order numbers
* @param inputs - List of input strings (can be productionID or 生产订单号)
* @returns List of order mappings
* Check if input matches order number pattern
*/
async resolve(inputs: string[]): Promise<OrderMapping[]> {
const mappings: OrderMapping[] = []
const stats: ResolutionStats = {
totalInputs: inputs.length,
recognizedAsProductionId: 0,
recognizedAsOrderNumber: 0,
unknownFormat: 0,
successfullyResolved: 0,
failedToResolve: 0,
notFoundInDatabase: 0
}
// First pass: recognize types and categorize
const productionIds: string[] = []
const orderNumbers: string[] = []
for (const input of inputs) {
const trimmed = input.trim()
if (!trimmed) continue
const type = this.recognizeType(trimmed)
const baseMapping: OrderMapping = {
input: trimmed,
isValid: false,
inputType: type
}
if (type === 'productionId') {
stats.recognizedAsProductionId++
productionIds.push(trimmed)
baseMapping.productionId = trimmed
} else if (type === 'orderNumber') {
stats.recognizedAsOrderNumber++
orderNumbers.push(trimmed)
baseMapping.orderNumber = trimmed
baseMapping.isValid = true // Order numbers are valid by format
stats.successfullyResolved++
} else {
stats.unknownFormat++
baseMapping.error = `无法识别的格式:${trimmed}`
mappings.push(baseMapping)
continue
}
mappings.push(baseMapping)
}
// Query database for productionIDs
if (productionIds.length > 0) {
const productionIdMappings = await this.resolveProductionIds(productionIds)
// Update mappings with database results
for (const mapping of mappings) {
if (mapping.inputType === 'productionId') {
const dbResult = productionIdMappings.find((m) => m.input === mapping.input)
if (dbResult) {
mapping.orderNumber = dbResult.orderNumber
mapping.isValid = dbResult.isValid
mapping.error = dbResult.error
if (dbResult.isValid) {
stats.successfullyResolved++
} else {
stats.failedToResolve++
}
}
}
}
}
// Verify order numbers exist in database (optional validation)
// This can be skipped if you want to allow any SC+14digits format
// For now, we'll verify them against the database
if (orderNumbers.length > 0) {
const verifiedOrderNumbers = new Set(await this.verifyOrderNumbers(orderNumbers))
for (const mapping of mappings) {
if (mapping.inputType === 'orderNumber' && mapping.orderNumber) {
if (!verifiedOrderNumbers.has(mapping.orderNumber)) {
mapping.isValid = false
mapping.error = `生产订单号不存在于数据库中:${mapping.orderNumber}`
stats.notFoundInDatabase++
stats.successfullyResolved--
stats.failedToResolve++
}
}
}
}
return mappings
isOrderNumber(input: string): boolean {
return ORDER_NUMBER_PATTERN.test(input)
}
/**
* Resolve productionIDs to production order numbers via database lookup
* @param productionIds - List of productionIDs to resolve
* @returns List of order mappings
* Map productionID to order number via database lookup
*/
private async resolveProductionIds(productionIds: string[]): Promise<OrderMapping[]> {
const mappings: OrderMapping[] = []
if (!this.dbService.isConnected()) {
// Database not connected, return all as failed
for (const pid of productionIds) {
mappings.push({
input: pid,
productionId: pid,
isValid: false,
error: '数据库未连接,无法查询生产订单号',
inputType: 'productionId'
})
}
return mappings
}
async mapProductionIdToOrderNumber(productionId: string): Promise<string | null> {
try {
const isSqlServer = this.dbService.type === 'sqlserver'
const tableName = this.getTableName(DB_CONFIG.TABLE_NAME)
const dbConfig = getDbConfig()
const tableName = this.getTableName(dbConfig.TABLE_NAME)
log.debug('Resolving production IDs', {
count: productionIds.length,
dbType: this.dbService.type
})
let sql: string
let params: any[]
let result
if (isSqlServer) {
// Use queryWithParams for SQL Server with explicit parameter types
const placeholders = productionIds.map((_, idx) => `@p${idx}`).join(', ')
const params: Record<
string,
{
value: string
type: sql.ISqlType | sql.ISqlTypeFactoryWithLength | sql.ISqlTypeWithLength
}
> = {}
productionIds.forEach((id, idx) => {
params[`p${idx}`] = { value: id, type: sql.NVarChar(255) }
})
const query = `
SELECT ${DB_CONFIG.FIELD_PRODUCTION_ID}, ${DB_CONFIG.FIELD_ORDER_NUMBER}
FROM ${tableName}
WHERE ${DB_CONFIG.FIELD_PRODUCTION_ID} IN (${placeholders})
`
result = await (this.dbService as SqlServerService).queryWithParams(query, params)
if (this.dbService.type === 'sqlserver') {
sql = `SELECT TOP 1 [${dbConfig.FIELD_ORDER_NUMBER}] FROM ${tableName} WHERE [${dbConfig.FIELD_PRODUCTION_ID}] = @p0`
params = [productionId]
} else {
// Use standard query for MySQL
const placeholders = productionIds.map(() => '?').join(', ')
const query = `
SELECT \`${DB_CONFIG.FIELD_PRODUCTION_ID}\`, \`${DB_CONFIG.FIELD_ORDER_NUMBER}\`
FROM ${tableName}
WHERE \`${DB_CONFIG.FIELD_PRODUCTION_ID}\` IN (${placeholders})
`
result = await this.dbService.query(query, productionIds)
sql = `SELECT \`${dbConfig.FIELD_ORDER_NUMBER}\` FROM \`${tableName}\` WHERE \`${dbConfig.FIELD_PRODUCTION_ID}\` = ? LIMIT 1`
params = [productionId]
}
// Create a map for quick lookup (use lowercase key for case-insensitive matching)
const resultMap = new Map<string, string>()
const result = await this.dbService.query(sql, params)
if (result.rows.length > 0) {
const orderNumber = result.rows[0][Object.keys(result.rows[0])[0]] as string
return orderNumber || null
}
return null
} catch (error) {
const message = error instanceof Error ? error.message : '未知数据库错误'
log.error('Failed to map productionID to order number', {
productionId,
error: message
})
throw error
}
}
/**
* Map multiple productionIds to order numbers
*/
async mapProductionIdsToOrderNumbers(productionIds: string[]): Promise<Map<string, string>> {
try {
const dbConfig = getDbConfig()
const tableName = this.getTableName(dbConfig.TABLE_NAME)
if (productionIds.length === 0) {
return new Map()
}
// Use parameterized query to prevent SQL injection
const placeholders = productionIds.map((_, i) => `@p${i}`).join(', ')
const params = productionIds
let sql: string
if (this.dbService.type === 'sqlserver') {
sql = `SELECT [${dbConfig.FIELD_PRODUCTION_ID}], [${dbConfig.FIELD_ORDER_NUMBER}] FROM ${tableName} WHERE [${dbConfig.FIELD_PRODUCTION_ID}] IN (${placeholders})`
} else {
const idPlaceholders = productionIds.map(() => '?').join(', ')
sql = `SELECT \`${dbConfig.FIELD_PRODUCTION_ID}\`, \`${dbConfig.FIELD_ORDER_NUMBER}\` FROM \`${tableName}\` WHERE \`${dbConfig.FIELD_PRODUCTION_ID}\` IN (${idPlaceholders})`
}
const result = await this.dbService.query(sql, params)
const mappings = new Map<string, string>()
for (const row of result.rows) {
const prodId = row[DB_CONFIG.FIELD_PRODUCTION_ID] as string
const orderNum = row[DB_CONFIG.FIELD_ORDER_NUMBER] as string
const keys = Object.keys(row)
const prodId = row[keys[0]] as string
const orderNum = row[keys[1]] as string
if (prodId && orderNum) {
// Store with lowercase key for case-insensitive matching
resultMap.set(prodId.toLowerCase(), orderNum)
}
}
// Build mappings
for (const pid of productionIds) {
// Use lowercase for case-insensitive lookup
const orderNumber = resultMap.get(pid.toLowerCase())
if (orderNumber) {
mappings.push({
input: pid,
productionId: pid,
orderNumber,
isValid: true,
inputType: 'productionId'
})
} else {
mappings.push({
input: pid,
productionId: pid,
isValid: false,
error: `数据库中未找到生产 ID${pid}`,
inputType: 'productionId'
})
mappings.set(prodId, orderNum)
}
}
return mappings
} catch (error) {
const message = error instanceof Error ? error.message : '未知数据库错误'
// Return all as failed with error
return productionIds.map((pid) => ({
input: pid,
productionId: pid,
isValid: false,
error: `数据库查询失败:${message}`,
inputType: 'productionId'
}))
log.error('Failed to map productionIds to order numbers', {
error: message
})
throw error
}
}
/**
* Verify that order numbers exist in the database
* @param orderNumbers - List of order numbers to verify
* @returns List of valid order numbers
* Resolve order numbers from mixed input
*/
private async verifyOrderNumbers(orderNumbers: string[]): Promise<string[]> {
if (!this.dbService.isConnected()) {
return orderNumbers // Skip verification if not connected
}
async resolve(inputs: string[]): Promise<OrderMapping[]> {
const mappings: OrderMapping[] = []
try {
const isSqlServer = this.dbService.type === 'sqlserver'
const tableName = this.getTableName(DB_CONFIG.TABLE_NAME)
for (const input of inputs) {
const mapping: OrderMapping = { input, resolved: false }
let result
if (isSqlServer) {
// Use queryWithParams for SQL Server with explicit parameter types
const placeholders = orderNumbers.map((_, idx) => `@p${idx}`).join(', ')
const params: Record<
string,
{
value: string
type: sql.ISqlType | sql.ISqlTypeFactoryWithLength | sql.ISqlTypeWithLength
if (this.isOrderNumber(input)) {
// Already an order number
mapping.orderNumber = input
mapping.resolved = true
} else if (this.isProductionId(input)) {
// Is a productionID, need to lookup
mapping.productionId = input
try {
const orderNumber = await this.mapProductionIdToOrderNumber(input)
if (orderNumber) {
mapping.orderNumber = orderNumber
mapping.resolved = true
} else {
mapping.error = '未在数据库中找到对应的订单号'
}
> = {}
orderNumbers.forEach((id, idx) => {
params[`p${idx}`] = { value: id, type: sql.NVarChar(255) }
})
const query = `
SELECT ${DB_CONFIG.FIELD_ORDER_NUMBER}
FROM ${tableName}
WHERE ${DB_CONFIG.FIELD_ORDER_NUMBER} IN (${placeholders})
`
result = await (this.dbService as SqlServerService).queryWithParams(query, params)
} catch (error) {
mapping.error = error instanceof Error ? error.message : '数据库查询失败'
log.warn('Failed to resolve productionID', { productionId: input, error })
}
} else {
// Use standard query for MySQL
const placeholders = orderNumbers.map(() => '?').join(', ')
const query = `
SELECT \`${DB_CONFIG.FIELD_ORDER_NUMBER}\`
FROM ${tableName}
WHERE \`${DB_CONFIG.FIELD_ORDER_NUMBER}\` IN (${placeholders})
`
result = await this.dbService.query(query, orderNumbers)
mapping.error = '格式不识别:既不是有效的生产订单号也不是总排号格式'
}
return result.rows.map((row) => row[DB_CONFIG.FIELD_ORDER_NUMBER] as string)
} catch (error) {
console.warn('[OrderResolver] Failed to verify order numbers:', error)
return orderNumbers // Skip verification on error
mappings.push(mapping)
}
return mappings
}
/**
* Get valid order numbers from mappings
*/
getValidOrderNumbers(mappings: OrderMapping[]): string[] {
return mappings.filter((m) => m.resolved && m.orderNumber).map((m) => m.orderNumber!)
}
/**
* Get warnings from failed mappings
*/
getWarnings(mappings: OrderMapping[]): string[] {
return mappings.filter((m) => !m.resolved && m.error).map((m) => `${m.input}: ${m.error}`)
}
/**
* Recognize the type of input
*/
recognizeType(input: string): OrderNumberType {
if (this.isOrderNumber(input)) return 'orderNumber'
if (this.isProductionId(input)) return 'productionId'
return 'unknown'
}
/**
* Get resolution statistics
* @param mappings - List of order mappings
* @returns Resolution statistics
*/
getStats(mappings: OrderMapping[]): ResolutionStats {
const stats: ResolutionStats = {
totalInputs: mappings.length,
recognizedAsProductionId: 0,
recognizedAsOrderNumber: 0,
unknownFormat: 0,
successfullyResolved: 0,
failedToResolve: 0,
notFoundInDatabase: 0
validOrderNumbers: 0,
validProductionIds: 0,
resolvedCount: 0,
failedCount: 0,
unknownFormat: 0
}
for (const mapping of mappings) {
if (mapping.inputType === 'productionId') {
stats.recognizedAsProductionId++
} else if (mapping.inputType === 'orderNumber') {
stats.recognizedAsOrderNumber++
if (mapping.resolved) {
stats.resolvedCount++
if (mapping.orderNumber && !mapping.productionId) {
stats.validOrderNumbers++
} else if (mapping.productionId) {
stats.validProductionIds++
}
} else {
stats.unknownFormat++
}
if (mapping.isValid) {
stats.successfullyResolved++
} else if (mapping.error?.includes('不存在于数据库中')) {
stats.notFoundInDatabase++
stats.failedToResolve++
} else if (mapping.error) {
stats.failedToResolve++
stats.failedCount++
if (!mapping.productionId && !mapping.orderNumber) {
stats.unknownFormat++
}
}
}
return stats
}
/**
* Extract valid order numbers from mappings
* @param mappings - List of order mappings
* @returns List of valid production order numbers
*/
getValidOrderNumbers(mappings: OrderMapping[]): string[] {
return mappings.filter((m) => m.isValid && m.orderNumber).map((m) => m.orderNumber!)
}
/**
* Extract warnings/errors from mappings
* @param mappings - List of order mappings
* @returns List of warning messages
*/
getWarnings(mappings: OrderMapping[]): string[] {
return mappings.filter((m) => !m.isValid && m.error).map((m) => m.error!)
}
}

View File

@@ -54,7 +54,7 @@ const createFileTransport = (level?: string): DailyRotateFile => {
// Create the logger instance
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
level: 'info', // Log level is now hardcoded, can be moved to config.yaml if needed
defaultMeta: { service: 'erpauto' },
transports: [
// Console transport - always enabled
@@ -67,7 +67,7 @@ const logger = winston.createLogger({
})
// Add error-specific file transport in production
if (process.env.NODE_ENV === 'production') {
if (app.isPackaged) {
logger.add(
new DailyRotateFile({
filename: path.join(getLogDir(), 'error-%DATE%.log'),

View File

@@ -10,6 +10,7 @@
import { MySqlService } from '../database/mysql'
import { SqlServerService } from '../database/sql-server'
import { ConfigManager } from '../config/config-manager'
import sql from 'mssql'
import type { UserInfo } from '../../types/user.types'
@@ -43,17 +44,14 @@ export class BIPUsersDAO {
private mysqlService: MySqlService | null = null
private sqlServerService: SqlServerService | null = null
private dbType: 'mysql' | 'sqlserver' = 'mysql'
private configManager: ConfigManager
/**
* Constructor - determine database type from environment
* Constructor - get database type from ConfigManager
*/
constructor() {
const dbType = process.env.DB_TYPE?.toLowerCase()
if (dbType === 'sqlserver' || dbType === 'mssql') {
this.dbType = 'sqlserver'
} else {
this.dbType = 'mysql'
}
this.configManager = ConfigManager.getInstance()
this.dbType = this.configManager.getDatabaseType()
}
/**
@@ -69,20 +67,23 @@ export class BIPUsersDAO {
* Get database service instance (MySQL or SQL Server)
*/
private async getDatabaseService(): Promise<MySqlService | SqlServerService> {
const config = this.configManager.getConfig()
if (this.dbType === 'sqlserver') {
if (this.sqlServerService && this.sqlServerService.isConnected()) {
return this.sqlServerService
}
const dbConfig = config.database.sqlserver
this.sqlServerService = new SqlServerService({
server: process.env.DB_SERVER || 'localhost',
port: parseInt(process.env.DB_SQLSERVER_PORT || '1433', 10),
user: process.env.DB_USERNAME || 'sa',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || '',
server: dbConfig.server,
port: dbConfig.port,
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database,
options: {
encrypt: false,
trustServerCertificate: process.env.DB_TRUST_SERVER_CERTIFICATE === 'yes'
trustServerCertificate: dbConfig.trustServerCertificate
}
})
@@ -93,12 +94,13 @@ export class BIPUsersDAO {
return this.mysqlService
}
const dbConfig = config.database.mysql
this.mysqlService = new MySqlService({
host: process.env.DB_MYSQL_HOST || 'localhost',
port: parseInt(process.env.DB_MYSQL_PORT || '3306', 10),
user: process.env.DB_USERNAME || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || ''
host: dbConfig.host,
port: dbConfig.port,
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database
})
await this.mysqlService.connect()
@@ -485,12 +487,11 @@ export class BIPUsersDAO {
}
/**
* Get ERP configuration for a user
* @param username - The username to get ERP config for
* @returns ERP configuration object or null if not found
* Get ERP credentials for a user (username and password only, URL is from config.yaml)
* @param username - The username to get ERP credentials for
* @returns ERP credentials object or null if not found
*/
async getUserErpConfig(username: string): Promise<{
url: string
async getUserErpCredentials(username: string): Promise<{
username: string
password: string
} | null> {
@@ -501,7 +502,7 @@ export class BIPUsersDAO {
if (this.dbType === 'sqlserver') {
const sqlString = `
SELECT ${cols.ERP_URL}, ${cols.ERP_USERNAME}, ${cols.ERP_PASSWORD}
SELECT ${cols.ERP_USERNAME}, ${cols.ERP_PASSWORD}
FROM ${tableName}
WHERE UserName = @username
`
@@ -513,7 +514,6 @@ export class BIPUsersDAO {
if (result.rows.length > 0) {
const row = result.rows[0]
return {
url: (row[cols.ERP_URL] as string) || '',
username: (row[cols.ERP_USERNAME] as string) || '',
password: (row[cols.ERP_PASSWORD] as string) || ''
}
@@ -521,7 +521,7 @@ export class BIPUsersDAO {
return null
} else {
const sqlString = `
SELECT ${cols.ERP_URL}, ${cols.ERP_USERNAME}, ${cols.ERP_PASSWORD}
SELECT ${cols.ERP_USERNAME}, ${cols.ERP_PASSWORD}
FROM ${tableName}
WHERE UserName = ?
`
@@ -531,7 +531,6 @@ export class BIPUsersDAO {
if (result.rows.length > 0) {
const row = result.rows[0]
return {
url: (row[cols.ERP_URL] as string) || '',
username: (row[cols.ERP_USERNAME] as string) || '',
password: (row[cols.ERP_PASSWORD] as string) || ''
}
@@ -539,22 +538,20 @@ export class BIPUsersDAO {
return null
}
} catch (error) {
console.error('[BIPUsersDAO] Get user ERP config error:', error)
console.error('[BIPUsersDAO] Get user ERP credentials error:', error)
return null
}
}
/**
* Update ERP configuration for a user
* @param username - The username to update ERP config for
* @param erpUrl - The ERP URL
* Update ERP credentials for a user (username and password only, URL is from config.yaml)
* @param username - The username to update ERP credentials for
* @param erpUsername - The ERP username
* @param erpPassword - The ERP password
* @returns True if successful
*/
async updateUserErpConfig(
async updateUserErpCredentials(
username: string,
erpUrl: string,
erpUsername: string,
erpPassword: string
): Promise<boolean> {
@@ -566,15 +563,13 @@ export class BIPUsersDAO {
if (this.dbType === 'sqlserver') {
const sqlString = `
UPDATE ${tableName}
SET ${cols.ERP_URL} = @erpUrl,
${cols.ERP_USERNAME} = @erpUsername,
SET ${cols.ERP_USERNAME} = @erpUsername,
${cols.ERP_PASSWORD} = @erpPassword
WHERE UserName = @username
`
await (dbService as SqlServerService).queryWithParams(sqlString, {
username: { value: username, type: sql.NVarChar(255) },
erpUrl: { value: erpUrl, type: sql.NVarChar(500) },
erpUsername: { value: erpUsername, type: sql.NVarChar(255) },
erpPassword: { value: erpPassword, type: sql.NVarChar(255) }
})
@@ -582,22 +577,16 @@ export class BIPUsersDAO {
} else {
const sqlString = `
UPDATE ${tableName}
SET ${cols.ERP_URL} = ?,
${cols.ERP_USERNAME} = ?,
SET ${cols.ERP_USERNAME} = ?,
${cols.ERP_PASSWORD} = ?
WHERE UserName = ?
`
await (dbService as MySqlService).query(sqlString, [
erpUrl,
erpUsername,
erpPassword,
username
])
await (dbService as MySqlService).query(sqlString, [erpUsername, erpPassword, username])
return true
}
} catch (error) {
console.error('[BIPUsersDAO] Update user ERP config error:', error)
console.error('[BIPUsersDAO] Update user ERP credentials error:', error)
return false
}
}

View File

@@ -2,8 +2,10 @@
* Migration Script: Add ERP parameters to BIPUsers table
*
* This script adds ERP_URL, ERP_Username, and ERP_Password columns
* to the dbo_BIPUsers table and initializes all existing users
* with the same ERP credentials from the current .env configuration.
* to the dbo_BIPUsers table and initializes all existing users.
*
* Note: ERP credentials are now stored per-user in the database.
* This migration is for backward compatibility only.
*
* Usage:
* npx tsx src/main/services/user/migration/add-erp-params-migration.ts
@@ -16,6 +18,7 @@ import { dirname } from 'path'
import { ConfigManager } from '../../config/config-manager'
import { MySqlService } from '../../database/mysql'
import { SqlServerService } from '../../database/sql-server'
import yaml from 'js-yaml'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
@@ -28,8 +31,7 @@ const MIGRATION_CONFIG = {
tableName: {
mysql: 'dbo_BIPUsers',
sqlserver: '[dbo].[BIPUsers]'
},
columns: ['ERP_URL', 'ERP_Username', 'ERP_Password']
}
}
/**
@@ -40,15 +42,12 @@ async function checkColumnExistsMySQL(
tableName: string,
columnName: string
): Promise<boolean> {
const sql = `
SELECT COUNT(*) as count
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?
`
const result = await mysqlService.query(sql, [tableName, columnName])
return result.rows.length > 0 && (result.rows[0].count as number) > 0
const result = await mysqlService.query(
`SELECT COUNT(*) as count FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
[tableName, columnName]
)
return (result.rows[0]?.count as number) > 0
}
/**
@@ -59,16 +58,12 @@ async function checkColumnExistsSqlServer(
tableName: string,
columnName: string
): Promise<boolean> {
const sql = `
SELECT COUNT(*) as count
FROM sys.columns
WHERE object_id = OBJECT_ID(${tableName})
AND name = @columnName
`
const result = await sqlServerService.queryWithParams(sql, {
columnName: { value: columnName.replace('ERP_', ''), type: require('mssql').NVarChar(128) }
})
return result.rows.length > 0 && (result.rows[0].count as number) > 0
const result = await sqlServerService.query(
`SELECT COUNT(*) as count FROM sys.columns
WHERE OBJECT_ID = OBJECT_ID(?) AND name = ?`,
[tableName, columnName]
)
return (result.rows[0]?.count as number) > 0
}
/**
@@ -80,9 +75,8 @@ async function addColumnMySQL(
columnName: string,
columnType: string
): Promise<void> {
const sql = `ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${columnType} NULL`
await mysqlService.query(sql)
console.log(` ✓ Added column ${columnName} to ${tableName}`)
await mysqlService.query(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${columnType}`)
console.log(` ✓ Added column ${columnName} (${columnType})`)
}
/**
@@ -94,49 +88,64 @@ async function addColumnSqlServer(
columnName: string,
columnType: string
): Promise<void> {
const sql = `ALTER TABLE ${tableName} ADD ${columnName} ${columnType} NULL`
await sqlServerService.query(sql)
console.log(` ✓ Added column ${columnName} to ${tableName}`)
await sqlServerService.query(`ALTER TABLE ${tableName} ADD ${columnName} ${columnType}`)
console.log(` ✓ Added column ${columnName} (${columnType})`)
}
/**
* Update all users with ERP credentials from .env
* Initialize ERP credentials for all users in MySQL
*/
async function initializeErpCredentialsMySQL(
mysqlService: MySqlService,
tableName: string,
erpUrl: string,
erpUsername: string,
erpPassword: string
): Promise<number> {
const sql = `
UPDATE ${MIGRATION_CONFIG.tableName.mysql}
SET ERP_URL = ?, ERP_Username = ?, ERP_Password = ?
WHERE ERP_URL IS NULL OR ERP_URL = ''
`
const result = await mysqlService.query(sql, [erpUrl, erpUsername, erpPassword])
return result.rowCount
): Promise<void> {
const result = await mysqlService.query(`SELECT COUNT(*) as count FROM ${tableName}`)
const userCount = result.rows[0]?.count as number
if (userCount === 0) {
console.log('No users found in BIPUsers table')
return
}
console.log(`Initializing ERP credentials for ${userCount} user(s)...`)
await mysqlService.query(
`UPDATE ${tableName} SET ERP_URL = ?, ERP_Username = ?, ERP_Password = ?`,
[erpUrl, erpUsername, erpPassword]
)
console.log('✓ ERP credentials initialized for all users')
}
/**
* Update all users with ERP credentials from .env (SQL Server)
* Initialize ERP credentials for all users in SQL Server
*/
async function initializeErpCredentialsSqlServer(
sqlServerService: SqlServerService,
tableName: string,
erpUrl: string,
erpUsername: string,
erpPassword: string
): Promise<number> {
const sql = `
UPDATE ${MIGRATION_CONFIG.tableName.sqlserver}
SET ERP_URL = @erpUrl, ERP_Username = @erpUsername, ERP_Password = @erpPassword
WHERE ERP_URL IS NULL OR ERP_URL = ''
`
const result = await sqlServerService.queryWithParams(sql, {
erpUrl: { value: erpUrl, type: require('mssql').NVarChar(500) },
erpUsername: { value: erpUsername, type: require('mssql').NVarChar(255) },
erpPassword: { value: erpPassword, type: require('mssql').NVarChar(255) }
})
return result.rowCount
): Promise<void> {
const result = await sqlServerService.query(`SELECT COUNT(*) as count FROM ${tableName}`)
const userCount = result.rows[0]?.count as number
if (userCount === 0) {
console.log('No users found in BIPUsers table')
return
}
console.log(`Initializing ERP credentials for ${userCount} user(s)...`)
await sqlServerService.query(
`UPDATE ${tableName} SET ERP_URL = @p0, ERP_Username = @p1, ERP_Password = @p2`,
[erpUrl, erpUsername, erpPassword]
)
console.log('✓ ERP credentials initialized for all users')
}
/**
@@ -145,21 +154,17 @@ async function initializeErpCredentialsSqlServer(
async function runMySQLMigration(configManager: ConfigManager): Promise<void> {
console.log('\n📦 Running MySQL Migration...')
// Read database config from .env file with correct key names
const mysqlHost = configManager.get('DB_MYSQL_HOST', 'localhost')
const mysqlPort = configManager.getNumber('DB_MYSQL_PORT', 3306)
const mysqlUser = configManager.get('DB_USERNAME', 'root')
const mysqlPassword = configManager.get('DB_PASSWORD', '')
const mysqlDatabase = configManager.get('DB_NAME', '')
const config = configManager.getConfig()
const dbConfig = config.database.mysql
console.log(`Connecting to MySQL: ${mysqlHost}:${mysqlPort}/${mysqlDatabase}`)
console.log(`Connecting to MySQL: ${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`)
const mysqlService = new MySqlService({
host: mysqlHost,
port: mysqlPort,
user: mysqlUser,
password: mysqlPassword,
database: mysqlDatabase
host: dbConfig.host,
port: dbConfig.port,
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database
})
try {
@@ -182,29 +187,18 @@ async function runMySQLMigration(configManager: ConfigManager): Promise<void> {
}
}
// Initialize ERP credentials from .env
const erpUrl = configManager.get('ERP_URL', '')
const erpUsername = configManager.get('ERP_USERNAME', '')
const erpPassword = configManager.get('ERP_PASSWORD', '')
// Note: ERP credentials are now managed per-user via settings UI
// This migration no longer initializes them from config
console.log('\n✓ MySQL Migration completed')
console.log(' Note: ERP credentials should be configured per-user via the Settings UI')
if (erpUrl && erpUsername && erpPassword) {
const updatedCount = await initializeErpCredentialsMySQL(
mysqlService,
erpUrl,
erpUsername,
erpPassword
)
console.log(` ✓ Updated ${updatedCount} users with ERP credentials`)
} else {
console.log(' ⚠ Skipping ERP credential initialization (missing .env values)')
}
console.log('✅ MySQL Migration completed successfully!\n')
} catch (error) {
console.error('❌ MySQL Migration failed:', error)
throw error
} finally {
await mysqlService.disconnect()
} catch (error) {
console.error('✗ MySQL Migration failed:', error instanceof Error ? error.message : error)
if (mysqlService.isConnected()) {
await mysqlService.disconnect()
}
throw error
}
}
@@ -214,16 +208,19 @@ async function runMySQLMigration(configManager: ConfigManager): Promise<void> {
async function runSqlServerMigration(configManager: ConfigManager): Promise<void> {
console.log('\n📦 Running SQL Server Migration...')
const mssql = await import('mssql')
const config = configManager.getConfig()
const dbConfig = config.database.sqlserver
console.log(`Connecting to SQL Server: ${dbConfig.server}:${dbConfig.port}/${dbConfig.database}`)
const sqlServerService = new SqlServerService({
server: configManager.get('DB_SERVER', 'localhost'),
port: configManager.getNumber('DB_SQLSERVER_PORT', 1433),
user: configManager.get('DB_USERNAME', 'sa'),
password: configManager.get('DB_PASSWORD', ''),
database: configManager.get('DB_NAME', ''),
server: dbConfig.server,
port: dbConfig.port,
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database,
options: {
encrypt: false,
trustServerCertificate: configManager.get('DB_TRUST_SERVER_CERTIFICATE') === 'yes'
trustServerCertificate: dbConfig.trustServerCertificate
}
})
@@ -247,70 +244,46 @@ async function runSqlServerMigration(configManager: ConfigManager): Promise<void
}
}
// Initialize ERP credentials from .env
const erpUrl = configManager.get('ERP_URL', '')
const erpUsername = configManager.get('ERP_USERNAME', '')
const erpPassword = configManager.get('ERP_PASSWORD', '')
// Note: ERP credentials are now managed per-user via settings UI
console.log('\n✓ SQL Server Migration completed')
console.log(' Note: ERP credentials should be configured per-user via the Settings UI')
if (erpUrl && erpUsername && erpPassword) {
const updatedCount = await initializeErpCredentialsSqlServer(
sqlServerService,
erpUrl,
erpUsername,
erpPassword
)
console.log(` ✓ Updated ${updatedCount} users with ERP credentials`)
} else {
console.log(' ⚠ Skipping ERP credential initialization (missing .env values)')
}
console.log('✅ SQL Server Migration completed successfully!\n')
} catch (error) {
console.error('❌ SQL Server Migration failed:', error)
throw error
} finally {
await sqlServerService.disconnect()
} catch (error) {
console.error('✗ SQL Server Migration failed:', error instanceof Error ? error.message : error)
if (sqlServerService.isConnected()) {
await sqlServerService.disconnect()
}
throw error
}
}
/**
* Main migration runner
* Main function
*/
async function runMigration(): Promise<void> {
console.log('==============================================')
console.log('BIPUsers Table Migration: Add ERP Parameters')
console.log('==============================================\n')
const configManager = ConfigManager.getInstance()
await configManager.initialize()
const dbType = configManager.get('DB_TYPE', 'mysql').toLowerCase()
const isSqlServer = dbType === 'sqlserver' || dbType === 'mssql'
async function main(): Promise<void> {
console.log('╔═══════════════════════════════════════════════════════════╗')
console.log(' Migration: Add ERP Parameters to BIPUsers Table ║')
console.log('╚═══════════════════════════════════════════════════════════╝')
try {
if (isSqlServer) {
await runSqlServerMigration(configManager)
} else {
const configManager = ConfigManager.getInstance()
await configManager.initialize()
const dbType = configManager.getDatabaseType()
console.log(`\nCurrent database type: ${dbType}`)
if (dbType === 'mysql') {
await runMySQLMigration(configManager)
} else {
await runSqlServerMigration(configManager)
}
console.log('==============================================')
console.log('Migration Summary:')
console.log('==============================================')
console.log(`Database Type: ${isSqlServer ? 'SQL Server' : 'MySQL'}`)
console.log('Columns Added/Verified:')
console.log(' - ERP_URL (VARCHAR/NVARCHAR 500)')
console.log(' - ERP_Username (VARCHAR/NVARCHAR 255)')
console.log(' - ERP_Password (VARCHAR/NVARCHAR 255)')
console.log('==============================================\n')
console.log('\n✅ Migration completed successfully!\n')
} catch (error) {
console.error('\n❌ Migration failed with error:', error)
console.error('\n❌ Migration failed:', error instanceof Error ? error.message : error)
process.exit(1)
}
}
// Run migration
runMigration().catch((error) => {
console.error('Unexpected error:', error)
process.exit(1)
})
main()

View File

@@ -1,13 +1,14 @@
/**
* User ERP Configuration Service
*
* Manages ERP configuration (URL, username, password) stored in the BIPUsers table.
* Manages ERP credentials (username, password) stored in the BIPUsers table.
* Each user can have their own ERP credentials.
* ERP URL is fixed and stored in config.yaml.
*
* Features:
* - Get current user's ERP config
* - Update current user's ERP config
* - Get ERP config for any user (admin only)
* - Get current user's ERP credentials
* - Update current user's ERP credentials
* - Get ERP credentials for any user (admin only)
*/
import { BIPUsersDAO } from './bip-users-dao'
@@ -17,10 +18,9 @@ import { createLogger } from '../logger'
const log = createLogger('UserErpConfigService')
/**
* ERP Configuration object
* ERP Credentials object (username and password only)
*/
export interface ErpConfig {
url: string
export interface ErpCredentials {
username: string
password: string
}
@@ -48,9 +48,9 @@ export class UserErpConfigService {
/**
* Get ERP configuration for the current authenticated user
* @returns ERP configuration or null if not found
* @returns ERP credentials or null if not found
*/
async getCurrentUserErpConfig(): Promise<ErpConfig | null> {
async getCurrentUserErpConfig(): Promise<ErpCredentials | null> {
try {
const sessionManager = SessionManager.getInstance()
const currentUser = sessionManager.getUserInfo()
@@ -60,56 +60,55 @@ export class UserErpConfigService {
return null
}
log.info('Fetching ERP config for user', { username: currentUser.username })
const config = await this.dao.getUserErpConfig(currentUser.username)
log.info('Fetching ERP credentials for user', { username: currentUser.username })
const config = await this.dao.getUserErpCredentials(currentUser.username)
if (!config) {
log.warn('No ERP config found for user', { username: currentUser.username })
log.warn('No ERP credentials found for user', { username: currentUser.username })
return null
}
log.info('ERP config retrieved successfully', {
log.info('ERP credentials retrieved successfully', {
username: currentUser.username,
hasUrl: !!config.url,
hasUsername: !!config.username,
hasPassword: !!config.password
})
return config
} catch (error) {
log.error('Error getting current user ERP config', { error })
log.error('Error getting current user ERP credentials', { error })
return null
}
}
/**
* Get ERP configuration for a specific user (admin only)
* @param username - The username to get ERP config for
* @returns ERP configuration or null if not found
* Get ERP credentials for a specific user (admin only)
* @param username - The username to get ERP credentials for
* @returns ERP credentials or null if not found
*/
async getUserErpConfig(username: string): Promise<ErpConfig | null> {
async getUserErpConfig(username: string): Promise<ErpCredentials | null> {
try {
log.info('Fetching ERP config for user', { username })
const config = await this.dao.getUserErpConfig(username)
log.info('Fetching ERP credentials for user', { username })
const config = await this.dao.getUserErpCredentials(username)
if (!config) {
log.warn('No ERP config found for user', { username })
log.warn('No ERP credentials found for user', { username })
return null
}
return config
} catch (error) {
log.error('Error getting user ERP config', { error })
log.error('Error getting user ERP credentials', { error })
return null
}
}
/**
* Update ERP configuration for the current authenticated user
* @param config - ERP configuration to save
* Update ERP credentials for the current authenticated user
* @param credentials - ERP credentials to save
* @returns True if successful
*/
async updateCurrentUserErpConfig(config: ErpConfig): Promise<boolean> {
async updateCurrentUserErpConfig(credentials: ErpCredentials): Promise<boolean> {
try {
const sessionManager = SessionManager.getInstance()
const currentUser = sessionManager.getUserInfo()
@@ -119,52 +118,50 @@ export class UserErpConfigService {
return false
}
log.info('Updating ERP config for user', { username: currentUser.username })
const success = await this.dao.updateUserErpConfig(
log.info('Updating ERP credentials for user', { username: currentUser.username })
const success = await this.dao.updateUserErpCredentials(
currentUser.username,
config.url,
config.username,
config.password
credentials.username,
credentials.password
)
if (success) {
log.info('ERP config updated successfully', { username: currentUser.username })
log.info('ERP credentials updated successfully', { username: currentUser.username })
} else {
log.error('Failed to update ERP config', { username: currentUser.username })
log.error('Failed to update ERP credentials', { username: currentUser.username })
}
return success
} catch (error) {
log.error('Error updating current user ERP config', { error })
log.error('Error updating current user ERP credentials', { error })
return false
}
}
/**
* Update ERP configuration for a specific user (admin only)
* @param username - The username to update ERP config for
* @param config - ERP configuration to save
* Update ERP credentials for a specific user (admin only)
* @param username - The username to update ERP credentials for
* @param credentials - ERP credentials to save
* @returns True if successful
*/
async updateUserErpConfig(username: string, config: ErpConfig): Promise<boolean> {
async updateUserErpConfig(username: string, credentials: ErpCredentials): Promise<boolean> {
try {
log.info('Updating ERP config for user', { username })
const success = await this.dao.updateUserErpConfig(
log.info('Updating ERP credentials for user', { username })
const success = await this.dao.updateUserErpCredentials(
username,
config.url,
config.username,
config.password
credentials.username,
credentials.password
)
if (success) {
log.info('ERP config updated successfully', { username })
log.info('ERP credentials updated successfully', { username })
} else {
log.error('Failed to update ERP config', { username })
log.error('Failed to update ERP credentials', { username })
}
return success
} catch (error) {
log.error('Error updating user ERP config', { error })
log.error('Error updating user ERP credentials', { error })
return false
}
}