From e3968347f64bb27faecc7bf7577b765577e381be Mon Sep 17 00:00:00 2001 From: lunaticbum Date: Tue, 17 Nov 2026 16:51:54 +0900 Subject: [PATCH] feat(ui): auto-scroll to latest decision on new items and enhance stream data management tools --- src/main/kotlin/ui/TradingDecisionLog.kt | 249 ++++++++++++++++---- src/main/kotlin/ui/store/TradingLogStore.kt | 36 ++- 2 files changed, 228 insertions(+), 57 deletions(-) diff --git a/src/main/kotlin/ui/TradingDecisionLog.kt b/src/main/kotlin/ui/TradingDecisionLog.kt index ee2d1d1..966b10f 100644 --- a/src/main/kotlin/ui/TradingDecisionLog.kt +++ b/src/main/kotlin/ui/TradingDecisionLog.kt @@ -13,6 +13,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowDownward +import androidx.compose.material.icons.filled.ArrowUpward import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.* @@ -25,6 +26,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.launch import model.KisSession import network.KisTradeService @@ -35,6 +37,8 @@ import ui.component.CsvDropZone import ui.component.FilterChipWithRightClick import ui.panel.TradeConfigPanel import ui.store.TradingLogStore +import java.awt.Toolkit +import java.awt.datatransfer.StringSelection import java.text.NumberFormat import java.time.LocalTime import java.time.ZoneId @@ -47,7 +51,13 @@ fun TradingDecisionLog() { val coroutineScope = rememberCoroutineScope() var searchQuery by remember { mutableStateOf("") } var selectedFilters by remember { mutableStateOf(setOf("전체")) } - val filterOptions = listOf("전체", "BUY", "SELL", "SETTING", "ANALYZER", "WATCH", "AFTER", "NOTICE") + val filterOptions = listOf("전체", "BUY", "SELL", "WATCH", "ANALYZER", "HOLD", "NOTICE", "SETTING", "AFTER") + + // 데이터 관리 및 스트림 제어 상태 + var autoScrollEnabled by remember { mutableStateOf(true) } + var isNewestOnTop by remember { mutableStateOf(true) } + var showClearDialog by remember { mutableStateOf(false) } + var copyFeedback by remember { mutableStateOf(null) } var llmAnalyser by remember { mutableStateOf(AutoTradingManager.llmAnalyser) } LaunchedEffect(AutoTradingManager.llmAnalyser) { @@ -80,16 +90,41 @@ fun TradingDecisionLog() { val scrollState = rememberScrollState() // 원본 로그에서 필터 조건에 맞는 리스트 산출 - val filteredLogs = TradingLogStore.decisionLogs.filter { log -> - val matchesType = if (selectedFilters.contains("전체")) { - true - } else { - selectedFilters.contains(log.decision) + val filteredLogs = remember(TradingLogStore.decisionLogs.size, selectedFilters, searchQuery) { + TradingLogStore.decisionLogs.filter { log -> + val matchesType = if (selectedFilters.contains("전체")) { + true + } else { + selectedFilters.contains(log.decision) + } + val matchesQuery = searchQuery.isBlank() || + log.stockName.contains(searchQuery, ignoreCase = true) || + (log.stockCode?.contains(searchQuery, ignoreCase = true) ?: false) || + log.reason.contains(searchQuery, ignoreCase = true) || + log.decision.contains(searchQuery, ignoreCase = true) + matchesType && matchesQuery + } + } + + // 화면 표시용 정렬 (최신 상단 vs 최신 하단) + val displayLogs = remember(filteredLogs, isNewestOnTop) { + if (isNewestOnTop) filteredLogs.reversed() else filteredLogs + } + + // 새 데이터 추가 시 자동으로 최신 위치로 스크롤 포커스 이동 + LaunchedEffect(displayLogs.size) { + if (autoScrollEnabled && displayLogs.isNotEmpty()) { + val targetIndex = if (isNewestOnTop) 0 else displayLogs.size - 1 + listState.animateScrollToItem(targetIndex) + } + } + + // 카테고리별 실시간 건수 계산 + val filterCounts = remember(TradingLogStore.decisionLogs.size) { + filterOptions.associateWith { opt -> + if (opt == "전체") TradingLogStore.decisionLogs.size + else TradingLogStore.decisionLogs.count { it.decision == opt } } - val matchesQuery = searchQuery.isBlank() || - log.stockName.contains(searchQuery, ignoreCase = true) || - log.reason.contains(searchQuery, ignoreCase = true) - matchesType && matchesQuery } Column( @@ -134,7 +169,7 @@ fun TradingDecisionLog() { .fillMaxSize() .padding(12.dp) ) { - // 좌측 패널 헤더 + // 좌측 패널 상단 헤더: 타이틀 & 건수 & 제어 툴바 Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, @@ -165,46 +200,126 @@ fun TradingDecisionLog() { } } - // 최신 로그 바로가기 버튼 - OutlinedButton( - onClick = { - coroutineScope.launch { - if (filteredLogs.isNotEmpty()) { - listState.animateScrollToItem(filteredLogs.size - 1) - } - } - }, - contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), - modifier = Modifier.height(28.dp), - shape = RoundedCornerShape(6.dp), - border = BorderStroke(1.dp, Color(0xFFCBD5E1)) + // 스트림 컨트롤 액션 버튼 그룹 + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) ) { - Icon( - Icons.Default.ArrowDownward, - contentDescription = "Scroll to Bottom", - modifier = Modifier.size(13.dp), - tint = Color(0xFF64748B) - ) - Spacer(Modifier.width(3.dp)) - Text("최신순", fontSize = 11.sp, color = Color(0xFF64748B)) + // 1. 자동 포커스 (Auto Scroll) 토글 버튼 + OutlinedButton( + onClick = { autoScrollEnabled = !autoScrollEnabled }, + contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp), + modifier = Modifier.height(26.dp), + shape = RoundedCornerShape(6.dp), + border = BorderStroke( + 1.dp, + if (autoScrollEnabled) Color(0xFF10B981) else Color(0xFFCBD5E1) + ), + colors = ButtonDefaults.outlinedButtonColors( + backgroundColor = if (autoScrollEnabled) Color(0xFFECFDF5) else Color.White + ) + ) { + Text( + if (autoScrollEnabled) "⚡ 자동포커스 ON" else "⏸️ 자동포커스 OFF", + fontSize = 10.sp, + fontWeight = FontWeight.Bold, + color = if (autoScrollEnabled) Color(0xFF059669) else Color(0xFF64748B) + ) + } + + // 2. 최신 로그 즉시 포커스 이동 버튼 + OutlinedButton( + onClick = { + coroutineScope.launch { + if (displayLogs.isNotEmpty()) { + val target = if (isNewestOnTop) 0 else displayLogs.size - 1 + listState.animateScrollToItem(target) + } + } + }, + contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp), + modifier = Modifier.height(26.dp), + shape = RoundedCornerShape(6.dp), + border = BorderStroke(1.dp, Color(0xFFCBD5E1)) + ) { + Icon( + if (isNewestOnTop) Icons.Default.ArrowUpward else Icons.Default.ArrowDownward, + contentDescription = "Scroll to Latest", + modifier = Modifier.size(12.dp), + tint = Color(0xFF4F46E5) + ) + Spacer(Modifier.width(2.dp)) + Text("최신위치", fontSize = 10.sp, color = Color(0xFF4F46E5), fontWeight = FontWeight.Bold) + } + + // 3. 정렬 순서 전환 버튼 (최신 상단 ⬆️ vs 최신 하단 ⬇️) + OutlinedButton( + onClick = { isNewestOnTop = !isNewestOnTop }, + contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp), + modifier = Modifier.height(26.dp), + shape = RoundedCornerShape(6.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Text( + if (isNewestOnTop) "⬆️ 최신위" else "⬇️ 최신아래", + fontSize = 10.sp, + color = Color(0xFF475569) + ) + } + + // 4. 복사 버튼 + OutlinedButton( + onClick = { + try { + val text = TradingLogStore.exportLogsAsText(displayLogs) + val selection = StringSelection(text) + Toolkit.getDefaultToolkit().systemClipboard.setContents(selection, selection) + copyFeedback = "복사 완료 (${displayLogs.size}건)" + coroutineScope.launch { + delay(2000) + copyFeedback = null + } + } catch (e: Exception) { + copyFeedback = "복사 실패" + } + }, + contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp), + modifier = Modifier.height(26.dp), + shape = RoundedCornerShape(6.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Text(copyFeedback ?: "📋 복사", fontSize = 10.sp, color = Color(0xFF475569)) + } + + // 5. 전체 비우기 버튼 + OutlinedButton( + onClick = { showClearDialog = true }, + contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp), + modifier = Modifier.height(26.dp), + shape = RoundedCornerShape(6.dp), + border = BorderStroke(1.dp, Color(0xFFFCA5A5)), + colors = ButtonDefaults.outlinedButtonColors(backgroundColor = Color(0xFFFEF2F2)) + ) { + Text("🗑️ 비우기", fontSize = 10.sp, color = Color(0xFFDC2626), fontWeight = FontWeight.Bold) + } } } - Spacer(modifier = Modifier.height(8.dp)) + Spacer(modifier = Modifier.height(6.dp)) // 검색창 OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it }, - placeholder = { Text("종목명 또는 사유 검색...", fontSize = 12.sp, color = Color(0xFF94A3B8)) }, + placeholder = { Text("종목명, 코드, 결정유형 또는 사유 검색...", fontSize = 12.sp, color = Color(0xFF94A3B8)) }, modifier = Modifier .fillMaxWidth() - .height(48.dp), + .height(44.dp), leadingIcon = { Icon( Icons.Default.Search, contentDescription = null, - modifier = Modifier.size(18.dp), + modifier = Modifier.size(16.dp), tint = Color(0xFF94A3B8) ) }, @@ -212,12 +327,12 @@ fun TradingDecisionLog() { if (searchQuery.isNotEmpty()) { IconButton( onClick = { searchQuery = "" }, - modifier = Modifier.size(24.dp) + modifier = Modifier.size(22.dp) ) { Icon( Icons.Default.Close, contentDescription = "Clear", - modifier = Modifier.size(16.dp), + modifier = Modifier.size(14.dp), tint = Color(0xFF94A3B8) ) } @@ -234,7 +349,7 @@ fun TradingDecisionLog() { Spacer(modifier = Modifier.height(6.dp)) - // 필터 칩 영역 (가로 스크롤) + // 필터 칩 영역 (가로 스크롤 및 실시간 건수 뱃지) Row( modifier = Modifier .fillMaxWidth() @@ -244,8 +359,11 @@ fun TradingDecisionLog() { ) { filterOptions.forEach { option -> val isSelected = selectedFilters.contains(option) + val count = filterCounts[option] ?: 0 + val labelWithCount = if (count > 0) "$option ($count)" else option + FilterChipWithRightClick( - label = option, + label = labelWithCount, isSelected = isSelected, onClick = { val newFilters = selectedFilters.toMutableSet() @@ -289,27 +407,37 @@ fun TradingDecisionLog() { Spacer(modifier = Modifier.height(4.dp)) // 로그 리스트 스트림 - if (filteredLogs.isEmpty()) { + if (displayLogs.isEmpty()) { Box( modifier = Modifier .fillMaxWidth() .weight(1f), contentAlignment = Alignment.Center ) { - Text( - "수신된 의사결정 로그가 없습니다.", - fontSize = 12.sp, - color = Color(0xFF94A3B8) - ) + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text( + "수신된 의사결정 로그가 없습니다.", + fontSize = 12.sp, + color = Color(0xFF94A3B8) + ) + Text( + "자동 매매 및 실시간 분석이 진행되면 실시간으로 기록됩니다.", + fontSize = 11.sp, + color = Color(0xFFCBD5E1) + ) + } } } else { LazyColumn( state = listState, - reverseLayout = true, + reverseLayout = false, modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(6.dp) ) { - items(filteredLogs) { log -> + items(displayLogs) { log -> DecisionLogCard(log = log, onManualSell = { code, qty -> coroutineScope.launch { KisTradeService.postOrder( @@ -348,6 +476,31 @@ fun TradingDecisionLog() { ) } } + + // 전체 비우기 확인 다이얼로그 + if (showClearDialog) { + AlertDialog( + onDismissRequest = { showClearDialog = false }, + title = { Text("의사결정 스트림 비우기", fontWeight = FontWeight.Bold, fontSize = 14.sp) }, + text = { Text("현재 누적된 의사결정 로그(${TradingLogStore.decisionLogs.size}건)를 모두 삭제하시겠습니까?", fontSize = 12.sp) }, + confirmButton = { + Button( + onClick = { + TradingLogStore.clear() + showClearDialog = false + }, + colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFFEF4444)) + ) { + Text("삭제", color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.Bold) + } + }, + dismissButton = { + TextButton(onClick = { showClearDialog = false }) { + Text("취소", color = Color(0xFF64748B), fontSize = 12.sp) + } + } + ) + } } } diff --git a/src/main/kotlin/ui/store/TradingLogStore.kt b/src/main/kotlin/ui/store/TradingLogStore.kt index b092368..d8a32a4 100644 --- a/src/main/kotlin/ui/store/TradingLogStore.kt +++ b/src/main/kotlin/ui/store/TradingLogStore.kt @@ -12,6 +12,9 @@ import java.time.LocalTime import java.time.format.DateTimeFormatter object TradingLogStore { + // 로그 보관 최대 상한 (메모리 최적화 및 1,000건 안전 유지) + const val MAX_LOG_SIZE = 1000 + // UI에서 관찰할 수 있는 경량 로그 리스트 val decisionLogs = mutableStateListOf() @@ -25,9 +28,24 @@ object TradingLogStore { var qty: Int? = 0, ) + private fun trimLogs() { + while (decisionLogs.size > MAX_LOG_SIZE) { + decisionLogs.removeAt(0) + } + } + + /** + * 로그 목록을 텍스트 형식으로 내보냅니다. + */ + fun exportLogsAsText(logs: List = decisionLogs): String { + return logs.joinToString("\n") { log -> + "[${log.time}] [${log.decision}] ${log.stockName} (신뢰도: ${log.confidence.toInt()}%) - ${log.reason}" + } + } + fun addLog(decision: TradingDecision) { synchronized(this) { - if (decisionLogs.size > 100) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add(LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), stockName = "${decision.stockName}[${decision.currentPrice}]", @@ -48,7 +66,7 @@ object TradingLogStore { fun addSellLog(stockName: String, sellPrice: String, decision: String, log: String) { synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add( LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), @@ -71,7 +89,7 @@ object TradingLogStore { fun addLog(tradingDecision: TradingDecision, decision: String, log: String) { synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add( LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), @@ -94,7 +112,7 @@ object TradingLogStore { fun addWatchLog(tradingDecision: TradingDecision, decision: String, log: String) { synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add( LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), @@ -117,7 +135,7 @@ object TradingLogStore { fun addAnalyzer(name: String, code: String, log: String, positive: Boolean = false) { synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() if (positive) { decisionLogs.add( LogEntry( @@ -159,7 +177,7 @@ object TradingLogStore { } synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add( LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), @@ -183,7 +201,7 @@ object TradingLogStore { fun addNotice(name: String, code: String, log: String, qty: Int? = null) { synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add( LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), @@ -200,7 +218,7 @@ object TradingLogStore { fun addAfterMarketLog(name: String, code: String, log: String) { synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add( LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), @@ -215,7 +233,7 @@ object TradingLogStore { fun addSettingLog(settingDesc: String, old: String, new: String, log: String) { synchronized(this) { - if (decisionLogs.size > 1000) decisionLogs.removeAt(0) + trimLogs() decisionLogs.add( LogEntry( time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),