commit 8c0b02233eacaaec3db269fad8399d79f32b0af0 Author: kric_jspark Date: Fri Mar 20 08:52:16 2026 +0900 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12f7db7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,401 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# JetBrains IDE cahee +.idea/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml \ No newline at end of file diff --git a/Keps.WinForms/App.config b/Keps.WinForms/App.config new file mode 100644 index 0000000..774723a --- /dev/null +++ b/Keps.WinForms/App.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/Keps.WinForms/Docs/RealExtraction_Flow_3Steps.md b/Keps.WinForms/Docs/RealExtraction_Flow_3Steps.md new file mode 100644 index 0000000..e69de29 diff --git a/Keps.WinForms/Docs/VB_FinalExtraction_ActualFlow.md b/Keps.WinForms/Docs/VB_FinalExtraction_ActualFlow.md new file mode 100644 index 0000000..03ca26a --- /dev/null +++ b/Keps.WinForms/Docs/VB_FinalExtraction_ActualFlow.md @@ -0,0 +1,44 @@ +# VB 최종 추출 단계 실제 흐름 요약 + +## 1. 사전 단계 +- 선거, 지역, 총(군집) 수, 정렬 기준, 정렬 방향 선택 +- `poll_data`에서 `비고 = 1`인 투표구만 모집단으로 사용 +- `군집별비율`에서 군집별 비율 조회 +- 군집별 투표구 수 조회 +- 자동/수동 추출 개수 입력 영역 준비 +- 층별 추출 ID / 조정 ID 입력 영역 준비 + +## 2. 자동 배분 +- 총 추출 투표구 수 × 군집 비율 계산 +- 정수부 우선 배분 +- 남는 수량은 소수점 큰 군집부터 1개씩 추가 + +## 3. 추출 위치 +- 기본 / 추출위치 빼기 / 추출위치 더하기 +- 군집별 허용 가감 범위를 계산해 UI에 표시 +- 현재 C# 화면에서도 이 구조를 반영 + +## 4. 최종 추출 +- 선택 후보 득표율 또는 투표인수 기준 정렬 +- 오름차순 / 내림차순 적용 +- 군집별 간격 = `Int(총투표구수 / 추출개수)` +- 시작 위치 계산 후 가감값 적용 +- 등간 방식으로 추출 ID 선택 + +## 5. 검증 및 결과 +- 추출 결과와 실제 결과를 군집별/전체로 비교 +- 최종 투표소 현황, 자가 검증 요약, 기준설정 Mode 등을 시트로 저장 + +## 이번 수정에서 반영한 범위 +- WinForms UI를 VB 화면 구조에 가깝게 재배치 +- 사전 단계 / 최종 추출 버튼 분리 +- 좌측: 자동/수동 추출 옵션 + 추출위치 +- 중앙: 수동 조정 ID 표 +- 우측: 자가 검증 요약 표 +- 하단: 최종 투표소 추출현황 표 +- 샘플 강원 출력 파일 구조를 참고해 xlsx 보고서 생성 서비스 추가 + +## 남은 확인 항목 +- 실제 VB의 시작 위치 계산식 1:1 재현 여부 +- 조정 ID를 반영한 재추출 처리 +- 반복 추출(시작/종료/간격) 실제 실행 로직 diff --git a/Keps.WinForms/Forms/DataInputForm.Designer.cs b/Keps.WinForms/Forms/DataInputForm.Designer.cs new file mode 100644 index 0000000..dda32e8 --- /dev/null +++ b/Keps.WinForms/Forms/DataInputForm.Designer.cs @@ -0,0 +1,193 @@ +namespace Keps.WinForms.Forms +{ + partial class DataInputForm + { + private System.ComponentModel.IContainer components = null; + private System.Windows.Forms.TableLayoutPanel _layout; + private System.Windows.Forms.FlowLayoutPanel _buttonPanel; + private System.Windows.Forms.Label _lblElection; + private System.Windows.Forms.Label _lblFolder; + private System.Windows.Forms.ComboBox _cmbElection; + private System.Windows.Forms.TextBox _txtFolder; + private System.Windows.Forms.Button _btnFolder; + private System.Windows.Forms.Button _btnImportReal; + private System.Windows.Forms.ProgressBar _progress; + private System.Windows.Forms.Label _lblMain; + private System.Windows.Forms.Label _lblDetail; + private System.Windows.Forms.FolderBrowserDialog _folderDialog; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this._layout = new System.Windows.Forms.TableLayoutPanel(); + this._lblElection = new System.Windows.Forms.Label(); + this._cmbElection = new System.Windows.Forms.ComboBox(); + this._lblFolder = new System.Windows.Forms.Label(); + this._txtFolder = new System.Windows.Forms.TextBox(); + this._btnFolder = new System.Windows.Forms.Button(); + this._progress = new System.Windows.Forms.ProgressBar(); + this._lblMain = new System.Windows.Forms.Label(); + this._lblDetail = new System.Windows.Forms.Label(); + this._buttonPanel = new System.Windows.Forms.FlowLayoutPanel(); + this._btnImportReal = new System.Windows.Forms.Button(); + this._folderDialog = new System.Windows.Forms.FolderBrowserDialog(); + this._layout.SuspendLayout(); + this._buttonPanel.SuspendLayout(); + this.SuspendLayout(); + // + // _layout + // + this._layout.ColumnCount = 3; + this._layout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 120F)); + this._layout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this._layout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 180F)); + this._layout.Controls.Add(this._lblElection, 0, 0); + this._layout.Controls.Add(this._cmbElection, 1, 0); + this._layout.Controls.Add(this._lblFolder, 0, 1); + this._layout.Controls.Add(this._txtFolder, 1, 1); + this._layout.Controls.Add(this._btnFolder, 2, 1); + this._layout.Controls.Add(this._progress, 0, 2); + this._layout.Controls.Add(this._lblMain, 0, 3); + this._layout.Controls.Add(this._lblDetail, 0, 4); + this._layout.Dock = System.Windows.Forms.DockStyle.Top; + this._layout.Location = new System.Drawing.Point(0, 0); + this._layout.Name = "_layout"; + this._layout.Padding = new System.Windows.Forms.Padding(12); + this._layout.RowCount = 5; + this._layout.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this._layout.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this._layout.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this._layout.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this._layout.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this._layout.Size = new System.Drawing.Size(1000, 161); + this._layout.TabIndex = 0; + // + // _lblElection + // + this._lblElection.Anchor = System.Windows.Forms.AnchorStyles.Left; + this._lblElection.AutoSize = true; + this._lblElection.Location = new System.Drawing.Point(15, 19); + this._lblElection.Name = "_lblElection"; + this._lblElection.Size = new System.Drawing.Size(53, 12); + this._lblElection.TabIndex = 0; + this._lblElection.Text = "선거년월"; + // + // _cmbElection + // + this._cmbElection.Dock = System.Windows.Forms.DockStyle.Fill; + this._cmbElection.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this._cmbElection.FormattingEnabled = true; + this._cmbElection.Location = new System.Drawing.Point(135, 15); + this._cmbElection.Name = "_cmbElection"; + this._cmbElection.Size = new System.Drawing.Size(670, 20); + this._cmbElection.TabIndex = 1; + // + // _lblFolder + // + this._lblFolder.Anchor = System.Windows.Forms.AnchorStyles.Left; + this._lblFolder.AutoSize = true; + this._lblFolder.Location = new System.Drawing.Point(15, 47); + this._lblFolder.Name = "_lblFolder"; + this._lblFolder.Size = new System.Drawing.Size(57, 12); + this._lblFolder.TabIndex = 2; + this._lblFolder.Text = "엑셀 폴더"; + // + // _txtFolder + // + this._txtFolder.Dock = System.Windows.Forms.DockStyle.Fill; + this._txtFolder.Location = new System.Drawing.Point(135, 41); + this._txtFolder.Name = "_txtFolder"; + this._txtFolder.ReadOnly = true; + this._txtFolder.Size = new System.Drawing.Size(670, 21); + this._txtFolder.TabIndex = 3; + // + // _btnFolder + // + this._btnFolder.Anchor = System.Windows.Forms.AnchorStyles.Left; + this._btnFolder.Location = new System.Drawing.Point(811, 41); + this._btnFolder.Name = "_btnFolder"; + this._btnFolder.Size = new System.Drawing.Size(100, 25); + this._btnFolder.TabIndex = 4; + this._btnFolder.Text = "폴더 선택"; + this._btnFolder.UseVisualStyleBackColor = true; + this._btnFolder.Click += new System.EventHandler(this.BtnFolder_Click); + // + // _progress + // + this._layout.SetColumnSpan(this._progress, 3); + this._progress.Dock = System.Windows.Forms.DockStyle.Fill; + this._progress.Location = new System.Drawing.Point(15, 72); + this._progress.Name = "_progress"; + this._progress.Size = new System.Drawing.Size(970, 23); + this._progress.TabIndex = 5; + // + // _lblMain + // + this._lblMain.AutoSize = true; + this._layout.SetColumnSpan(this._lblMain, 3); + this._lblMain.Location = new System.Drawing.Point(15, 98); + this._lblMain.Name = "_lblMain"; + this._lblMain.Size = new System.Drawing.Size(29, 12); + this._lblMain.TabIndex = 6; + this._lblMain.Text = "대기"; + // + // _lblDetail + // + this._lblDetail.AutoSize = true; + this._layout.SetColumnSpan(this._lblDetail, 3); + this._lblDetail.Location = new System.Drawing.Point(15, 110); + this._lblDetail.Name = "_lblDetail"; + this._lblDetail.Size = new System.Drawing.Size(0, 12); + this._lblDetail.TabIndex = 7; + // + // _buttonPanel + // + this._buttonPanel.Controls.Add(this._btnImportReal); + this._buttonPanel.Dock = System.Windows.Forms.DockStyle.Top; + this._buttonPanel.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft; + this._buttonPanel.Location = new System.Drawing.Point(0, 161); + this._buttonPanel.Name = "_buttonPanel"; + this._buttonPanel.Padding = new System.Windows.Forms.Padding(12, 0, 12, 12); + this._buttonPanel.Size = new System.Drawing.Size(1000, 52); + this._buttonPanel.TabIndex = 1; + // + // _btnImportReal + // + this._btnImportReal.Location = new System.Drawing.Point(846, 3); + this._btnImportReal.Name = "_btnImportReal"; + this._btnImportReal.Size = new System.Drawing.Size(127, 25); + this._btnImportReal.TabIndex = 0; + this._btnImportReal.Text = "최종 추출용 입력"; + this._btnImportReal.UseVisualStyleBackColor = true; + this._btnImportReal.Click += new System.EventHandler(this.BtnImportReal_Click); + // + // DataInputForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1000, 320); + this.Controls.Add(this._buttonPanel); + this.Controls.Add(this._layout); + this.Name = "DataInputForm"; + this.Text = "엑셀 자료 입력"; + this.WindowState = System.Windows.Forms.FormWindowState.Maximized; + this.Load += new System.EventHandler(this.DataInputForm_Load); + this._layout.ResumeLayout(false); + this._layout.PerformLayout(); + this._buttonPanel.ResumeLayout(false); + this.ResumeLayout(false); + } + } +} diff --git a/Keps.WinForms/Forms/DataInputForm.cs b/Keps.WinForms/Forms/DataInputForm.cs new file mode 100644 index 0000000..2532957 --- /dev/null +++ b/Keps.WinForms/Forms/DataInputForm.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using System.Windows.Forms; +using Keps.WinForms.Models; +using Keps.WinForms.Services; + +namespace Keps.WinForms.Forms +{ + public sealed partial class DataInputForm : Form + { + private readonly string _appBasePath = Application.StartupPath; + private ExcelImportService _excelImportService; + + public DataInputForm() + { + InitializeComponent(); + } + + public DataInputForm(ExcelImportService excelImportService) + : this() + { + SetServices(excelImportService); + } + + public void SetServices(ExcelImportService excelImportService) + { + _excelImportService = excelImportService; + } + + private void DataInputForm_Load(object sender, EventArgs e) + { + + if (_excelImportService == null) + { + _lblMain.Text = "서비스 미연결"; + _lblDetail.Text = "MainMdiForm.InitializeRuntime 호출 후 사용하세요."; + return; + } + + + List elections = _excelImportService.LoadElectionYears(); + _cmbElection.Items.Clear(); + foreach (string election in elections) + { + _cmbElection.Items.Add(election); + } + + if (_cmbElection.Items.Count > 0) + { + _cmbElection.SelectedIndex = 0; + } + } + + private void BtnFolder_Click(object sender, EventArgs e) + { + // 초기 디렉터리는 _txtFolder의 값(폴더이거나 파일이면 그 폴더) 또는 _appBasePath + string initialDir = _appBasePath; + + if (!string.IsNullOrWhiteSpace(_txtFolder.Text)) + { + try + { + if (Directory.Exists(_txtFolder.Text)) + { + initialDir = _txtFolder.Text; + } + else + { + var dir = Path.GetDirectoryName(_txtFolder.Text); + if (!string.IsNullOrWhiteSpace(dir) && Directory.Exists(dir)) + initialDir = dir; + } + } + catch + { + initialDir = _appBasePath; + } + } + + // FolderBrowserDialog는 SelectedPath로 초기 경로를 설정 + _folderDialog.SelectedPath = initialDir; + + if (_folderDialog.ShowDialog(this) == DialogResult.OK) + { + _txtFolder.Text = _folderDialog.SelectedPath; + } + } + + private async void BtnImportReal_Click(object sender, EventArgs e) + { + if (_excelImportService == null) + { + MessageBox.Show(this, "ExcelImportService가 초기화되지 않았습니다.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + if (_cmbElection.SelectedItem == null) + { + MessageBox.Show(this, "선거년월을 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + if (string.IsNullOrWhiteSpace(_txtFolder.Text) || !Directory.Exists(_txtFolder.Text)) + { + MessageBox.Show(this, "엑셀 폴더를 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + string folderPath = _txtFolder.Text; + string electionName = _cmbElection.SelectedItem.ToString(); + + ToggleState(false); + _progress.Value = 0; + _lblMain.Text = "엑셀자료 입력 시작 - 최종 투표구 추출용"; + + Progress progress = new Progress(p => + { + _progress.Value = Math.Max(0, Math.Min(100, p.Percent)); + _lblDetail.Text = p.Message; + }); + + try + { + await Task.Run(() => + { + _excelImportService.Import(folderPath, electionName, ImportMode.Real, progress); + }); + + _lblMain.Text = "완료"; + MessageBox.Show(this, "엑셀 기초자료 DB 적재와 군집 재구성이 완료되었습니다.", "완료", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _lblMain.Text = "실패"; + MessageBox.Show(this, ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + finally + { + ToggleState(true); + } + } + + private void ToggleState(bool enabled) + { + _cmbElection.Enabled = enabled; + _btnFolder.Enabled = enabled; + _btnImportReal.Enabled = enabled; + } + } +} diff --git a/Keps.WinForms/Forms/DataInputForm.resx b/Keps.WinForms/Forms/DataInputForm.resx new file mode 100644 index 0000000..9389daa --- /dev/null +++ b/Keps.WinForms/Forms/DataInputForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/Keps.WinForms/Forms/MainMdiForm.Designer.cs b/Keps.WinForms/Forms/MainMdiForm.Designer.cs new file mode 100644 index 0000000..92ff694 --- /dev/null +++ b/Keps.WinForms/Forms/MainMdiForm.Designer.cs @@ -0,0 +1,68 @@ +namespace Keps.WinForms.Forms +{ + partial class MainMdiForm + { + private System.ComponentModel.IContainer components = null; + private System.Windows.Forms.MenuStrip _menu; + private System.Windows.Forms.ToolStripMenuItem _mnuData; + private System.Windows.Forms.ToolStripMenuItem _mnuReal; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this._menu = new System.Windows.Forms.MenuStrip(); + this._mnuData = new System.Windows.Forms.ToolStripMenuItem(); + this._mnuReal = new System.Windows.Forms.ToolStripMenuItem(); + this._menu.SuspendLayout(); + this.SuspendLayout(); + // + // _menu + // + this._menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this._mnuData, + this._mnuReal}); + this._menu.Location = new System.Drawing.Point(0, 0); + this._menu.Name = "_menu"; + this._menu.Size = new System.Drawing.Size(1400, 24); + this._menu.TabIndex = 0; + this._menu.Text = "menuStrip1"; + // + // _mnuData + // + this._mnuData.Name = "_mnuData"; + this._mnuData.Size = new System.Drawing.Size(91, 20); + this._mnuData.Text = "기초자료입력"; + // + // _mnuReal + // + this._mnuReal.Name = "_mnuReal"; + this._mnuReal.Size = new System.Drawing.Size(111, 20); + this._mnuReal.Text = "최종 투표구 추출"; + // + // MainMdiForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1400, 900); + this.Controls.Add(this._menu); + this.IsMdiContainer = true; + this.MainMenuStrip = this._menu; + this.Name = "MainMdiForm"; + this.Text = "KEPS (C# WinForms Migration)"; + this.WindowState = System.Windows.Forms.FormWindowState.Maximized; + this._menu.ResumeLayout(false); + this._menu.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + } +} diff --git a/Keps.WinForms/Forms/MainMdiForm.cs b/Keps.WinForms/Forms/MainMdiForm.cs new file mode 100644 index 0000000..1a9f22b --- /dev/null +++ b/Keps.WinForms/Forms/MainMdiForm.cs @@ -0,0 +1,104 @@ +using System; +using System.Windows.Forms; +using Keps.WinForms.Infrastructure; +using Keps.WinForms.Services; + +namespace Keps.WinForms.Forms +{ + public sealed partial class MainMdiForm : Form + { + private SqlConnectionFactory _connectionFactory; + private AppVersionService _versionService; + private ExcelImportService _excelImportService; + + private DataInputForm _dataForm; + private RealExtractionForm _realForm; + + public MainMdiForm() + { + InitializeComponent(); + WireEvents(); + } + + public MainMdiForm(SqlConnectionFactory connectionFactory) + : this() + { + InitializeRuntime(connectionFactory); + } + + public void InitializeRuntime(SqlConnectionFactory connectionFactory) + { + _connectionFactory = connectionFactory; + _versionService = connectionFactory == null ? null : new AppVersionService(connectionFactory); + _excelImportService = connectionFactory == null ? null : new ExcelImportService(connectionFactory); + } + + private void WireEvents() + { + Load += MainMdiForm_Load; + _mnuData.Click += delegate { ShowDataInput(); }; + _mnuReal.Click += delegate { ShowReal(); }; + } + + private void MainMdiForm_Load(object sender, EventArgs e) + { + if (DesignTimeHelper.IsDesignMode(this) || _versionService == null) + { + return; + } + + try + { + string version = _versionService.GetCurrentVersion(); + if (!string.IsNullOrWhiteSpace(version)) + { + Text += " - DB Ver: " + version; + } + } + catch (Exception ex) + { + MessageBox.Show(this, + "초기 DB 연결에는 성공했지만 버전 조회 중 오류가 발생했습니다.\r\n\r\n" + ex.Message, + "초기화 경고", + MessageBoxButtons.OK, + MessageBoxIcon.Warning); + } + } + + private void ShowDataInput() + { + HideChildren(); + if (_dataForm == null || _dataForm.IsDisposed) + { + _dataForm = new DataInputForm(); + _dataForm.SetServices(_excelImportService); + _dataForm.MdiParent = this; + } + + _dataForm.Show(); + _dataForm.BringToFront(); + } + + private void ShowReal() + { + HideChildren(); + if (_realForm == null || _realForm.IsDisposed) + { + _realForm = new RealExtractionForm(); + _realForm.SetConnectionFactory(_connectionFactory); + _realForm.MdiParent = this; + } + + _realForm.Show(); + _realForm.BringToFront(); + } + + private void HideChildren() + { + foreach (Form child in MdiChildren) + { + child.Hide(); + } + } + } +} diff --git a/Keps.WinForms/Forms/MainMdiForm.resx b/Keps.WinForms/Forms/MainMdiForm.resx new file mode 100644 index 0000000..012ed34 --- /dev/null +++ b/Keps.WinForms/Forms/MainMdiForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/Keps.WinForms/Forms/RealExtractionForm.Designer.cs b/Keps.WinForms/Forms/RealExtractionForm.Designer.cs new file mode 100644 index 0000000..5d05648 --- /dev/null +++ b/Keps.WinForms/Forms/RealExtractionForm.Designer.cs @@ -0,0 +1,648 @@ +using System.Drawing; + +namespace Keps.WinForms.Forms +{ + partial class RealExtractionForm + { + private System.ComponentModel.IContainer components = null; + private System.Windows.Forms.TableLayoutPanel _rootLayout; + private System.Windows.Forms.Panel _headerPanel; + private System.Windows.Forms.Label _lblQuickCaption; + private System.Windows.Forms.Label _lblOffsetPreview; + private System.Windows.Forms.Label _lblMainStatus; + private System.Windows.Forms.ProgressBar _progressBar; + private System.Windows.Forms.Label _lblDetailStatus; + private System.Windows.Forms.GroupBox _grpCriteria; + private System.Windows.Forms.Label _lblElectionCaption; + private System.Windows.Forms.ComboBox _cmbElection; + private System.Windows.Forms.Label _lblAreaCaption; + private System.Windows.Forms.ComboBox _cmbArea; + private System.Windows.Forms.Label _lblClusterCaption; + private System.Windows.Forms.ComboBox _cmbClusterMax; + private System.Windows.Forms.Label _lblSortMetricCaption; + private System.Windows.Forms.ComboBox _cmbSortMetric; + private System.Windows.Forms.ComboBox _cmbSortDirection; + private System.Windows.Forms.Button _btnPrepare; + private System.Windows.Forms.Button _btnExtract; + private System.Windows.Forms.SplitContainer _outerSplit; + private System.Windows.Forms.TableLayoutPanel _bodyLayout; + private System.Windows.Forms.GroupBox _grpSampleOption; + private System.Windows.Forms.RadioButton _rdoAuto; + private System.Windows.Forms.RadioButton _rdoManual; + private System.Windows.Forms.NumericUpDown _numTotalSamples; + private System.Windows.Forms.Label _lblTotalCaption; + private System.Windows.Forms.Panel _allocationPanel; + private System.Windows.Forms.DataGridView _gridAuto; + private System.Windows.Forms.DataGridView _gridManual; + private System.Windows.Forms.GroupBox _grpPosition; + private System.Windows.Forms.RadioButton _optOffsetSubtract; + private System.Windows.Forms.RadioButton _optOffsetBasic; + private System.Windows.Forms.RadioButton _optOffsetAdd; + private System.Windows.Forms.Label _lblOffsetRange; + private System.Windows.Forms.Label _lblOffsetValue; + private System.Windows.Forms.NumericUpDown _numOffsetValue; + private System.Windows.Forms.GroupBox _grpAdjustment; + private System.Windows.Forms.DataGridView _gridAdjustment; + private System.Windows.Forms.GroupBox _grpVerification; + private System.Windows.Forms.DataGridView _gridVerification; + private System.Windows.Forms.GroupBox _grpResult; + private System.Windows.Forms.DataGridView _gridResult; + private System.Windows.Forms.FlowLayoutPanel _exportPanel; + private System.Windows.Forms.Button _btnExportExcel; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this._rootLayout = new System.Windows.Forms.TableLayoutPanel(); + this._headerPanel = new System.Windows.Forms.Panel(); + this._lblQuickCaption = new System.Windows.Forms.Label(); + this._lblOffsetPreview = new System.Windows.Forms.Label(); + this._lblMainStatus = new System.Windows.Forms.Label(); + this._progressBar = new System.Windows.Forms.ProgressBar(); + this._lblDetailStatus = new System.Windows.Forms.Label(); + this._grpCriteria = new System.Windows.Forms.GroupBox(); + this._lblElectionCaption = new System.Windows.Forms.Label(); + this._cmbElection = new System.Windows.Forms.ComboBox(); + this._lblAreaCaption = new System.Windows.Forms.Label(); + this._cmbArea = new System.Windows.Forms.ComboBox(); + this._lblClusterCaption = new System.Windows.Forms.Label(); + this._cmbClusterMax = new System.Windows.Forms.ComboBox(); + this._lblSortMetricCaption = new System.Windows.Forms.Label(); + this._cmbSortMetric = new System.Windows.Forms.ComboBox(); + this._cmbSortDirection = new System.Windows.Forms.ComboBox(); + this._btnPrepare = new System.Windows.Forms.Button(); + this._btnExtract = new System.Windows.Forms.Button(); + this._outerSplit = new System.Windows.Forms.SplitContainer(); + this._bodyLayout = new System.Windows.Forms.TableLayoutPanel(); + this._grpSampleOption = new System.Windows.Forms.GroupBox(); + this._rdoAuto = new System.Windows.Forms.RadioButton(); + this._rdoManual = new System.Windows.Forms.RadioButton(); + this._lblTotalCaption = new System.Windows.Forms.Label(); + this._numTotalSamples = new System.Windows.Forms.NumericUpDown(); + this._allocationPanel = new System.Windows.Forms.Panel(); + this._gridAuto = new System.Windows.Forms.DataGridView(); + this._gridManual = new System.Windows.Forms.DataGridView(); + this._grpPosition = new System.Windows.Forms.GroupBox(); + this._optOffsetSubtract = new System.Windows.Forms.RadioButton(); + this._optOffsetBasic = new System.Windows.Forms.RadioButton(); + this._optOffsetAdd = new System.Windows.Forms.RadioButton(); + this._lblOffsetRange = new System.Windows.Forms.Label(); + this._lblOffsetValue = new System.Windows.Forms.Label(); + this._numOffsetValue = new System.Windows.Forms.NumericUpDown(); + this._grpAdjustment = new System.Windows.Forms.GroupBox(); + this._gridAdjustment = new System.Windows.Forms.DataGridView(); + this._grpVerification = new System.Windows.Forms.GroupBox(); + this._gridVerification = new System.Windows.Forms.DataGridView(); + this._grpResult = new System.Windows.Forms.GroupBox(); + this._gridResult = new System.Windows.Forms.DataGridView(); + this._exportPanel = new System.Windows.Forms.FlowLayoutPanel(); + this._btnExportExcel = new System.Windows.Forms.Button(); + this._rootLayout.SuspendLayout(); + this._headerPanel.SuspendLayout(); + this._grpCriteria.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this._outerSplit)).BeginInit(); + this._outerSplit.Panel1.SuspendLayout(); + this._outerSplit.Panel2.SuspendLayout(); + this._outerSplit.SuspendLayout(); + this._bodyLayout.SuspendLayout(); + this._grpSampleOption.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this._numTotalSamples)).BeginInit(); + this._allocationPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this._gridAuto)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this._gridManual)).BeginInit(); + this._grpPosition.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this._numOffsetValue)).BeginInit(); + this._grpAdjustment.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this._gridAdjustment)).BeginInit(); + this._grpVerification.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this._gridVerification)).BeginInit(); + this._grpResult.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this._gridResult)).BeginInit(); + this._exportPanel.SuspendLayout(); + this.SuspendLayout(); + // + // _rootLayout + // + this._rootLayout.ColumnCount = 1; + this._rootLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this._rootLayout.Controls.Add(this._headerPanel, 0, 0); + this._rootLayout.Controls.Add(this._grpCriteria, 0, 1); + this._rootLayout.Controls.Add(this._outerSplit, 0, 2); + this._rootLayout.Dock = System.Windows.Forms.DockStyle.Fill; + this._rootLayout.Location = new System.Drawing.Point(0, 0); + this._rootLayout.Name = "_rootLayout"; + this._rootLayout.RowCount = 3; + this._rootLayout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 125F)); + this._rootLayout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 105F)); + this._rootLayout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this._rootLayout.Size = new System.Drawing.Size(1528, 860); + this._rootLayout.TabIndex = 0; + // + // _headerPanel + // + this._headerPanel.Controls.Add(this._lblQuickCaption); + this._headerPanel.Controls.Add(this._lblOffsetPreview); + this._headerPanel.Controls.Add(this._lblMainStatus); + this._headerPanel.Controls.Add(this._progressBar); + this._headerPanel.Controls.Add(this._lblDetailStatus); + this._headerPanel.Dock = System.Windows.Forms.DockStyle.Fill; + this._headerPanel.Location = new System.Drawing.Point(3, 3); + this._headerPanel.Name = "_headerPanel"; + this._headerPanel.Size = new System.Drawing.Size(1522, 119); + this._headerPanel.TabIndex = 0; + // + // _lblQuickCaption + // + this._lblQuickCaption.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this._lblQuickCaption.Font = new System.Drawing.Font("굴림", 9F, System.Drawing.FontStyle.Bold); + this._lblQuickCaption.Location = new System.Drawing.Point(25, 18); + this._lblQuickCaption.Name = "_lblQuickCaption"; + this._lblQuickCaption.Size = new System.Drawing.Size(100, 28); + this._lblQuickCaption.TabIndex = 0; + this._lblQuickCaption.Text = "추출위치"; + this._lblQuickCaption.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // _lblOffsetPreview + // + this._lblOffsetPreview.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this._lblOffsetPreview.Font = new System.Drawing.Font("굴림", 9F); + this._lblOffsetPreview.Location = new System.Drawing.Point(135, 18); + this._lblOffsetPreview.Name = "_lblOffsetPreview"; + this._lblOffsetPreview.Size = new System.Drawing.Size(110, 28); + this._lblOffsetPreview.TabIndex = 1; + this._lblOffsetPreview.Text = "n - 0"; + this._lblOffsetPreview.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // _lblMainStatus + // + this._lblMainStatus.AutoSize = true; + this._lblMainStatus.Font = new System.Drawing.Font("굴림", 15.75F); + this._lblMainStatus.Location = new System.Drawing.Point(20, 68); + this._lblMainStatus.Name = "_lblMainStatus"; + this._lblMainStatus.Size = new System.Drawing.Size(94, 21); + this._lblMainStatus.TabIndex = 3; + this._lblMainStatus.Text = "완료......"; + // + // _progressBar + // + this._progressBar.Location = new System.Drawing.Point(24, 94); + this._progressBar.Name = "_progressBar"; + this._progressBar.Size = new System.Drawing.Size(640, 18); + this._progressBar.TabIndex = 4; + // + // _lblDetailStatus + // + this._lblDetailStatus.AutoSize = true; + this._lblDetailStatus.Font = new System.Drawing.Font("굴림", 14.25F); + this._lblDetailStatus.ForeColor = System.Drawing.Color.Blue; + this._lblDetailStatus.Location = new System.Drawing.Point(680, 93); + this._lblDetailStatus.Name = "_lblDetailStatus"; + this._lblDetailStatus.Size = new System.Drawing.Size(95, 19); + this._lblDetailStatus.TabIndex = 5; + this._lblDetailStatus.Text = "100.000 %"; + // + // _grpCriteria + // + this._grpCriteria.Controls.Add(this._lblElectionCaption); + this._grpCriteria.Controls.Add(this._cmbElection); + this._grpCriteria.Controls.Add(this._lblAreaCaption); + this._grpCriteria.Controls.Add(this._cmbArea); + this._grpCriteria.Controls.Add(this._lblClusterCaption); + this._grpCriteria.Controls.Add(this._cmbClusterMax); + this._grpCriteria.Controls.Add(this._lblSortMetricCaption); + this._grpCriteria.Controls.Add(this._cmbSortMetric); + this._grpCriteria.Controls.Add(this._cmbSortDirection); + this._grpCriteria.Controls.Add(this._btnPrepare); + this._grpCriteria.Controls.Add(this._btnExtract); + this._grpCriteria.Dock = System.Windows.Forms.DockStyle.Fill; + this._grpCriteria.Font = new System.Drawing.Font("굴림", 12F, System.Drawing.FontStyle.Bold); + this._grpCriteria.ForeColor = System.Drawing.Color.Blue; + this._grpCriteria.Location = new System.Drawing.Point(3, 128); + this._grpCriteria.Name = "_grpCriteria"; + this._grpCriteria.Size = new System.Drawing.Size(1522, 99); + this._grpCriteria.TabIndex = 1; + this._grpCriteria.TabStop = false; + this._grpCriteria.Text = "추출용 선거"; + // + // _lblElectionCaption + // + this._lblElectionCaption.AutoSize = true; + this._lblElectionCaption.Location = new System.Drawing.Point(22, 33); + this._lblElectionCaption.Name = "_lblElectionCaption"; + this._lblElectionCaption.Size = new System.Drawing.Size(41, 16); + this._lblElectionCaption.TabIndex = 0; + this._lblElectionCaption.Text = "선거"; + // + // _cmbElection + // + this._cmbElection.FormattingEnabled = true; + this._cmbElection.Location = new System.Drawing.Point(78, 29); + this._cmbElection.Name = "_cmbElection"; + this._cmbElection.Size = new System.Drawing.Size(110, 24); + this._cmbElection.TabIndex = 1; + // + // _lblAreaCaption + // + this._lblAreaCaption.AutoSize = true; + this._lblAreaCaption.Location = new System.Drawing.Point(218, 33); + this._lblAreaCaption.Name = "_lblAreaCaption"; + this._lblAreaCaption.Size = new System.Drawing.Size(41, 16); + this._lblAreaCaption.TabIndex = 2; + this._lblAreaCaption.Text = "지역"; + // + // _cmbArea + // + this._cmbArea.FormattingEnabled = true; + this._cmbArea.Location = new System.Drawing.Point(270, 29); + this._cmbArea.Name = "_cmbArea"; + this._cmbArea.Size = new System.Drawing.Size(110, 24); + this._cmbArea.TabIndex = 3; + // + // _lblClusterCaption + // + this._lblClusterCaption.AutoSize = true; + this._lblClusterCaption.Location = new System.Drawing.Point(405, 33); + this._lblClusterCaption.Name = "_lblClusterCaption"; + this._lblClusterCaption.Size = new System.Drawing.Size(72, 16); + this._lblClusterCaption.TabIndex = 4; + this._lblClusterCaption.Text = "층(군집)"; + // + // _cmbClusterMax + // + this._cmbClusterMax.FormattingEnabled = true; + this._cmbClusterMax.Location = new System.Drawing.Point(476, 29); + this._cmbClusterMax.Name = "_cmbClusterMax"; + this._cmbClusterMax.Size = new System.Drawing.Size(96, 24); + this._cmbClusterMax.TabIndex = 5; + // + // _lblSortMetricCaption + // + this._lblSortMetricCaption.AutoSize = true; + this._lblSortMetricCaption.Location = new System.Drawing.Point(598, 33); + this._lblSortMetricCaption.Name = "_lblSortMetricCaption"; + this._lblSortMetricCaption.Size = new System.Drawing.Size(41, 16); + this._lblSortMetricCaption.TabIndex = 6; + this._lblSortMetricCaption.Text = "Sort"; + // + // _cmbSortMetric + // + this._cmbSortMetric.FormattingEnabled = true; + this._cmbSortMetric.Location = new System.Drawing.Point(648, 29); + this._cmbSortMetric.Name = "_cmbSortMetric"; + this._cmbSortMetric.Size = new System.Drawing.Size(160, 24); + this._cmbSortMetric.TabIndex = 7; + // + // _cmbSortDirection + // + this._cmbSortDirection.FormattingEnabled = true; + this._cmbSortDirection.Location = new System.Drawing.Point(818, 29); + this._cmbSortDirection.Name = "_cmbSortDirection"; + this._cmbSortDirection.Size = new System.Drawing.Size(96, 24); + this._cmbSortDirection.TabIndex = 8; + // + // _btnPrepare + // + this._btnPrepare.Font = new System.Drawing.Font("굴림", 11.25F, System.Drawing.FontStyle.Bold); + this._btnPrepare.ForeColor = System.Drawing.Color.Black; + this._btnPrepare.Location = new System.Drawing.Point(24, 61); + this._btnPrepare.Name = "_btnPrepare"; + this._btnPrepare.Size = new System.Drawing.Size(170, 30); + this._btnPrepare.TabIndex = 9; + this._btnPrepare.Text = "1. 추출 사전 단계"; + this._btnPrepare.UseVisualStyleBackColor = true; + // + // _btnExtract + // + this._btnExtract.Font = new System.Drawing.Font("굴림", 11.25F, System.Drawing.FontStyle.Bold); + this._btnExtract.ForeColor = System.Drawing.Color.Black; + this._btnExtract.Location = new System.Drawing.Point(205, 61); + this._btnExtract.Name = "_btnExtract"; + this._btnExtract.Size = new System.Drawing.Size(270, 30); + this._btnExtract.TabIndex = 10; + this._btnExtract.Text = "2. 추출 및 검즘-등간 정수"; + this._btnExtract.UseVisualStyleBackColor = true; + // + // _outerSplit + // + this._outerSplit.Dock = System.Windows.Forms.DockStyle.Fill; + this._outerSplit.Location = new System.Drawing.Point(3, 233); + this._outerSplit.Name = "_outerSplit"; + this._outerSplit.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // _outerSplit.Panel1 + // + this._outerSplit.Panel1.Controls.Add(this._bodyLayout); + // + // _outerSplit.Panel2 + // + this._outerSplit.Panel2.Controls.Add(this._grpResult); + this._outerSplit.Panel2.Controls.Add(this._exportPanel); + this._outerSplit.Size = new System.Drawing.Size(1522, 624); + this._outerSplit.SplitterDistance = 350; + this._outerSplit.TabIndex = 2; + // + // _bodyLayout + // + this._bodyLayout.ColumnCount = 3; + this._bodyLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 27.85808F)); + this._bodyLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 14.12615F)); + this._bodyLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 58.01577F)); + this._bodyLayout.Controls.Add(this._grpSampleOption, 0, 0); + this._bodyLayout.Controls.Add(this._grpAdjustment, 1, 0); + this._bodyLayout.Controls.Add(this._grpVerification, 2, 0); + this._bodyLayout.Dock = System.Windows.Forms.DockStyle.Fill; + this._bodyLayout.Location = new System.Drawing.Point(0, 0); + this._bodyLayout.Name = "_bodyLayout"; + this._bodyLayout.RowCount = 1; + this._bodyLayout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this._bodyLayout.Size = new System.Drawing.Size(1522, 350); + this._bodyLayout.TabIndex = 0; + // + // _grpSampleOption + // + this._grpSampleOption.Controls.Add(this._rdoAuto); + this._grpSampleOption.Controls.Add(this._rdoManual); + this._grpSampleOption.Controls.Add(this._lblTotalCaption); + this._grpSampleOption.Controls.Add(this._numTotalSamples); + this._grpSampleOption.Controls.Add(this._allocationPanel); + this._grpSampleOption.Controls.Add(this._grpPosition); + this._grpSampleOption.Dock = System.Windows.Forms.DockStyle.Fill; + this._grpSampleOption.Font = new System.Drawing.Font("굴림", 10.5F, System.Drawing.FontStyle.Bold); + this._grpSampleOption.Location = new System.Drawing.Point(3, 3); + this._grpSampleOption.Name = "_grpSampleOption"; + this._grpSampleOption.Size = new System.Drawing.Size(418, 344); + this._grpSampleOption.TabIndex = 0; + this._grpSampleOption.TabStop = false; + this._grpSampleOption.Text = "투표구수 지정 옵션"; + // + // _rdoAuto + // + this._rdoAuto.AutoSize = true; + this._rdoAuto.ForeColor = System.Drawing.Color.Blue; + this._rdoAuto.Location = new System.Drawing.Point(18, 28); + this._rdoAuto.Name = "_rdoAuto"; + this._rdoAuto.Size = new System.Drawing.Size(163, 18); + this._rdoAuto.TabIndex = 0; + this._rdoAuto.TabStop = true; + this._rdoAuto.Text = "합계 기준 자동 설정"; + this._rdoAuto.UseVisualStyleBackColor = true; + // + // _rdoManual + // + this._rdoManual.AutoSize = true; + this._rdoManual.ForeColor = System.Drawing.Color.Blue; + this._rdoManual.Location = new System.Drawing.Point(186, 28); + this._rdoManual.Name = "_rdoManual"; + this._rdoManual.Size = new System.Drawing.Size(207, 18); + this._rdoManual.TabIndex = 1; + this._rdoManual.Text = "층(군집)별 개수 수동 지정"; + this._rdoManual.UseVisualStyleBackColor = true; + // + // _lblTotalCaption + // + this._lblTotalCaption.AutoSize = true; + this._lblTotalCaption.Location = new System.Drawing.Point(206, 57); + this._lblTotalCaption.Name = "_lblTotalCaption"; + this._lblTotalCaption.Size = new System.Drawing.Size(118, 14); + this._lblTotalCaption.TabIndex = 2; + this._lblTotalCaption.Text = "총 추출투표구수"; + // + // _numTotalSamples + // + this._numTotalSamples.Location = new System.Drawing.Point(321, 53); + this._numTotalSamples.Name = "_numTotalSamples"; + this._numTotalSamples.Size = new System.Drawing.Size(83, 24); + this._numTotalSamples.TabIndex = 3; + // + // _allocationPanel + // + this._allocationPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this._allocationPanel.Controls.Add(this._gridAuto); + this._allocationPanel.Controls.Add(this._gridManual); + this._allocationPanel.Location = new System.Drawing.Point(12, 82); + this._allocationPanel.Name = "_allocationPanel"; + this._allocationPanel.Size = new System.Drawing.Size(395, 153); + this._allocationPanel.TabIndex = 4; + // + // _gridAuto + // + this._gridAuto.Dock = System.Windows.Forms.DockStyle.Fill; + this._gridAuto.Location = new System.Drawing.Point(0, 0); + this._gridAuto.Name = "_gridAuto"; + this._gridAuto.Size = new System.Drawing.Size(395, 153); + this._gridAuto.TabIndex = 0; + // + // _gridManual + // + this._gridManual.Dock = System.Windows.Forms.DockStyle.Fill; + this._gridManual.Location = new System.Drawing.Point(0, 0); + this._gridManual.Name = "_gridManual"; + this._gridManual.Size = new System.Drawing.Size(395, 153); + this._gridManual.TabIndex = 1; + // + // _grpPosition + // + this._grpPosition.Controls.Add(this._optOffsetSubtract); + this._grpPosition.Controls.Add(this._optOffsetBasic); + this._grpPosition.Controls.Add(this._optOffsetAdd); + this._grpPosition.Controls.Add(this._lblOffsetRange); + this._grpPosition.Controls.Add(this._lblOffsetValue); + this._grpPosition.Controls.Add(this._numOffsetValue); + this._grpPosition.Font = new System.Drawing.Font("굴림", 10.5F, System.Drawing.FontStyle.Bold); + this._grpPosition.ForeColor = System.Drawing.Color.Blue; + this._grpPosition.Location = new System.Drawing.Point(12, 241); + this._grpPosition.Name = "_grpPosition"; + this._grpPosition.Size = new System.Drawing.Size(390, 95); + this._grpPosition.TabIndex = 5; + this._grpPosition.TabStop = false; + this._grpPosition.Text = "추출위치"; + // + // _optOffsetSubtract + // + this._optOffsetSubtract.AutoSize = true; + this._optOffsetSubtract.Location = new System.Drawing.Point(14, 24); + this._optOffsetSubtract.Name = "_optOffsetSubtract"; + this._optOffsetSubtract.Size = new System.Drawing.Size(121, 18); + this._optOffsetSubtract.TabIndex = 0; + this._optOffsetSubtract.Text = "추출위치 빼기"; + this._optOffsetSubtract.UseVisualStyleBackColor = true; + // + // _optOffsetBasic + // + this._optOffsetBasic.AutoSize = true; + this._optOffsetBasic.Location = new System.Drawing.Point(14, 46); + this._optOffsetBasic.Name = "_optOffsetBasic"; + this._optOffsetBasic.Size = new System.Drawing.Size(55, 18); + this._optOffsetBasic.TabIndex = 1; + this._optOffsetBasic.Text = "기본"; + this._optOffsetBasic.UseVisualStyleBackColor = true; + // + // _optOffsetAdd + // + this._optOffsetAdd.AutoSize = true; + this._optOffsetAdd.Location = new System.Drawing.Point(14, 68); + this._optOffsetAdd.Name = "_optOffsetAdd"; + this._optOffsetAdd.Size = new System.Drawing.Size(136, 18); + this._optOffsetAdd.TabIndex = 2; + this._optOffsetAdd.Text = "추출위치 더하기"; + this._optOffsetAdd.UseVisualStyleBackColor = true; + // + // _lblOffsetRange + // + this._lblOffsetRange.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this._lblOffsetRange.ForeColor = System.Drawing.Color.Black; + this._lblOffsetRange.Location = new System.Drawing.Point(161, 19); + this._lblOffsetRange.Name = "_lblOffsetRange"; + this._lblOffsetRange.Size = new System.Drawing.Size(210, 25); + this._lblOffsetRange.TabIndex = 3; + this._lblOffsetRange.Text = "가감 범위 1 ~ 11"; + this._lblOffsetRange.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // _lblOffsetValue + // + this._lblOffsetValue.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this._lblOffsetValue.ForeColor = System.Drawing.Color.Black; + this._lblOffsetValue.Location = new System.Drawing.Point(161, 55); + this._lblOffsetValue.Name = "_lblOffsetValue"; + this._lblOffsetValue.Size = new System.Drawing.Size(102, 25); + this._lblOffsetValue.TabIndex = 4; + this._lblOffsetValue.Text = "가감 값"; + this._lblOffsetValue.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // _numOffsetValue + // + this._numOffsetValue.Location = new System.Drawing.Point(278, 57); + this._numOffsetValue.Name = "_numOffsetValue"; + this._numOffsetValue.Size = new System.Drawing.Size(74, 24); + this._numOffsetValue.TabIndex = 5; + // + // _grpAdjustment + // + this._grpAdjustment.Controls.Add(this._gridAdjustment); + this._grpAdjustment.Dock = System.Windows.Forms.DockStyle.Fill; + this._grpAdjustment.Font = new System.Drawing.Font("굴림", 10.5F, System.Drawing.FontStyle.Bold); + this._grpAdjustment.Location = new System.Drawing.Point(427, 3); + this._grpAdjustment.Name = "_grpAdjustment"; + this._grpAdjustment.Size = new System.Drawing.Size(209, 344); + this._grpAdjustment.TabIndex = 1; + this._grpAdjustment.TabStop = false; + this._grpAdjustment.Text = "수동 조정시 층별 ID 조정"; + // + // _gridAdjustment + // + this._gridAdjustment.Dock = System.Windows.Forms.DockStyle.Fill; + this._gridAdjustment.Location = new System.Drawing.Point(3, 20); + this._gridAdjustment.Name = "_gridAdjustment"; + this._gridAdjustment.Size = new System.Drawing.Size(203, 321); + this._gridAdjustment.TabIndex = 0; + // + // _grpVerification + // + this._grpVerification.Controls.Add(this._gridVerification); + this._grpVerification.Dock = System.Windows.Forms.DockStyle.Fill; + this._grpVerification.Font = new System.Drawing.Font("굴림", 10.5F, System.Drawing.FontStyle.Bold); + this._grpVerification.Location = new System.Drawing.Point(642, 3); + this._grpVerification.Name = "_grpVerification"; + this._grpVerification.Size = new System.Drawing.Size(877, 344); + this._grpVerification.TabIndex = 2; + this._grpVerification.TabStop = false; + this._grpVerification.Text = "자가 검증 - 요약분석"; + // + // _gridVerification + // + this._gridVerification.Dock = System.Windows.Forms.DockStyle.Fill; + this._gridVerification.Location = new System.Drawing.Point(3, 20); + this._gridVerification.Name = "_gridVerification"; + this._gridVerification.Size = new System.Drawing.Size(871, 321); + this._gridVerification.TabIndex = 0; + // + // _grpResult + // + this._grpResult.Controls.Add(this._gridResult); + this._grpResult.Dock = System.Windows.Forms.DockStyle.Fill; + this._grpResult.Font = new System.Drawing.Font("굴림", 10.5F, System.Drawing.FontStyle.Bold); + this._grpResult.Location = new System.Drawing.Point(0, 34); + this._grpResult.Name = "_grpResult"; + this._grpResult.Size = new System.Drawing.Size(1522, 236); + this._grpResult.TabIndex = 1; + this._grpResult.TabStop = false; + this._grpResult.Text = "최종 투표소 추출현황"; + // + // _gridResult + // + this._gridResult.Dock = System.Windows.Forms.DockStyle.Fill; + this._gridResult.Location = new System.Drawing.Point(3, 20); + this._gridResult.Name = "_gridResult"; + this._gridResult.Size = new System.Drawing.Size(1516, 213); + this._gridResult.TabIndex = 0; + // + // _exportPanel + // + this._exportPanel.Controls.Add(this._btnExportExcel); + this._exportPanel.Dock = System.Windows.Forms.DockStyle.Top; + this._exportPanel.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft; + this._exportPanel.Location = new System.Drawing.Point(0, 0); + this._exportPanel.Name = "_exportPanel"; + this._exportPanel.Padding = new System.Windows.Forms.Padding(6); + this._exportPanel.Size = new System.Drawing.Size(1522, 34); + this._exportPanel.TabIndex = 0; + // + // _btnExportExcel + // + this._btnExportExcel.Location = new System.Drawing.Point(1418, 9); + this._btnExportExcel.Name = "_btnExportExcel"; + this._btnExportExcel.Size = new System.Drawing.Size(89, 23); + this._btnExportExcel.TabIndex = 0; + this._btnExportExcel.Text = "엑셀 저장"; + this._btnExportExcel.UseVisualStyleBackColor = true; + // + // RealExtractionForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1528, 860); + this.Controls.Add(this._rootLayout); + this.Name = "RealExtractionForm"; + this.Text = "KEPS(Korea Research Exit Poll Sampling) - [층화 후 득표율 기준 정렬 등간 추출 방식 - 최종 투표구 추출]"; + this.WindowState = System.Windows.Forms.FormWindowState.Maximized; + this._rootLayout.ResumeLayout(false); + this._headerPanel.ResumeLayout(false); + this._headerPanel.PerformLayout(); + this._grpCriteria.ResumeLayout(false); + this._grpCriteria.PerformLayout(); + this._outerSplit.Panel1.ResumeLayout(false); + this._outerSplit.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this._outerSplit)).EndInit(); + this._outerSplit.ResumeLayout(false); + this._bodyLayout.ResumeLayout(false); + this._grpSampleOption.ResumeLayout(false); + this._grpSampleOption.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this._numTotalSamples)).EndInit(); + this._allocationPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this._gridAuto)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this._gridManual)).EndInit(); + this._grpPosition.ResumeLayout(false); + this._grpPosition.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this._numOffsetValue)).EndInit(); + this._grpAdjustment.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this._gridAdjustment)).EndInit(); + this._grpVerification.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this._gridVerification)).EndInit(); + this._grpResult.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this._gridResult)).EndInit(); + this._exportPanel.ResumeLayout(false); + this.ResumeLayout(false); + + } + } +} diff --git a/Keps.WinForms/Forms/RealExtractionForm.cs b/Keps.WinForms/Forms/RealExtractionForm.cs new file mode 100644 index 0000000..f58b71c --- /dev/null +++ b/Keps.WinForms/Forms/RealExtractionForm.cs @@ -0,0 +1,546 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Windows.Forms; +using Keps.WinForms.Infrastructure; +using Keps.WinForms.Models; +using Keps.WinForms.Services; + +namespace Keps.WinForms.Forms +{ + public sealed partial class RealExtractionForm : Form + { + private SqlConnectionFactory _connectionFactory; + private LookupService _lookupService; + private SamplingService _samplingService; + private ExcelReportService _excelReportService; + private RealScenarioContext _preparedContext; + + private BindingList _autoRows = new BindingList(); + private BindingList _manualRows = new BindingList(); + private BindingList _adjustmentRows = new BindingList(); + private BindingList _verificationRows = new BindingList(); + private BindingList _resultRows = new BindingList(); + private RealExtractionResult _lastResult; + private List _candidateNames = new List(); + + public RealExtractionForm() + { + InitializeComponent(); + WireEvents(); + InitializeDefaults(); + InitializeGridColumns(); + } + + public void SetConnectionFactory(SqlConnectionFactory connectionFactory) + { + _connectionFactory = connectionFactory; + if (_connectionFactory == null) + { + _lookupService = null; + _samplingService = null; + _excelReportService = null; + return; + } + + _lookupService = new LookupService(_connectionFactory); + _samplingService = new SamplingService(_connectionFactory); + _excelReportService = new ExcelReportService(); + } + + private void WireEvents() + { + Load += RealExtractionForm_Load; + _cmbElection.SelectedIndexChanged += CmbElection_SelectedIndexChanged; + _cmbArea.SelectedIndexChanged += CmbArea_SelectedIndexChanged; + _btnPrepare.Click += BtnPrepare_Click; + _btnExtract.Click += BtnExtract_Click; + _btnExportExcel.Click += BtnExportExcel_Click; + _rdoAuto.CheckedChanged += ToggleAllocationMode; + _rdoManual.CheckedChanged += ToggleAllocationMode; + _optOffsetSubtract.CheckedChanged += OffsetModeChanged; + _optOffsetBasic.CheckedChanged += OffsetModeChanged; + _optOffsetAdd.CheckedChanged += OffsetModeChanged; + _numOffsetValue.ValueChanged += OffsetModeChanged; + _numTotalSamples.ValueChanged += TotalSamplesChanged; + } + + private void InitializeDefaults() + { + _cmbElection.DropDownStyle = ComboBoxStyle.DropDownList; + _cmbArea.DropDownStyle = ComboBoxStyle.DropDownList; + _cmbClusterMax.DropDownStyle = ComboBoxStyle.DropDownList; + _cmbSortMetric.DropDownStyle = ComboBoxStyle.DropDownList; + _cmbSortDirection.DropDownStyle = ComboBoxStyle.DropDownList; + + _cmbSortDirection.Items.Add("내림차순"); + _cmbSortDirection.Items.Add("오름차순"); + _cmbSortDirection.SelectedIndex = 0; + + _numTotalSamples.Minimum = 1; + _numTotalSamples.Maximum = 5000; + _numTotalSamples.Value = 123; + _numOffsetValue.Minimum = 0; + _numOffsetValue.Maximum = 100; + _preparedContext = null; + + _rdoAuto.Checked = true; + _optOffsetBasic.Checked = true; + _lblMainStatus.Text = "완료......"; + _lblDetailStatus.Text = "0.000 %"; + _progressBar.Value = 0; + ToggleAllocationMode(this, EventArgs.Empty); + OffsetModeChanged(this, EventArgs.Empty); + } + + private void RealExtractionForm_Load(object sender, EventArgs e) + { + if (_lookupService == null) + { + _lblMainStatus.Text = "서비스 미연결"; + return; + } + + ReloadElections(); + } + + private void ReloadElections() + { + _cmbElection.Items.Clear(); + foreach (string item in _lookupService.LoadRealElections()) + { + _cmbElection.Items.Add(item); + } + + if (_cmbElection.Items.Count > 0) + { + _cmbElection.SelectedIndex = 0; + } + } + private void CmbElection_SelectedIndexChanged(object sender, EventArgs e) + { + if (DesignTimeHelper.IsDesignMode(this) || _lookupService == null || _cmbElection.SelectedItem == null) + { + return; + } + + _cmbArea.Items.Clear(); + _cmbClusterMax.Items.Clear(); + _cmbSortMetric.Items.Clear(); + + foreach (string area in _lookupService.LoadRealAreas(_cmbElection.SelectedItem.ToString())) + { + _cmbArea.Items.Add(area); + } + if (_cmbArea.Items.Count > 0) + { + _cmbArea.SelectedIndex = 0; + } + + foreach (CandidateOption option in _lookupService.LoadCandidateOptions(_cmbElection.SelectedItem.ToString())) + { + _cmbSortMetric.Items.Add(option); + } + _cmbSortMetric.DisplayMember = "DisplayName"; + _cmbSortMetric.ValueMember = "Key"; + if (_cmbSortMetric.Items.Count > 0) + { + _cmbSortMetric.SelectedIndex = 0; + } + } + + private void CmbArea_SelectedIndexChanged(object sender, EventArgs e) + { + if (DesignTimeHelper.IsDesignMode(this) || _lookupService == null || _cmbElection.SelectedItem == null || _cmbArea.SelectedItem == null) + { + return; + } + + _cmbClusterMax.Items.Clear(); + foreach (int value in _lookupService.LoadRealClusterMaxList(_cmbElection.SelectedItem.ToString(), _cmbArea.SelectedItem.ToString())) + { + _cmbClusterMax.Items.Add(value); + } + if (_cmbClusterMax.Items.Count > 0) + { + _cmbClusterMax.SelectedIndex = 0; + } + } + + private void BtnPrepare_Click(object sender, EventArgs e) + { + if (!ValidateScenarioInputs() || _samplingService == null) + { + return; + } + + SetProgress(10, "조건 로드 중..."); + string election = _cmbElection.SelectedItem.ToString(); + string area = _cmbArea.SelectedItem.ToString(); + int clusterMax = Convert.ToInt32(_cmbClusterMax.SelectedItem); + + RealScenarioContext context = _samplingService.LoadRealScenario(election, area, clusterMax); + _preparedContext = context; + _autoRows = new BindingList(_samplingService.AllocateAutoSampleCounts(context.AutoRows, Convert.ToInt32(_numTotalSamples.Value))); + _manualRows = new BindingList(context.ManualRows.Select(CloneRow).ToList()); + for (int i = 0; i < _manualRows.Count && i < _autoRows.Count; i++) + { + _manualRows[i].SampleCount = _autoRows[i].SampleCount; + } + + _adjustmentRows = new BindingList(BuildDefaultAdjustmentRows(GetWorkingRows())); + _verificationRows = new BindingList(); + _resultRows = new BindingList(); + _lastResult = null; + BindGridSources(); + ApplyVerificationHeaders(); + UpdateOffsetRange(); + SetProgress(100, "사전 단계 완료"); + } + + private void BtnExtract_Click(object sender, EventArgs e) + { + if (!ValidateScenarioInputs() || _samplingService == null) + { + return; + } + + List workingRows = GetWorkingRows(); + if (workingRows.Count == 0 || workingRows.All(x => x.SampleCount <= 0)) + { + MessageBox.Show(this, "추출 대상 층별 개수를 먼저 설정하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + string election = _cmbElection.SelectedItem.ToString(); + string area = _cmbArea.SelectedItem.ToString(); + int clusterMax = Convert.ToInt32(_cmbClusterMax.SelectedItem); + CandidateOption option = _cmbSortMetric.SelectedItem as CandidateOption; + string sortKey = option == null ? "투표인수" : option.Key; + bool descending = _cmbSortDirection.SelectedIndex == 0; + int offset = GetSignedOffset(); + + SetProgress(15, "최종 추출 실행 중..."); + _lastResult = _samplingService.RunRealExtraction(election, area, clusterMax, sortKey, option == null ? "투표인수" : option.DisplayName, descending, workingRows, offset, GetOffsetDescription(), _rdoAuto.Checked); + _candidateNames = (_lastResult.CandidateNames ?? new List()).ToList(); + _resultRows = new BindingList(_lastResult.ExtractedRows ?? new List()); + _adjustmentRows = new BindingList(_lastResult.AdjustmentRows ?? new List()); + _verificationRows = new BindingList(_lastResult.VerificationRows ?? new List()); + BindGridSources(); + ApplyVerificationHeaders(); + SetProgress(100, "최종 추출 완료"); + } + + private void BtnExportExcel_Click(object sender, EventArgs e) + { + if (_lastResult == null || _resultRows.Count == 0) + { + MessageBox.Show(this, "먼저 최종 추출을 실행하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + using (SaveFileDialog dialog = new SaveFileDialog()) + { + dialog.Filter = "Excel 파일 (*.xlsx)|*.xlsx"; + dialog.FileName = string.Format("층화_후_득표율_기준_{0}-{1}_최종_{2:yyyyMMdd_HHmmss}.xlsx", _cmbElection.SelectedItem, _cmbArea.SelectedItem, DateTime.Now); + if (dialog.ShowDialog(this) == DialogResult.OK) + { + _excelReportService.ExportRealExtractionWorkbook(dialog.FileName, _cmbElection.SelectedItem.ToString(), _cmbArea.SelectedItem.ToString(), GetWorkingRows(), _lastResult); + MessageBox.Show(this, "엑셀 저장 완료" + Environment.NewLine + dialog.FileName, "완료", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } + + private void TotalSamplesChanged(object sender, EventArgs e) + { + if (_samplingService == null || _preparedContext == null) + { + _lblOffsetPreview.Text = GetOffsetDescription(); + return; + } + + if (_rdoAuto.Checked) + { + _autoRows = new BindingList(_samplingService.AllocateAutoSampleCounts(_preparedContext.AutoRows, Convert.ToInt32(_numTotalSamples.Value))); + + if (_manualRows == null || _manualRows.Count != _autoRows.Count) + { + _manualRows = new BindingList(_preparedContext.ManualRows.Select(CloneRow).ToList()); + } + + for (int i = 0; i < _manualRows.Count && i < _autoRows.Count; i++) + { + _manualRows[i].SampleCount = _autoRows[i].SampleCount; + } + + BindGridSources(); + } + + UpdateOffsetRange(); + } + + private void ToggleAllocationMode(object sender, EventArgs e) + { + _gridAuto.Visible = _rdoAuto.Checked; + _gridManual.Visible = _rdoManual.Checked; + UpdateOffsetRange(); + } + + private void OffsetModeChanged(object sender, EventArgs e) + { + bool showOffset = !_optOffsetBasic.Checked; + _lblOffsetValue.Enabled = showOffset; + _numOffsetValue.Enabled = showOffset && _numOffsetValue.Maximum > 0; + _lblOffsetPreview.Text = GetOffsetDescription(); + } + + private string GetOffsetDescription() + { + if (_optOffsetBasic.Checked) + { + return "n - 0"; + } + + string prefix = _optOffsetSubtract.Checked ? "n - " : "n + "; + return prefix + Convert.ToInt32(_numOffsetValue.Value); + } + + private int GetSignedOffset() + { + if (_optOffsetBasic.Checked) + { + return 0; + } + int value = Convert.ToInt32(_numOffsetValue.Value); + return _optOffsetSubtract.Checked ? -value : value; + } + + private void UpdateOffsetRange() + { + List rows = GetWorkingRows(); + ClusterSummaryRow targetRow = rows.LastOrDefault(x => x.SampleCount > 0); + int maxRange = 0; + bool offsetEnabled = true; + + if (targetRow != null) + { + int total = targetRow.PollingPlaceCount; + int sample = Math.Max(0, targetRow.SampleCount); + if (sample > 0) + { + int interval = total / sample; + int start = interval / 2; + int endPoint = start + (interval * (sample - 1)); + int x1 = total - endPoint; + int x2 = start - 1; + start = (int)Math.Round((x1 + x2) / 2m, 0, MidpointRounding.AwayFromZero); + maxRange = total - (interval * (sample - 1)) - start; + + if (interval == 0) + { + maxRange = 0; + offsetEnabled = false; + } + } + } + + if (maxRange < 0) + { + maxRange = 0; + } + + _lblOffsetRange.Text = "가감 범위 1 ~ " + maxRange; + _numOffsetValue.Maximum = Math.Max(0, maxRange); + + if (!offsetEnabled) + { + _numOffsetValue.Value = 0; + _numOffsetValue.Enabled = false; + } + else + { + if (!_optOffsetBasic.Checked) + { + _numOffsetValue.Enabled = true; + } + if (_numOffsetValue.Value > _numOffsetValue.Maximum) + { + _numOffsetValue.Value = _numOffsetValue.Maximum; + } + } + + _lblOffsetPreview.Text = GetOffsetDescription(); + } + + private bool ValidateScenarioInputs() + { + if (_cmbElection.SelectedItem == null) + { + MessageBox.Show(this, "선거를 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return false; + } + if (_cmbArea.SelectedItem == null) + { + MessageBox.Show(this, "지역을 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return false; + } + if (_cmbClusterMax.SelectedItem == null) + { + MessageBox.Show(this, "군집수를 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return false; + } + return true; + } + + private List GetWorkingRows() + { + return (_rdoAuto.Checked ? _autoRows : _manualRows).Select(CloneRow).ToList(); + } + + private static ClusterSummaryRow CloneRow(ClusterSummaryRow source) + { + return new ClusterSummaryRow + { + ClusterNo = source.ClusterNo, + ClusterLabel = source.ClusterLabel, + PollingPlaceCount = source.PollingPlaceCount, + Ratio = source.Ratio, + SampleCount = source.SampleCount + }; + } + + private static List BuildDefaultAdjustmentRows(List rows) + { + List result = new List(); + foreach (ClusterSummaryRow row in rows) + { + int interval = row.SampleCount <= 0 ? 1 : Math.Max(1, row.PollingPlaceCount / row.SampleCount); + for (int i = 0; i < row.SampleCount; i++) + { + result.Add(new AdjustmentRow { ClusterNo = row.ClusterNo, ExtractId = 1 + (i * interval) }); + } + } + return result; + } + + private void BindGridSources() + { + _gridAuto.DataSource = _autoRows; + _gridManual.DataSource = _manualRows; + _gridAdjustment.DataSource = _adjustmentRows; + _gridVerification.DataSource = _verificationRows; + _gridResult.DataSource = _resultRows; + } + + private void SetProgress(int percent, string text) + { + _progressBar.Value = Math.Max(0, Math.Min(100, percent)); + _lblMainStatus.Text = text; + _lblDetailStatus.Text = string.Format("{0:0.000} %", percent); + } + + private void InitializeGridColumns() + { + ConfigureGridBase(_gridAuto); + ConfigureGridBase(_gridManual); + ConfigureGridBase(_gridAdjustment); + ConfigureGridBase(_gridVerification); + ConfigureGridBase(_gridResult); + + ConfigureClusterGrid(_gridAuto, true); + ConfigureClusterGrid(_gridManual, false); + ConfigureAdjustmentGrid(); + ConfigureVerificationGrid(); + ConfigureResultGrid(); + BindGridSources(); + } + + private static void ConfigureGridBase(DataGridView grid) + { + grid.AllowUserToAddRows = false; + grid.AllowUserToDeleteRows = false; + grid.RowHeadersVisible = false; + grid.SelectionMode = DataGridViewSelectionMode.CellSelect; + grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; + grid.BackgroundColor = System.Drawing.Color.White; + grid.BorderStyle = BorderStyle.FixedSingle; + } + + private static void ConfigureClusterGrid(DataGridView grid, bool readOnlySampleCount) + { + grid.AutoGenerateColumns = false; + grid.Columns.Clear(); + grid.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ClusterNo", HeaderText = "층", ReadOnly = true, Width = 50 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "PollingPlaceCount", HeaderText = "투표구수", ReadOnly = true, Width = 80 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Ratio", HeaderText = "층의비율", ReadOnly = true, Width = 85, DefaultCellStyle = new DataGridViewCellStyle { Format = "0.00000" } }); + grid.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "SampleCount", HeaderText = "층별추출개수", ReadOnly = readOnlySampleCount, Width = 95 }); + } + + private void ConfigureAdjustmentGrid() + { + _gridAdjustment.AutoGenerateColumns = false; + _gridAdjustment.Columns.Clear(); + _gridAdjustment.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ClusterNo", HeaderText = "층", ReadOnly = true, Width = 45 }); + _gridAdjustment.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ExtractId", HeaderText = "추출ID", ReadOnly = true, Width = 70 }); + _gridAdjustment.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "AdjustId", HeaderText = "조정ID", Width = 70 }); + } + + private void ConfigureVerificationGrid() + { + _gridVerification.AutoGenerateColumns = false; + _gridVerification.Columns.Clear(); + _gridVerification.ColumnHeadersHeight = 42; // 원하는 높이 + + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "RowLabel", HeaderText = "구분", ReadOnly = true, Width = 70 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Extracted1", HeaderText = "추출1", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Extracted2", HeaderText = "추출2", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Extracted3", HeaderText = "추출3", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Actual1", HeaderText = "실제1", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Actual2", HeaderText = "실제2", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Actual3", HeaderText = "실제3", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "WeightedError1", HeaderText = "1오차", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "WeightedError2", HeaderText = "2오차", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "WeightedError3", HeaderText = "3오차", ReadOnly = true, Width = 80 }); + _gridVerification.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "WeightedErrorSum", HeaderText = "오차합", ReadOnly = true, Width = 80 }); + } + + private void ConfigureResultGrid() + { + _gridResult.AutoGenerateColumns = false; + _gridResult.Columns.Clear(); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ClusterNo", HeaderText = "층", ReadOnly = true, Width = 45 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ClusterOrder", HeaderText = "추출순번", ReadOnly = true, Width = 80 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "OriginalOrder", HeaderText = "원본정렬순번", ReadOnly = true, Width = 120 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Interval", HeaderText = "간격", ReadOnly = true, Width = 50 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "StartPosition", HeaderText = "시작위치", ReadOnly = true, Width = 80 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "OffsetDescription", HeaderText = "추출위치", ReadOnly = true, Width = 80 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "DistrictName", HeaderText = "선거구명", ReadOnly = true, Width = 120 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "EupMyeonDong", HeaderText = "읍면동", ReadOnly = true, Width = 120 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "PollingPlaceNo", HeaderText = "투표구", ReadOnly = true, Width = 60 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "EligibleVoterCount", HeaderText = "유권자수", ReadOnly = true, Width = 80 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "VoteCount", HeaderText = "투표인수", ReadOnly = true, Width = 80 }); + _gridResult.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "SortValue", HeaderText = "정렬값", ReadOnly = true, Width = 60 }); + } + + private void ApplyVerificationHeaders() + { + List names = (_candidateNames ?? new List()).ToList(); + while (names.Count < 3) + { + names.Add("후보" + (names.Count + 1)); + } + + if (_gridVerification.Columns.Count >= 11) + { + _gridVerification.Columns[1].HeaderText = "추출" + Environment.NewLine + names[0]; + _gridVerification.Columns[2].HeaderText = "추출" + Environment.NewLine + names[1]; + _gridVerification.Columns[3].HeaderText = "추출" + Environment.NewLine + names[2]; + _gridVerification.Columns[4].HeaderText = "실제" + Environment.NewLine + names[0]; + _gridVerification.Columns[5].HeaderText = "실제" + Environment.NewLine + names[1]; + _gridVerification.Columns[6].HeaderText = "실제" + Environment.NewLine + names[2]; + } + } + } +} diff --git a/Keps.WinForms/Forms/RealExtractionForm.resx b/Keps.WinForms/Forms/RealExtractionForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Keps.WinForms/Forms/RealExtractionForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Keps.WinForms/Infrastructure/DesignTimeHelper.cs b/Keps.WinForms/Infrastructure/DesignTimeHelper.cs new file mode 100644 index 0000000..7e326d1 --- /dev/null +++ b/Keps.WinForms/Infrastructure/DesignTimeHelper.cs @@ -0,0 +1,33 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Windows.Forms; + +namespace Keps.WinForms.Infrastructure +{ + internal static class DesignTimeHelper + { + /// + /// 현재 실행 컨텍스트가 디자이너(디자인 타임)인지 여부를 판단합니다. + /// WinForms 디자이너나 XAML 디자이너 프로세스에서 실행 중이면 true를 반환합니다. + /// + /// 디자인 모드를 추가로 판별할 대상 컨트롤. null이면 프로세스 이름만으로 판별합니다. + /// 디자인 타임이면 true, 런타임이면 false. + public static bool IsDesignMode(Control control = null) + { + if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) + { + return true; + } + + if (control != null && control.Site != null && control.Site.DesignMode) + { + return true; + } + + string processName = Process.GetCurrentProcess().ProcessName; + return string.Equals(processName, "devenv", StringComparison.OrdinalIgnoreCase) + || string.Equals(processName, "XDesProc", StringComparison.OrdinalIgnoreCase); + } + } +} diff --git a/Keps.WinForms/Infrastructure/ExcelEpplusReader.cs b/Keps.WinForms/Infrastructure/ExcelEpplusReader.cs new file mode 100644 index 0000000..563bfc4 --- /dev/null +++ b/Keps.WinForms/Infrastructure/ExcelEpplusReader.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.IO; +using OfficeOpenXml; + +namespace Keps.WinForms.Infrastructure +{ + public sealed class ExcelEpplusReader : IDisposable + { + private ExcelPackage _package; + + /// + /// 지정된 경로의 Excel 파일(.xlsx/.xlsm)을 열고 내부 패키지를 초기화합니다. + /// + /// 읽어들일 Excel 파일 경로. + /// 파일이 존재하지 않을 때 발생합니다. + /// 지원하지 않는 확장자일 때 발생합니다. + public void Open(string path) + { + if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) + { + throw new FileNotFoundException("Excel 파일을 찾을 수 없습니다.", path); + } + + string extension = Path.GetExtension(path); + if (!string.Equals(extension, ".xlsx", StringComparison.OrdinalIgnoreCase) && + !string.Equals(extension, ".xlsm", StringComparison.OrdinalIgnoreCase)) + { + throw new NotSupportedException( + "EPPlus 4.5.3.3은 .xlsx/.xlsm만 직접 지원합니다. 입력 파일을 .xlsx로 변환한 뒤 다시 시도하세요."); + } + + _package = new ExcelPackage(new FileInfo(path)); + } + + /// + /// 현재 열려 있는 Excel 패키지의 모든 워크시트를 순회 가능한 형태로 반환합니다. + /// + /// 열거 시퀀스. + /// Open이 선행되지 않은 경우 발생합니다. + public IEnumerable ReadSheets() + { + if (_package == null) + { + throw new InvalidOperationException("먼저 Open을 호출해야 합니다."); + } + + foreach (ExcelWorksheet worksheet in _package.Workbook.Worksheets) + { + if (worksheet == null) + { + continue; + } + + yield return new ExcelSheet(worksheet); + } + } + + /// + /// 내부 Excel 패키지 리소스를 해제합니다. + /// + public void Dispose() + { + if (_package != null) + { + _package.Dispose(); + _package = null; + } + } + } + + public sealed class ExcelSheet + { + private readonly ExcelWorksheet _worksheet; + + /// + /// EPPlus의 를 래핑하는 시트를 생성합니다. + /// + /// 원본 워크시트 인스턴스. + public ExcelSheet(ExcelWorksheet worksheet) + { + _worksheet = worksheet; + } + + public string Name + { + get { return _worksheet.Name; } + } + + /// + /// 지정한 행/열 위치의 셀 값을 반환합니다. 범위를 벗어나면 null을 반환합니다. + /// + /// 1부터 시작하는 행 번호. + /// 1부터 시작하는 열 번호. + /// 셀 값 또는 범위 밖일 경우 null. + public object GetValue(int row, int column) + { + if (_worksheet.Dimension == null) + { + return null; + } + + if (row < 1 || column < 1) + { + return null; + } + + if (row > _worksheet.Dimension.End.Row || column > _worksheet.Dimension.End.Column) + { + return null; + } + + return _worksheet.Cells[row, column].Value; + } + + /// + /// 첫 번째 행(헤더 행)에서 주어진 헤더 텍스트와 일치하는 열의 인덱스를 찾습니다. + /// + /// 찾을 헤더 텍스트. + /// 검색을 수행할 최대 열 번호(1 기반). + /// 일치하는 열 번호(1 기반). 찾지 못하면 -1. + public int FindHeaderColumn(string header, int maxColumn) + { + if (_worksheet.Dimension == null || string.IsNullOrWhiteSpace(header)) + { + return -1; + } + + int endColumn = Math.Min(maxColumn, _worksheet.Dimension.End.Column); + for (int column = 1; column <= endColumn; column++) + { + object rawValue = _worksheet.Cells[1, column].Value; + string value = rawValue == null ? string.Empty : Convert.ToString(rawValue).Trim(); + if (string.Equals(value, header, StringComparison.OrdinalIgnoreCase)) + { + return column; + } + } + + return -1; + } + } +} diff --git a/Keps.WinForms/Infrastructure/JsonHelper.cs b/Keps.WinForms/Infrastructure/JsonHelper.cs new file mode 100644 index 0000000..8b7c2a4 --- /dev/null +++ b/Keps.WinForms/Infrastructure/JsonHelper.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json; + +namespace Keps.WinForms.Infrastructure +{ + public static class JsonHelper + { + /// + /// 문자열 사전(IDictionary<string, string>)을 JSON 문자열로 직렬화합니다. + /// + /// 직렬화할 키-값 쌍 컬렉션. null이면 빈 사전으로 간주합니다. + /// JSON 형식의 문자열. + public static string Serialize(IDictionary values) + { + return JsonConvert.SerializeObject(values ?? new Dictionary()); + } + + /// + /// JSON 문자열을 문자열 사전(Dictionary<string, string>)으로 파싱합니다. + /// + /// 입력 JSON 문자열. null/공백이면 빈 사전을 반환합니다. + /// 파싱된 문자열 사전. 파싱 실패 시 빈 사전. + public static Dictionary ParseStringMap(string json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return new Dictionary(); + } + + return JsonConvert.DeserializeObject>(json) + ?? new Dictionary(); + } + + /// + /// JSON 문자열을 decimal 값의 사전(Dictionary<string, decimal>)으로 파싱합니다. + /// 내부적으로 문자열 사전을 먼저 파싱한 뒤, 각 값을 decimal로 변환합니다. + /// + /// 입력 JSON 문자열. + /// 키는 문자열, 값은 decimal인 사전. 숫자 변환 실패 시 해당 값은 0m으로 설정됩니다. + public static Dictionary ParseDecimalMap(string json) + { + Dictionary raw = ParseStringMap(json); + Dictionary result = new Dictionary(); + + foreach (KeyValuePair pair in raw) + { + decimal value; + if (!decimal.TryParse(pair.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) + { + value = 0m; + } + + result[pair.Key] = value; + } + + return result; + } + } +} diff --git a/Keps.WinForms/Infrastructure/LegacyConnectionResolver.cs b/Keps.WinForms/Infrastructure/LegacyConnectionResolver.cs new file mode 100644 index 0000000..10f4f73 --- /dev/null +++ b/Keps.WinForms/Infrastructure/LegacyConnectionResolver.cs @@ -0,0 +1,146 @@ +using System; +using System.Configuration; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +namespace Keps.WinForms.Infrastructure +{ + public static class LegacyConnectionResolver + { + /// + /// App.config 및 레거시 VB6 소스에서 DB 연결 정보를 해석하여 반환합니다. + /// 필수 항목이 누락된 경우 예외를 발생시킵니다. + /// + /// 해석된 인스턴스. + /// 연결 정보를 완성할 수 없을 때 발생합니다. + public static LegacyConnectionSettings Resolve() + { + LegacyConnectionSettings settings = new LegacyConnectionSettings + { + Server = GetAppSetting("DbServer"), + Database = GetAppSetting("DbName", "keps"), + UserId = GetAppSetting("DbUser"), + Password = GetAppSetting("DbPassword") + }; + + if (!settings.IsComplete()) + { + throw new InvalidOperationException( + "DB 연결 정보를 찾지 못했습니다.\r\n" + + "1) App.config의 LegacySourceFolder에 원본 VB6 소스 폴더를 지정하거나\r\n" + + "2) DbServer/DbName/DbUser/DbPassword를 직접 입력하세요."); + } + + return settings; + } + + /// + /// App.config의 LegacySourceFolder에 지정된 VB6 원본 폴더에서 연결 정보를 추출하려 시도합니다. + /// + /// 완전한 연결 정보가 추출되면 해당 설정, 아니면 null. + private static LegacyConnectionSettings TryFromLegacySourceFolder() + { + string folder = GetAppSetting("LegacySourceFolder"); + if (string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder)) + { + return null; + } + + string[] basFiles = Directory + .GetFiles(folder, "*.bas", SearchOption.AllDirectories) + .Where(path => + string.Equals(Path.GetFileName(path), "kepsmd.bas", StringComparison.OrdinalIgnoreCase) + || string.Equals(Path.GetFileName(path), "catisvmd.bas", StringComparison.OrdinalIgnoreCase)) + .ToArray(); + + foreach (string path in basFiles) + { + string source = File.ReadAllText(path); + LegacyConnectionSettings settings = ParseFromLegacyBas(source); + if (settings != null && settings.IsComplete()) + { + return settings; + } + } + + return null; + } + + /// + /// VB6 모듈 소스(.bas) 문자열에서 연결 문자열 구성 요소를 정규식으로 추출합니다. + /// + /// VB6 원본 소스 코드 텍스트. + /// + /// 추출된 값으로 구성된 . + /// 필수 항목을 충족하지 못하면 null. + /// + private static LegacyConnectionSettings ParseFromLegacyBas(string source) + { + if (string.IsNullOrWhiteSpace(source)) + { + return null; + } + + string server = MatchValue(source, + @"Server_DB_ip\s*=\s*""([^""]+)""", + @"Data Source=([^;""\r\n]+)", + @"Server=([^;""\r\n]+)"); + + string database = MatchValue(source, + @"Initial Catalog=([^;""\r\n]+)", + @"Database=([^;""\r\n]+)", + @"Db_Name\s*=\s*""([^""]+)"""); + + string userId = MatchValue(source, + @"User ID=([^;""\r\n]+)", + @"UID=([^;""\r\n]+)"); + + string password = MatchValue(source, + @"Password=([^;""\r\n]+)", + @"PWD=([^;""\r\n]+)"); + + LegacyConnectionSettings settings = new LegacyConnectionSettings + { + Server = server, + Database = string.IsNullOrWhiteSpace(database) ? "keps" : database, + UserId = userId, + Password = password + }; + + return settings.IsComplete() ? settings : null; + } + + /// + /// 주어진 여러 정규식 패턴을 순서대로 적용하여 첫 번째로 매칭되는 그룹 값을 반환합니다. + /// + /// 검색할 원본 문자열. + /// 적용할 정규식 패턴 목록. 각 패턴은 그룹 1에 원하는 값을 캡처해야 합니다. + /// 첫 매칭의 그룹 1 값. 매칭이 없으면 null. + private static string MatchValue(string source, params string[] patterns) + { + foreach (string pattern in patterns) + { + Match match = Regex.Match(source, pattern, RegexOptions.IgnoreCase); + if (match.Success) + { + return match.Groups[1].Value.Trim(); + } + } + + return null; + } + + /// + /// App.config의 AppSettings에서 키 값을 읽고, 비어있으면 기본값을 반환합니다. + /// + /// 설정 키 이름. + /// 키가 없거나 값이 비어있을 때 사용할 기본값. + /// 설정값 또는 기본값. + private static string GetAppSetting(string key, string defaultValue = null) + { + string value = ConfigurationManager.AppSettings[key]; + return string.IsNullOrWhiteSpace(value) ? defaultValue : value; + } + } +} diff --git a/Keps.WinForms/Infrastructure/LegacyConnectionSettings.cs b/Keps.WinForms/Infrastructure/LegacyConnectionSettings.cs new file mode 100644 index 0000000..594bd74 --- /dev/null +++ b/Keps.WinForms/Infrastructure/LegacyConnectionSettings.cs @@ -0,0 +1,25 @@ +namespace Keps.WinForms.Infrastructure +{ + public sealed class LegacyConnectionSettings + { + public string Server { get; set; } + public string Database { get; set; } + public string UserId { get; set; } + public string Password { get; set; } + + /// + /// DB 연결 문자열을 구성하기 위한 필수 항목들이 모두 채워졌는지 확인합니다. + /// + /// + /// Server, Database, UserId, Password가 모두 비어있지 않으면 true, + /// 그 외에는 false. + /// + public bool IsComplete() + { + return !string.IsNullOrWhiteSpace(Server) + && !string.IsNullOrWhiteSpace(Database) + && !string.IsNullOrWhiteSpace(UserId) + && !string.IsNullOrWhiteSpace(Password); + } + } +} diff --git a/Keps.WinForms/Infrastructure/LegacyValueHelper.cs b/Keps.WinForms/Infrastructure/LegacyValueHelper.cs new file mode 100644 index 0000000..6e65930 --- /dev/null +++ b/Keps.WinForms/Infrastructure/LegacyValueHelper.cs @@ -0,0 +1,170 @@ +using System; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace Keps.WinForms.Infrastructure +{ + /// + /// DB에서 로드한 레거시 데이터를 정제하고 타입 변환하는 헬퍼 클래스 + /// + public static class LegacyValueHelper + { + /// + /// 객체 값을 문자열로 변환하면서 null/DBNull 체크 및 공백 제거 + /// + /// 변환할 객체 값. null이거나 DBNull.Value이면 빈 문자열 반환 + /// 정제된 문자열. 양쪽 공백이 제거되고 null은 빈 문자열로 반환 + public static string CleanString(object value) + { + if (value == null || value == DBNull.Value) + { + return string.Empty; + } + + return Convert.ToString(value).Trim(); + } + + /// + /// 객체 값을 정수로 변환 + /// 쉼표 제거, 부동소수점 값은 소수점 버림 처리, 변환 실패시 0 반환 + /// + /// 변환할 객체 값. null이거나 DBNull.Value이면 0 반환 + /// + /// 정수로 변환된 값 + /// 부동소수점은 Math.Truncate로 소수점 이하 버림 처리 + /// 변환 실패시 기본값 0 반환 + /// + public static int ToInt(object value) + { + if (value == null || value == DBNull.Value) + { + return 0; + } + + int result; + // 쉼표를 제거하고 공백을 제거 후 정수 파싱 시도 + string text = Convert.ToString(value).Replace(",", "").Trim(); + if (int.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out result)) + { + return result; + } + + // int 파싱 실패시 decimal로 파싱 후 정수 부분만 취득 + decimal decimalValue; + if (decimal.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out decimalValue)) + { + // Math.Truncate: 소수점 이하 버림 (음수도 0 방향으로 버림) + return Convert.ToInt32(Math.Truncate(decimalValue)); + } + + return 0; + } + + /// + /// 객체 값을 decimal(십진수)로 변환 + /// 쉼표 제거, 변환 실패시 0 반환 + /// + /// 변환할 객체 값. null이거나 DBNull.Value이면 0m 반환 + /// decimal으로 변환된 값. 변환 실패시 기본값 0m 반환 + public static decimal ToDecimal(object value) + { + if (value == null || value == DBNull.Value) + { + return 0m; + } + + decimal result; + // 쉼표를 제거하고 공백을 제거 후 decimal 파싱 시도 + string text = Convert.ToString(value).Replace(",", "").Trim(); + if (decimal.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out result)) + { + return result; + } + + return 0m; + } + + /// + /// 선거구명(District)에서 지역명(Area)을 추출 + /// "[지역명_세부구분]" 또는 "지역명.세부구분" 형태에서 지역명만 추출 + /// + /// + /// 선거구명 문자열 + /// 형식 예시: "[강원_강릉시]", "강원.강릉시", "강원_강릉시" 등 + /// null이거나 공백이면 빈 문자열 반환 + /// + /// + /// 추출된 지역명 + /// 양쪽 대괄호 제거 후 언더스코어(_)나 점(.)을 기준으로 앞부분만 반환 + /// 구분자가 없으면 전체 정규화된 문자열 반환 + /// + public static string DeriveAreaFromDistrict(string districtName) + { + if (string.IsNullOrWhiteSpace(districtName)) + { + return string.Empty; + } + + // 양쪽의 대괄호 제거 및 공백 제거 + string normalized = districtName.Trim().Trim('[', ']'); + + // 언더스코어(_) 기준으로 앞부분 추출 + int underscore = normalized.IndexOf('_'); + if (underscore > 0) + { + return normalized.Substring(0, underscore); + } + + // 점(.) 기준으로 앞부분 추출 + int dot = normalized.IndexOf('.'); + if (dot > 0) + { + return normalized.Substring(0, dot); + } + + // 구분자가 없으면 정규화된 전체 문자열 반환 + return normalized; + } + + /// + /// 투표구명(PollingPlaceName)에서 투표구 번호를 추출 + /// "제5투표소", "5 투표소", "제 5 투표" 등의 형식에서 숫자만 추출 + /// + /// + /// 투표구명 문자열 + /// 형식 예시: "제1투표소", "제5투표소", "10투표소", "투표소" 등 + /// null이거나 공백이면 "0" 반환 + /// + /// + /// 추출된 투표구 번호 문자열 + /// 정규표현식 "제?\s*(\d+)\s*투"로 매칭된 숫자 부분 반환 + /// 패턴 미매칭시 투표소로 끝나면 "1" 반환 + /// 모두 실패시 "0" 반환 + /// + public static string ExtractPollingPlaceNumber(string pollingPlaceName) + { + if (string.IsNullOrWhiteSpace(pollingPlaceName)) + { + return "0"; + } + + // 정규표현식으로 "제(선택적) + 공백(선택적) + 숫자 + 공백(선택적) + '투'" 패턴 매칭 + // 예: "제1투", "제 5 투", "10투" 등에서 숫자 부분 추출 + Match match = Regex.Match(pollingPlaceName, @"제?\s*(\d+)\s*투"); + if (match.Success) + { + // Groups[1]은 첫 번째 캡처 그룹(괄호 안의 내용) + return match.Groups[1].Value; + } + + // 정규표현식 미매칭시 "투표소"로 끝나면 단일 투표소로 간주하여 "1" 반환 + if (pollingPlaceName.EndsWith("투표소")) + { + return "1"; + } + + // 투표구 번호를 찾을 수 없음 + return "0"; + } + } +} diff --git a/Keps.WinForms/Infrastructure/SqlConnectionFactory.cs b/Keps.WinForms/Infrastructure/SqlConnectionFactory.cs new file mode 100644 index 0000000..30d4294 --- /dev/null +++ b/Keps.WinForms/Infrastructure/SqlConnectionFactory.cs @@ -0,0 +1,47 @@ +using System.Data.SqlClient; + +namespace Keps.WinForms.Infrastructure +{ + public sealed class SqlConnectionFactory + { + private readonly string _connectionString; + + /// + /// 주어진 레거시 DB 연결 설정으로 을 생성하기 위한 팩토리를 초기화합니다. + /// + /// 서버, 데이터베이스, 사용자, 비밀번호 등의 연결 정보. + public SqlConnectionFactory(LegacyConnectionSettings settings) + { + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); + builder.DataSource = settings.Server; + builder.InitialCatalog = settings.Database; + builder.UserID = settings.UserId; + builder.Password = settings.Password; + builder.IntegratedSecurity = false; + builder.ConnectTimeout = 30; + builder.TrustServerCertificate = true; + builder.Encrypt = false; + + _connectionString = builder.ConnectionString; + } + + /// + /// 구성된 연결 문자열로 SQL Server 연결을 열어 반환합니다. + /// + /// 열린 상태의 . + public SqlConnection Open() + { + SqlConnection connection = new SqlConnection(_connectionString); + connection.Open(); + return connection; + } + + /// + /// 내부에서 사용되는 연결 문자열을 반환합니다. + /// + public string ConnectionString + { + get { return _connectionString; } + } + } +} diff --git a/Keps.WinForms/Keps.WinForms.csproj b/Keps.WinForms/Keps.WinForms.csproj new file mode 100644 index 0000000..35b9fc4 --- /dev/null +++ b/Keps.WinForms/Keps.WinForms.csproj @@ -0,0 +1,21 @@ + + + WinExe + net48 + true + latest + disable + Keps.WinForms + Keps.WinForms + true + + + + + + + + + + + diff --git a/Keps.WinForms/Models/AdjustmentRow.cs b/Keps.WinForms/Models/AdjustmentRow.cs new file mode 100644 index 0000000..021e884 --- /dev/null +++ b/Keps.WinForms/Models/AdjustmentRow.cs @@ -0,0 +1,21 @@ +namespace Keps.WinForms.Models +{ + /// + /// 추출 표본 보정 내역을 표현하는 행 모델입니다. + /// + public sealed class AdjustmentRow + { + /// + /// 해당 표본이 속한 군집 번호. + /// + public int ClusterNo { get; set; } + /// + /// 원래 추출 순번(Extract ID). + /// + public int ExtractId { get; set; } + /// + /// 보정된 순번(있을 경우). null이면 보정 없음. + /// + public int? AdjustId { get; set; } + } +} diff --git a/Keps.WinForms/Models/CandidateOption.cs b/Keps.WinForms/Models/CandidateOption.cs new file mode 100644 index 0000000..31ed4d8 --- /dev/null +++ b/Keps.WinForms/Models/CandidateOption.cs @@ -0,0 +1,17 @@ +namespace Keps.WinForms.Models +{ + /// + /// 후보자 선택을 위한 표시 이름과 내부 키를 보관하는 옵션 항목입니다. + /// + public sealed class CandidateOption + { + /// + /// UI에 표시할 후보자 이름(예: 홍길동(1)). + /// + public string DisplayName { get; set; } + /// + /// 내부 조회/정렬에 사용되는 키(예: cand_ratio_1). + /// + public string Key { get; set; } + } +} diff --git a/Keps.WinForms/Models/ClusterSummaryRow.cs b/Keps.WinForms/Models/ClusterSummaryRow.cs new file mode 100644 index 0000000..4273228 --- /dev/null +++ b/Keps.WinForms/Models/ClusterSummaryRow.cs @@ -0,0 +1,29 @@ +namespace Keps.WinForms.Models +{ + /// + /// 군집(층화) 단위 요약 정보를 담는 모델입니다. + /// + public sealed class ClusterSummaryRow + { + /// + /// 군집 번호(1..N). + /// + public int ClusterNo { get; set; } + /// + /// 표시용 라벨(예: "1 층"). + /// + public string ClusterLabel { get; set; } + /// + /// 해당 군집 내 전체 투표구 수. + /// + public int PollingPlaceCount { get; set; } + /// + /// 표본 할당 비율(0~1). + /// + public decimal Ratio { get; set; } + /// + /// 최종 할당된 표본 수. + /// + public int SampleCount { get; set; } + } +} diff --git a/Keps.WinForms/Models/ExtractionRow.cs b/Keps.WinForms/Models/ExtractionRow.cs new file mode 100644 index 0000000..19c0237 --- /dev/null +++ b/Keps.WinForms/Models/ExtractionRow.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; + +namespace Keps.WinForms.Models +{ + /// + /// 실 추출/모집단 표의 각 행(투표구)을 표현하는 모델입니다. + /// + public sealed class ExtractionRow + { + /// 군집 번호. + public int ClusterNo { get; set; } + /// 해당 군집 내 추출 순번. + public int ClusterOrder { get; set; } + /// 정렬 후 모집단에서의 원래 순번. + public int OriginalOrder { get; set; } + /// 등간격 추출 간격. + public int Interval { get; set; } + /// 등간격 추출 시작 위치. + public int StartPosition { get; set; } + /// 오프셋(시작위치) 설명. + public string OffsetDescription { get; set; } + /// 시도명. + public string AreaName { get; set; } + /// 선거구명. + public string DistrictName { get; set; } + /// 시군구. + public string SiGunGu { get; set; } + /// 읍면동. + public string EupMyeonDong { get; set; } + /// 투표구 표시명(예: 읍면동 + " 제N투"). + public string PollingPlaceName { get; set; } + /// 투표구 번호(예: 제1투). + public string PollingPlaceNo { get; set; } + /// 유권자수(투표권자 수 추정/원자료 컬럼). + public int EligibleVoterCount { get; set; } + /// 선거인수. + public int ElectorateCount { get; set; } + /// 투표인수. + public int VoteCount { get; set; } + /// 후보자별 득표수 합계. + public int TotalCandidateVoteCount { get; set; } + /// 중복 투표소 여부 플래그. + public string DuplicateFlag { get; set; } + /// 투표소 건물명. + public string BuildingName { get; set; } + /// 주소(첫 줄). + public string Address1 { get; set; } + /// 비고/기타 메모. + public string Note { get; set; } + /// 정렬 기준 값(투표인수 또는 후보 득표율 등). + public decimal SortValue { get; set; } + /// 자동 추출에 의해 선택되었는지 여부. + public bool IsAutoSelected { get; set; } + /// 사용자 보정 선택 반영 여부. + public bool IsAdjustedSelected { get; set; } + /// 후보자별 득표수 맵. + public Dictionary CandidateVotes { get; set; } + /// 후보자별 득표율(%) 맵. + public Dictionary CandidateRatios { get; set; } + } +} diff --git a/Keps.WinForms/Models/ImportMode.cs b/Keps.WinForms/Models/ImportMode.cs new file mode 100644 index 0000000..a82c1bd --- /dev/null +++ b/Keps.WinForms/Models/ImportMode.cs @@ -0,0 +1,13 @@ +namespace Keps.WinForms.Models +{ + /// + /// Excel 적재 모드를 나타냅니다. + /// + public enum ImportMode + { + /// 실제 데이터(poll_data) 적재. + Real, + /// 시뮬레이션 데이터 적재(현재 미지원). + Simulation + } +} diff --git a/Keps.WinForms/Models/ImportProgress.cs b/Keps.WinForms/Models/ImportProgress.cs new file mode 100644 index 0000000..ea5cb5d --- /dev/null +++ b/Keps.WinForms/Models/ImportProgress.cs @@ -0,0 +1,28 @@ +namespace Keps.WinForms.Models +{ + /// + /// Excel 적재 과정에서의 진행 상태를 나타냅니다. + /// + public sealed class ImportProgress + { + /// + /// 진행 상태를 초기화합니다. + /// + /// 진행률(0~100). + /// 사용자에게 표시할 메시지. + public ImportProgress(int percent, string message) + { + Percent = percent; + Message = message; + } + + /// + /// 진행률(0~100). + /// + public int Percent { get; private set; } + /// + /// 현재 단계 설명 메시지. + /// + public string Message { get; private set; } + } +} diff --git a/Keps.WinForms/Models/PollingPlaceRecord.cs b/Keps.WinForms/Models/PollingPlaceRecord.cs new file mode 100644 index 0000000..1b5ed8a --- /dev/null +++ b/Keps.WinForms/Models/PollingPlaceRecord.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; + +namespace Keps.WinForms.Models +{ + /// + /// poll_data 원시 데이터 한 행(투표구 단위)을 표현하는 모델입니다. + /// + public sealed class PollingPlaceRecord + { + /// 선거명 또는 연월. + public string ElectionName { get; set; } + /// 시도명. + public string AreaName { get; set; } + /// 선거구명. + public string DistrictName { get; set; } + /// 시군구. + public string SiGunGu { get; set; } + /// 읍면동. + public string EupMyeonDong { get; set; } + /// 투표구 표시명(예: 읍면동 + " 제N투"). + public string PollingPlaceName { get; set; } + /// 투표구 번호. + public string PollingPlaceNo { get; set; } + /// 계산된 군집 값. + public int ClusterValue { get; set; } + /// 유권자수. + public int EligibleVoterCount { get; set; } + /// 선거인수. + public int ElectorateCount { get; set; } + /// 투표인수. + public int VoteCount { get; set; } + /// 후보자별 득표수 합계. + public int TotalCandidateVoteCount { get; set; } + /// 중복 투표소 여부 플래그. + public string DuplicateFlag { get; set; } + /// 투표소 건물명. + public string BuildingName { get; set; } + /// 주소(첫 줄). + public string Address1 { get; set; } + /// 관할구역/세부지역. + public string AreaDetail { get; set; } + /// 비고/기타 메모. + public string Note { get; set; } + /// 후보자별 득표수. + public Dictionary CandidateVotes { get; set; } + /// 후보자별 득표율(%) + public Dictionary CandidateRatios { get; set; } + + /// + /// 지정된 정렬 키에 대한 값을 반환합니다. + /// + /// 정렬 키(예: "투표인수" 또는 cand_ratio_*). + /// 정렬용 수치 값. + public decimal GetSortValue(string sortKey) + { + if (string.IsNullOrWhiteSpace(sortKey) || sortKey == "투표인수") + { + return VoteCount; + } + + if (CandidateRatios != null && CandidateRatios.ContainsKey(sortKey)) + { + return CandidateRatios[sortKey]; + } + + return 0m; + } + } +} diff --git a/Keps.WinForms/Models/RealExtractionResult.cs b/Keps.WinForms/Models/RealExtractionResult.cs new file mode 100644 index 0000000..c60f4e2 --- /dev/null +++ b/Keps.WinForms/Models/RealExtractionResult.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; + +namespace Keps.WinForms.Models +{ + /// + /// 실 추출 실행 결과 전체를 포함하는 DTO입니다. + /// + public sealed class RealExtractionResult + { + /// 후보자 표시 이름 목록. + public List CandidateNames { get; set; } + /// 후보자 득표수 조회 키 목록. + public List CandidateVoteKeys { get; set; } + /// 후보자 득표율 조회 키 목록. + public List CandidateRatioKeys { get; set; } + /// 최종 추출 표본 행 목록. + public List ExtractedRows { get; set; } + /// 모집단(전체) 행 목록. + public List PopulationRows { get; set; } + /// 보정 정보 목록. + public List AdjustmentRows { get; set; } + /// 검증(요약) 행 목록. + public List VerificationRows { get; set; } + /// 군집 최대값. + public int ClusterMax { get; set; } + /// 전체 표본 수. + public int TotalSampleCount { get; set; } + /// 자동 할당 여부. + public bool IsAutoAllocation { get; set; } + /// 정렬 기준 표시 이름. + public string SortDisplayName { get; set; } + /// 정렬 내림차순 여부. + public bool SortDescending { get; set; } + /// 오프셋 설명. + public string OffsetDescription { get; set; } + } +} diff --git a/Keps.WinForms/Models/RealScenarioContext.cs b/Keps.WinForms/Models/RealScenarioContext.cs new file mode 100644 index 0000000..b801891 --- /dev/null +++ b/Keps.WinForms/Models/RealScenarioContext.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace Keps.WinForms.Models +{ + /// + /// 실 추출 화면에 필요한 초기 데이터 컨텍스트입니다. + /// + public sealed class RealScenarioContext + { + /// 자동 할당용 군집 행 목록. + public List AutoRows { get; set; } + /// 수동 할당용 군집 행 목록. + public List ManualRows { get; set; } + /// 정렬 기준 선택 옵션 목록. + public List SortOptions { get; set; } + } +} diff --git a/Keps.WinForms/Models/VerificationSummaryRow.cs b/Keps.WinForms/Models/VerificationSummaryRow.cs new file mode 100644 index 0000000..5324404 --- /dev/null +++ b/Keps.WinForms/Models/VerificationSummaryRow.cs @@ -0,0 +1,36 @@ +namespace Keps.WinForms.Models +{ + /// + /// 검증 요약(가중 오차/군집 내 오차 등)을 담는 행 모델입니다. + /// + public sealed class VerificationSummaryRow + { + public string RowLabel { get; set; } + /// 해당 행(군집 또는 전체)의 비율. + public decimal ClusterRatio { get; set; } + /// 해당 행의 표본 수. + public int SampleCount { get; set; } + + /// 표본에서 계산된 후보1/2/3의 비율. + public decimal Extracted1 { get; set; } + public decimal Extracted2 { get; set; } + public decimal Extracted3 { get; set; } + + /// 실제(모집단) 후보1/2/3의 비율. + public decimal Actual1 { get; set; } + public decimal Actual2 { get; set; } + public decimal Actual3 { get; set; } + + /// 가중 오차(후보1/2/3 및 합). + public decimal WeightedError1 { get; set; } + public decimal WeightedError2 { get; set; } + public decimal WeightedError3 { get; set; } + public decimal WeightedErrorSum { get; set; } + + /// 군집 내 오차(후보1/2/3 및 합). + public decimal InClusterError1 { get; set; } + public decimal InClusterError2 { get; set; } + public decimal InClusterError3 { get; set; } + public decimal InClusterErrorSum { get; set; } + } +} diff --git a/Keps.WinForms/Program.cs b/Keps.WinForms/Program.cs new file mode 100644 index 0000000..e164cac --- /dev/null +++ b/Keps.WinForms/Program.cs @@ -0,0 +1,25 @@ +using System; +using System.Windows.Forms; +using Keps.WinForms.Forms; +using Keps.WinForms.Infrastructure; + +namespace Keps.WinForms +{ + internal static class Program + { + [STAThread] + private static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + + LegacyConnectionSettings settings = LegacyConnectionResolver.Resolve(); + SqlConnectionFactory connectionFactory = new SqlConnectionFactory(settings); + + MainMdiForm mainForm = new MainMdiForm(); + mainForm.InitializeRuntime(connectionFactory); + + Application.Run(mainForm); + } + } +} diff --git a/Keps.WinForms/Services/AppVersionService.cs b/Keps.WinForms/Services/AppVersionService.cs new file mode 100644 index 0000000..3c46a51 --- /dev/null +++ b/Keps.WinForms/Services/AppVersionService.cs @@ -0,0 +1,37 @@ +using System; +using System.Data.SqlClient; +using Keps.WinForms.Infrastructure; + +namespace Keps.WinForms.Services +{ + /// + /// 데이터베이스에 저장된 현재 프로그램 버전을 조회하는 서비스입니다. + /// + public sealed class AppVersionService + { + private readonly SqlConnectionFactory _connectionFactory; + + /// + /// 애플리케이션 버전 조회 서비스를 생성합니다. + /// + /// DB 연결을 생성하는 팩토리. + public AppVersionService(SqlConnectionFactory connectionFactory) + { + _connectionFactory = connectionFactory; + } + + /// + /// 데이터베이스의 정보 테이블에서 현재 프로그램 버전을 조회합니다. + /// + /// 버전 문자열. 조회 결과가 없으면 빈 문자열. + public string GetCurrentVersion() + { + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(LegacySqlCatalog.ProgramVersion, connection)) + { + object value = command.ExecuteScalar(); + return value == null ? string.Empty : Convert.ToString(value); + } + } + } +} diff --git a/Keps.WinForms/Services/ClusterMaintenanceService.cs b/Keps.WinForms/Services/ClusterMaintenanceService.cs new file mode 100644 index 0000000..a6565d8 --- /dev/null +++ b/Keps.WinForms/Services/ClusterMaintenanceService.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using Keps.WinForms.Infrastructure; + +namespace Keps.WinForms.Services +{ + /// + /// 군집(층화) 관련 중간 테이블 생성 및 poll_data 반영 작업을 수행하는 유지보수용 서비스입니다. + /// + public sealed class ClusterMaintenanceService + { + private readonly SqlConnectionFactory _connectionFactory; + + /// + /// 군집 관련 유지보수 작업을 수행하는 서비스를 생성합니다. + /// + /// DB 연결을 제공하는 팩토리. + public ClusterMaintenanceService(SqlConnectionFactory connectionFactory) + { + _connectionFactory = connectionFactory; + } + + /// + /// 주어진 선거 연도에 대해 군집 관련 중간 테이블을 재구축하고 poll_data에 반영합니다. + /// + /// 선거 연도(예: "201804"). + public void RebuildRealClusters(string electionYear) + { + using (SqlConnection connection = _connectionFactory.Open()) + { + DeleteWorkingTables(connection, electionYear); + InsertDistrictClusterMap(connection, electionYear); + InsertClusterRatios(connection, electionYear); + ResetPollDataClusters(connection, electionYear); + ApplyClusterValuesToPollData(connection, electionYear); + } + } + + /// + /// 대상 선거 연도의 작업용 테이블 데이터를 초기화합니다. + /// + /// 열린 DB 연결. + /// 선거 연도. + private void DeleteWorkingTables(SqlConnection connection, string electionYear) + { + Execute(connection, "DELETE FROM [시군구별유권자수와군집] WHERE ele_ym = @eleYm", electionYear); + Execute(connection, "DELETE FROM [군집별비율] WHERE ele_ym = @eleYm", electionYear); + } + + /// + /// 시군구별 유권자수와 군집 정보를 계산하여 매핑 테이블에 적재합니다. + /// + /// 열린 DB 연결. + /// 선거 연도. + private void InsertDistrictClusterMap(SqlConnection connection, string electionYear) + { + string sql = @" + INSERT INTO [시군구별유권자수와군집] + ( + ele_ym, 시도명, 시군구, + 군집1개, 군집2개, 군집3개, 군집4개, 군집5개, 군집6개, 군집7개, + 투표자수_etc1, 투표자수_etc2, 투표자수_etc3, 투표자수_etc4, 투표자수_etc5 + ) + SELECT + @eleYm AS ele_ym, + B.시도명, + B.선거구명 AS 시군구, + 1 AS 군집1개, + CASE WHEN A.층 = 2 THEN RANK() OVER(PARTITION BY B.시도명 ORDER BY B.선거구명) ELSE 0 END AS 군집2개, + CASE WHEN A.층 = 3 THEN RANK() OVER(PARTITION BY B.시도명 ORDER BY B.선거구명) ELSE 0 END AS 군집3개, + CASE WHEN A.층 = 4 THEN RANK() OVER(PARTITION BY B.시도명 ORDER BY B.선거구명) ELSE 0 END AS 군집4개, + CASE WHEN A.층 = 5 THEN RANK() OVER(PARTITION BY B.시도명 ORDER BY B.선거구명) ELSE 0 END AS 군집5개, + CASE WHEN A.층 = 6 THEN RANK() OVER(PARTITION BY B.시도명 ORDER BY B.선거구명) ELSE 0 END AS 군집6개, + CASE WHEN A.층 = 7 THEN RANK() OVER(PARTITION BY B.시도명 ORDER BY B.선거구명) ELSE 0 END AS 군집7개, + ISNULL((SELECT SUM(후보별득표수계) + FROM poll_data + WHERE ele_ym = @eleYm AND 시도명 = B.시도명 AND 선거구명 = B.선거구명), 0) AS 투표자수_etc1, + 0, 0, 0, 0 + FROM + ( + SELECT 시도명, COUNT(*) AS 층 + FROM + ( + SELECT 시도명, 선거구명 + FROM poll_data + WHERE ele_ym = @eleYm + GROUP BY 시도명, 선거구명 + ) T + GROUP BY 시도명 + ) A + LEFT JOIN + ( + SELECT 시도명, 선거구명 + FROM poll_data + WHERE ele_ym = @eleYm + GROUP BY 시도명, 선거구명 + ) B + ON A.시도명 = B.시도명"; + Execute(connection, sql, electionYear); + } + + /// + /// 선거명/시도명별로 군집 비율(득표수 기반)을 계산하여 적재합니다. + /// + /// 열린 DB 연결. + /// 선거 연도. + private void InsertClusterRatios(SqlConnection connection, string electionYear) + { + string sql = @" + INSERT INTO [군집별비율] + (ele_ym, 선거명, 시도명, 군집최대값, 군집, 비율) + SELECT + @eleYm AS ele_ym, + A.선거명, + B.시도명, + A.층 AS 군집최대값, + RANK() OVER(PARTITION BY B.선거명, B.시도명 ORDER BY B.선거구명) AS 군집, + CAST(ROUND( + CAST(ISNULL((SELECT SUM(후보별득표수계) + FROM poll_data + WHERE ele_ym = @eleYm AND 선거명 = B.선거명 AND 시도명 = B.시도명 AND 선거구명 = B.선거구명), 0) AS NUMERIC(10,3)) + / + NULLIF(CAST(ISNULL((SELECT SUM(후보별득표수계) + FROM poll_data + WHERE ele_ym = @eleYm AND 선거명 = B.선거명 AND 시도명 = B.시도명), 0) AS NUMERIC(10,3)), 0), + 5 + ) AS NUMERIC(10,5)) AS 비율 + FROM + ( + SELECT 선거명, 시도명, COUNT(*) AS 층 + FROM + ( + SELECT 선거명, 시도명, 선거구명 + FROM poll_data + WHERE ele_ym = @eleYm + GROUP BY 선거명, 시도명, 선거구명 + ) T + GROUP BY 선거명, 시도명 + ) A + LEFT JOIN + ( + SELECT 선거명, 선거구명, 시도명 + FROM poll_data + WHERE ele_ym = @eleYm + GROUP BY 선거명, 시도명, 선거구명 + ) B + ON A.선거명 = B.선거명 AND A.시도명 = B.시도명 + UNION ALL + SELECT + @eleYm, + 선거명, + 시도명, + 1, + 1, + CAST(1.00000 AS NUMERIC(10,5)) + FROM poll_data + WHERE ele_ym = @eleYm + GROUP BY 선거명, 시도명, 선거구명"; + Execute(connection, sql, electionYear); + } + + /// + /// poll_data 테이블의 군집 관련 컬럼 값을 초기화합니다. + /// + /// 열린 DB 연결. + /// 선거 연도. + private void ResetPollDataClusters(SqlConnection connection, string electionYear) + { + string sql = @" + UPDATE poll_data + SET + 군집1개 = 0, + 군집2개 = 0, + 군집3개 = 0, + 군집4개 = 0, + 군집5개 = 0, + 군집6개 = 0, + 군집7개 = 0, + 비고 = 1 + WHERE ele_ym = @eleYm"; + Execute(connection, sql, electionYear); + } + + /// + /// 시군구별 군집 값을 poll_data 테이블의 해당 행들에 반영합니다. + /// + /// 열린 DB 연결. + /// 선거 연도. + private void ApplyClusterValuesToPollData(SqlConnection connection, string electionYear) + { + string query = "SELECT 시도명, 시군구, 군집1개, 군집2개, 군집3개, 군집4개, 군집5개, 군집6개, 군집7개 FROM [시군구별유권자수와군집] WHERE ele_ym = @eleYm"; + using (SqlCommand command = new SqlCommand(query, connection)) + { + command.Parameters.AddWithValue("@eleYm", electionYear); + using (SqlDataReader reader = command.ExecuteReader()) + { + List> rows = new List>(); + while (reader.Read()) + { + Dictionary row = new Dictionary(); + row["시도명"] = reader["시도명"]; + row["시군구"] = reader["시군구"]; + row["군집1개"] = reader["군집1개"]; + row["군집2개"] = reader["군집2개"]; + row["군집3개"] = reader["군집3개"]; + row["군집4개"] = reader["군집4개"]; + row["군집5개"] = reader["군집5개"]; + row["군집6개"] = reader["군집6개"]; + row["군집7개"] = reader["군집7개"]; + rows.Add(row); + } + + reader.Close(); + + foreach (Dictionary row in rows) + { + string update = @" + UPDATE poll_data + SET + 군집1개 = @c1, + 군집2개 = @c2, + 군집3개 = @c3, + 군집4개 = @c4, + 군집5개 = @c5, + 군집6개 = @c6, + 군집7개 = @c7 + WHERE ele_ym = @eleYm AND 시도명 = @areaName AND 선거구명 = @districtName"; + + using (SqlCommand updateCommand = new SqlCommand(update, connection)) + { + updateCommand.Parameters.AddWithValue("@eleYm", electionYear); + updateCommand.Parameters.AddWithValue("@areaName", row["시도명"]); + updateCommand.Parameters.AddWithValue("@districtName", row["시군구"]); + updateCommand.Parameters.AddWithValue("@c1", row["군집1개"]); + updateCommand.Parameters.AddWithValue("@c2", row["군집2개"]); + updateCommand.Parameters.AddWithValue("@c3", row["군집3개"]); + updateCommand.Parameters.AddWithValue("@c4", row["군집4개"]); + updateCommand.Parameters.AddWithValue("@c5", row["군집5개"]); + updateCommand.Parameters.AddWithValue("@c6", row["군집6개"]); + updateCommand.Parameters.AddWithValue("@c7", row["군집7개"]); + updateCommand.ExecuteNonQuery(); + } + } + } + } + } + + /// + /// 공통 파라미터(@eleYm)를 바인딩하여 지정된 SQL을 실행합니다. + /// + /// 열린 DB 연결. + /// 실행할 SQL 문. + /// 바인딩할 선거 연도 값. + private void Execute(SqlConnection connection, string sql, string electionYear) + { + using (SqlCommand command = new SqlCommand(sql, connection)) + { + command.Parameters.AddWithValue("@eleYm", electionYear); + command.ExecuteNonQuery(); + } + } + } +} diff --git a/Keps.WinForms/Services/ExcelImportService.cs b/Keps.WinForms/Services/ExcelImportService.cs new file mode 100644 index 0000000..98bdc3b --- /dev/null +++ b/Keps.WinForms/Services/ExcelImportService.cs @@ -0,0 +1,333 @@ +using Keps.WinForms.Infrastructure; +using Keps.WinForms.Models; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; + +namespace Keps.WinForms.Services +{ + /// + /// Excel 파일에서 실데이터를 읽어 DB에 적재하는 서비스입니다. + /// + public sealed class ExcelImportService + { + private readonly SqlConnectionFactory _connectionFactory; + private readonly ClusterMaintenanceService _clusterMaintenanceService; + + /// + /// Excel 적재 서비스 인스턴스를 생성합니다. + /// + /// DB 연결을 제공하는 팩토리. + public ExcelImportService(SqlConnectionFactory connectionFactory) + { + _connectionFactory = connectionFactory; + _clusterMaintenanceService = new ClusterMaintenanceService(connectionFactory); + } + + /// + /// elections 테이블에서 사용 가능한 선거 연월 목록을 조회합니다. + /// + /// 연월 문자열 목록(내림차순). + public List LoadElectionYears() + { + List years = new List(); + + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(LegacySqlCatalog.ElectionYears, connection)) + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + years.Add(Convert.ToString(reader[0])); + } + } + + return years; + } + + /// + /// 지정한 폴더의 Excel 파일(.xlsx/.xlsm)을 읽어 실데이터를 DB에 적재합니다. + /// + /// Excel 파일들이 위치한 폴더 경로. + /// 적재 대상 선거 연월(예: "201804"). + /// 적재 모드(현재 Real만 지원). + /// 진행 상황을 보고받을 프로그레스 리스너. + /// 폴더가 없거나 지원 확장자가 없을 때 발생. + /// 미지원 모드일 때 발생. + public void Import(string folderPath, string electionYear, ImportMode mode, IProgress progress) + { + if (string.IsNullOrWhiteSpace(folderPath) || !Directory.Exists(folderPath)) + { + throw new InvalidOperationException("유효한 폴더를 선택하세요."); + } + + List files = [.. Directory.GetFiles(folderPath, "*.xlsx")]; + + if (files.Count == 0) + { + if (Directory.GetFiles(folderPath, "*.xls").Length > 0) + { + throw new InvalidOperationException("현재 버전은 EPPlus 4.5.3.3 기준으로 작성되어 .xlsx/.xlsm만 지원합니다. 기존 .xls 파일은 .xlsx로 변환 후 다시 시도하세요."); + } + + throw new InvalidOperationException("선택한 폴더에 지원되는 Excel 파일(.xlsx/.xlsm)이 없습니다."); + } + + progress.Report(new ImportProgress(5, "기존 데이터 정리")); + EnsureElectionExists(electionYear); + + if (mode == ImportMode.Real) + { + CleanupReal(electionYear); + } + else + { + throw new NotSupportedException("시뮬레이션 엑셀 적재는 지원하지 않습니다."); + } + + string firstFile = files[0]; + progress.Report(new ImportProgress(10, Path.GetFileName(firstFile) + " 열기")); + + List candidateNames = new List(); + + using (ExcelEpplusReader reader = new ExcelEpplusReader()) + { + reader.Open(firstFile); + List sheets = new List(reader.ReadSheets()); + + for (int sheetIndex = 0; sheetIndex < sheets.Count; sheetIndex++) + { + ExcelSheet sheet = sheets[sheetIndex]; + progress.Report(new ImportProgress(10 + (sheetIndex * 60 / Math.Max(1, sheets.Count)), "시트 처리 중: " + sheet.Name)); + ImportRealSheet(sheet, electionYear, candidateNames); + } + } + + UpsertCandidateNames(electionYear, candidateNames); + + progress.Report(new ImportProgress(80, "군집 테이블 재구성")); + _clusterMaintenanceService.RebuildRealClusters(electionYear); + progress.Report(new ImportProgress(100, "완료")); + } + + /// + /// elections 테이블에 대상 연월이 없으면 1건을 삽입하여 존재를 보장합니다. + /// + /// 선거 연월(예: "201804"). + private void EnsureElectionExists(string electionYear) + { + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand("INSERT INTO elections(ele_ym) SELECT TOP 1 @eleYm WHERE NOT EXISTS (SELECT 1 FROM elections WHERE ele_ym = @eleYm);", connection)) + { + command.Parameters.AddWithValue("@eleYm", electionYear); + command.ExecuteNonQuery(); + } + } + + /// + /// 실데이터 적재 전 기존 poll_data 및 관련 테이블에서 대상 연월의 데이터를 정리합니다. + /// + /// 선거 연월. + private void CleanupReal(string electionYear) + { + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand("DELETE FROM [poll_data] WHERE ele_ym = @eleYm", connection)) + { + command.Parameters.AddWithValue("@eleYm", electionYear); + command.ExecuteNonQuery(); + } + } + + /// + /// 실데이터 Excel 시트 한 개를 파싱하여 poll_data 등 테이블에 적재합니다. + /// + /// EPPlus로 읽은 시트. + /// 선거 연월. + /// 발견된 후보자명 누적 리스트(출력 가변). + private void ImportRealSheet(ExcelSheet sheet, string electionYear, List candidateNames) + { + int voteColumn = sheet.FindHeaderColumn("투표수", 128); + int totalColumn = sheet.FindHeaderColumn("계", 128); + if (voteColumn <= 0 || totalColumn <= 0 || totalColumn <= voteColumn) + { + return; + } + + int candidateStartColumn = voteColumn + 1; + int candidateEndColumn = totalColumn - 1; + if (candidateEndColumn < candidateStartColumn) + { + return; + } + + if (candidateNames.Count == 0) + { + for (int column = candidateStartColumn; column <= candidateEndColumn; column++) + { + string candidateName = LegacyValueHelper.CleanString(sheet.GetValue(1, column)); + if (!string.IsNullOrWhiteSpace(candidateName)) + { + candidateNames.Add(candidateName); + } + } + } + + int row = 2; + while (true) + { + string areaName = LegacyValueHelper.CleanString(sheet.GetValue(row, 1)); + if (string.IsNullOrWhiteSpace(areaName) || areaName == "합계") + { + break; + } + + string districtCode = LegacyValueHelper.CleanString(sheet.GetValue(row, 3)); + string districtLabel = LegacyValueHelper.CleanString(sheet.GetValue(row, 4)); + string districtName = "[" + districtCode + "]" + districtLabel; + string siGunGu = LegacyValueHelper.CleanString(sheet.GetValue(row, 2)); + string eupMyeonDong = LegacyValueHelper.CleanString(sheet.GetValue(row, 5)); + string pollingPlaceNo = ExtractLegacyPollingPlaceNo(LegacyValueHelper.CleanString(sheet.GetValue(row, 6))); + int eligibleVoterCount = LegacyValueHelper.ToInt(sheet.GetValue(row, 7)); + int electorateCount = LegacyValueHelper.ToInt(sheet.GetValue(row, 7)); + int voteCount = LegacyValueHelper.ToInt(sheet.GetValue(row, 8)); + int totalCandidateVotes = LegacyValueHelper.ToInt(sheet.GetValue(row, totalColumn)); + + Dictionary cand = new Dictionary(); + Dictionary candRatio = new Dictionary(); + int candidateNo = 1; + for (int column = candidateStartColumn; column <= candidateEndColumn; column++) + { + int vote = LegacyValueHelper.ToInt(sheet.GetValue(row, column)); + decimal ratio = totalCandidateVotes == 0 ? 0m : Math.Round((decimal)vote / totalCandidateVotes * 100, 2, MidpointRounding.AwayFromZero); + cand["cand_" + candidateNo] = vote.ToString(); + candRatio["cand_ratio_" + candidateNo] = ratio.ToString("0.00"); + candidateNo++; + } + + string buildingName = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 2)).Replace("'", "'"); + string address1 = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 3)).Replace("'", "'"); + string note = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 4)); + string duplicateFlag = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 5)); + string candJson = JsonHelper.Serialize(cand); + string candRatioJson = JsonHelper.Serialize(candRatio); + + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(@" + INSERT INTO poll_data + ( + ele_ym, 선거명, 시도명, 선거구명, 시군구, 읍면동, 투표구명, + t_유권자수, 선거인수, 투표인수, cand, cand_ratio, 후보별득표수계, + 투표소_중복여부, 관할구역, 건물명, 주소1, 비고_기타 + ) + VALUES + ( + @eleYm, @electionName, @areaName, @districtName, @siGunGu, @eupMyeonDong, @pollingPlaceNo, + @eligibleVoterCount, @electorateCount, @voteCount, @cand, @candRatio, @totalCandidateVoteCount, + @duplicateFlag, @areaDetail, @buildingName, @address1, @note + )", connection)) + + { + command.Parameters.Add(new SqlParameter("@eleYm", SqlDbType.VarChar, 6) { Value = electionYear ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@electionName", SqlDbType.VarChar, 50) { Value = electionYear ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@areaName", SqlDbType.VarChar, 50) { Value = areaName ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@districtName", SqlDbType.VarChar, 50) { Value = districtName ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@siGunGu", SqlDbType.VarChar, 50) { Value = siGunGu ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@eupMyeonDong", SqlDbType.VarChar, 50) { Value = eupMyeonDong ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@pollingPlaceNo", SqlDbType.VarChar, 16) { Value = pollingPlaceNo ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@eligibleVoterCount", SqlDbType.Int) { Value = eligibleVoterCount }); + command.Parameters.Add(new SqlParameter("@electorateCount", SqlDbType.Int) { Value = electorateCount }); + command.Parameters.Add(new SqlParameter("@voteCount", SqlDbType.Int) { Value = voteCount }); + command.Parameters.Add(new SqlParameter("@cand", SqlDbType.VarChar, -1) { Value = candJson ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@candRatio", SqlDbType.VarChar, -1) { Value = candRatioJson ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@totalCandidateVoteCount", SqlDbType.Int) { Value = totalCandidateVotes }); + command.Parameters.Add(new SqlParameter("@duplicateFlag", SqlDbType.VarChar, 50) { Value = duplicateFlag ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@areaDetail", SqlDbType.VarChar, 50) { Value = string.Empty }); + command.Parameters.Add(new SqlParameter("@buildingName", SqlDbType.VarChar, 500) { Value = buildingName ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@address1", SqlDbType.VarChar, 500) { Value = address1 ?? string.Empty }); + command.Parameters.Add(new SqlParameter("@note", SqlDbType.VarChar, 200) { Value = note ?? string.Empty }); + + try + { + command.ExecuteNonQuery(); + } + catch (SqlException) + { + foreach (SqlParameter p in command.Parameters) + { + string val = p.Value == null || p.Value == DBNull.Value ? string.Empty : p.Value.ToString(); + Debug.WriteLine(string.Format("PARAM {0} Len={1} Val={2}", p.ParameterName, val.Length, val.Length > 120 ? val.Substring(0, 120) : val)); + } + throw; + } + } + + row++; + } + } + + /// + /// 레거시 표기에서 투표구 번호 텍스트를 추출합니다(예: "제1투" → "1"). + /// + /// 원본 텍스트. + /// 정규화된 투표구 번호 문자열. + private static string ExtractLegacyPollingPlaceNo(string pollingPlaceText) + { + if (string.IsNullOrWhiteSpace(pollingPlaceText)) + { + return "0"; + } + + string value = pollingPlaceText.Trim(); + if (!value.EndsWith("투")) + { + return "0"; + } + + string right3 = value.Length <= 3 ? value : value.Substring(value.Length - 3, 3); + string left2 = right3.Length <= 2 ? right3 : right3.Substring(0, 2); + return left2.Replace("제", string.Empty).Trim(); + } + + /// + /// cand_name 테이블에 후보자명을 upsert(없으면 삽입, 있으면 유지)합니다. + /// + /// 선거 연월. + /// 후보자명 목록. + private void UpsertCandidateNames(string electionYear, List candidateNames) + { + if (candidateNames == null || candidateNames.Count == 0) + { + return; + } + + using (SqlConnection connection = _connectionFactory.Open()) + { + try + { + using (SqlCommand deleteCommand = new SqlCommand("DELETE FROM cand_name WHERE ele_ym = @eleYm", connection)) + { + deleteCommand.Parameters.AddWithValue("@eleYm", electionYear); + deleteCommand.ExecuteNonQuery(); + } + + for (int i = 0; i < candidateNames.Count; i++) + { + using (SqlCommand insertCommand = new SqlCommand("INSERT INTO cand_name(ele_ym, cand_no, cand_name) VALUES(@eleYm, @candNo, @candName)", connection)) + { + insertCommand.Parameters.AddWithValue("@eleYm", electionYear); + insertCommand.Parameters.AddWithValue("@candNo", (i + 1).ToString()); + insertCommand.Parameters.AddWithValue("@candName", candidateNames[i]); + insertCommand.ExecuteNonQuery(); + } + } + } + catch + { + } + } + } + } +} diff --git a/Keps.WinForms/Services/ExcelReportService.cs b/Keps.WinForms/Services/ExcelReportService.cs new file mode 100644 index 0000000..5f4b737 --- /dev/null +++ b/Keps.WinForms/Services/ExcelReportService.cs @@ -0,0 +1,835 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using Keps.WinForms.Models; +using OfficeOpenXml; +using OfficeOpenXml.Style; + +namespace Keps.WinForms.Services +{ + /// + /// 실 추출 결과를 Excel 워크북(.xlsx)으로 내보내는 서비스입니다. + /// + public sealed class ExcelReportService + { + /// + /// 실 추출 결과와 관련 시트를 포함한 Excel 워크북을 저장합니다. + /// + /// 저장할 파일 경로. + /// 선거명 또는 연월. + /// 시도명. + /// 군집 요약 행 목록(모드 시트 등에 사용). + /// 실 추출 결과 DTO. + public void ExportRealExtractionWorkbook(string filePath, string electionName, string areaName, List clusterRows, RealExtractionResult result) + { + if (result == null) + { + throw new InvalidOperationException("추출 결과가 없습니다."); + } + + string dir = Path.GetDirectoryName(filePath); + if (!string.IsNullOrWhiteSpace(dir)) + { + Directory.CreateDirectory(dir); + } + + using (ExcelPackage package = new ExcelPackage()) + { + List candidateNames = (result.CandidateNames ?? new List()).ToList(); + List candidateVoteKeys = (result.CandidateVoteKeys ?? new List()).ToList(); + List candidateRatioKeys = (result.CandidateRatioKeys ?? new List()).ToList(); + NormalizeCandidateLists(candidateNames, candidateVoteKeys, candidateRatioKeys); + + WriteExtractedSheet(package.Workbook.Worksheets.Add(areaName + "-추출결과"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List(), result.PopulationRows ?? new List(), result); + WriteVerificationSummarySheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-요약분석"), electionName, areaName, candidateNames, result.VerificationRows ?? new List(), result.ClusterMax); + WriteVerificationDetailSheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-세부분석"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List(), result.VerificationRows ?? new List(), result.ClusterMax); + WriteFinalStatusSheet(package.Workbook.Worksheets.Add(areaName + "-최종 투표소 추출현황"), electionName, areaName, candidateNames, candidateVoteKeys, result.PopulationRows ?? new List(), result.ClusterMax); + WriteClusterListSheet(package.Workbook.Worksheets.Add(areaName + "-층별 시군구 리스트"), electionName, areaName, result.PopulationRows ?? new List()); + WriteModeSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode"), electionName, clusterRows ?? new List(), result.PopulationRows ?? new List()); + WriteModeTargetSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode Target"), clusterRows ?? new List(), result.PopulationRows ?? new List()); + + package.SaveAs(new FileInfo(filePath)); + } + } + + /// + /// 추출 결과 시트를 작성합니다(클러스터별 표본과 모집단 요약 포함). + /// + /// 대상 워크시트. + /// 선거명 또는 연월. + /// 시도명. + /// 후보자 표시명 목록(최소 3개로 보정됨). + /// 후보자 득표 키 목록(최소 3개로 보정됨). + /// 추출 표본 행 목록. + /// 모집단 행 목록. + /// 추출 실행 메타(정렬/오프셋 등). + private static void WriteExtractedSheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List candidateVoteKeys, List rows, List populationRows, RealExtractionResult result) + { + int rowIndex = 1; + foreach (IGrouping clusterGroup in rows.GroupBy(x => x.ClusterNo).OrderBy(x => x.Key)) + { + int sampleCount = clusterGroup.Count(); + MergeAndSet(ws, rowIndex, 1, rowIndex, 15, BuildClusterTitle(result, clusterGroup.Key, sampleCount)); + ws.Cells[rowIndex, 1].Style.Font.Bold = true; + rowIndex++; + + SetExtractHeader(ws, rowIndex, candidateNames, result.ClusterMax); + rowIndex += 2; + + List clusterPopulation = populationRows.Where(x => x.ClusterNo == clusterGroup.Key).ToList(); + MergeAndSet(ws, rowIndex, 1, rowIndex, 8, clusterGroup.Key + " 층(군집) 전체"); + ws.Cells[rowIndex, 9].Value = clusterPopulation.Sum(x => GetVoteByKey(x, candidateVoteKeys[0])); + ws.Cells[rowIndex, 10].Value = clusterPopulation.Sum(x => GetVoteByKey(x, candidateVoteKeys[1])); + ws.Cells[rowIndex, 11].Value = clusterPopulation.Sum(x => GetVoteByKey(x, candidateVoteKeys[2])); + ws.Cells[rowIndex, 12].Value = clusterPopulation.Sum(x => x.TotalCandidateVoteCount); + ws.Cells[rowIndex, 13].Value = ComputeClusterActualRatio(clusterPopulation, candidateVoteKeys[0]); + ws.Cells[rowIndex, 14].Value = ComputeClusterActualRatio(clusterPopulation, candidateVoteKeys[1]); + ws.Cells[rowIndex, 15].Value = ComputeClusterActualRatio(clusterPopulation, candidateVoteKeys[2]); + FillHeaderGray(ws, rowIndex, 1, rowIndex, 15); + rowIndex++; + + foreach (ExtractionRow row in clusterGroup.OrderBy(x => x.ClusterOrder)) + { + ws.Cells[rowIndex, 1].Value = row.ClusterOrder; + ws.Cells[rowIndex, 2].Value = electionName; + ws.Cells[rowIndex, 3].Value = row.AreaName; + ws.Cells[rowIndex, 4].Value = row.DistrictName; + ws.Cells[rowIndex, 5].Value = row.ClusterNo; + ws.Cells[rowIndex, 6].Value = BuildTownLabel(row); + ws.Cells[rowIndex, 7].Value = row.PollingPlaceNo; + ws.Cells[rowIndex, 8].Value = row.ElectorateCount; + ws.Cells[rowIndex, 9].Value = GetVoteByKey(row, candidateVoteKeys[0]); + ws.Cells[rowIndex, 10].Value = GetVoteByKey(row, candidateVoteKeys[1]); + ws.Cells[rowIndex, 11].Value = GetVoteByKey(row, candidateVoteKeys[2]); + ws.Cells[rowIndex, 12].Value = row.TotalCandidateVoteCount; + ws.Cells[rowIndex, 13].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[0]); + ws.Cells[rowIndex, 14].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[1]); + ws.Cells[rowIndex, 15].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[2]); + rowIndex++; + } + + MergeAndSet(ws, rowIndex, 1, rowIndex, 15, "---------------------------------------------------"); + rowIndex++; + } + + ApplyCommonFormatting(ws, 15); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 8, 9, 10, 11, 12 }, "#,##0"); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 13, 14, 15 }, "0.0"); + } + + /// + /// 추출 결과 시트의 헤더(타이틀/열 병합/후보 라벨)를 설정합니다. + /// + /// 대상 워크시트. + /// 헤더를 쓸 시작 행. + /// 후보자 표시명 목록. + /// 층(군집) 최대 개수. + private static void SetExtractHeader(ExcelWorksheet ws, int rowIndex, List candidateNames, int clusterMax) + { + for (int col = 1; col <= 8; col++) + { + ws.Cells[rowIndex, col, rowIndex + 1, col].Merge = true; + } + ws.Cells[rowIndex, 12, rowIndex + 1, 12].Merge = true; + ws.Cells[rowIndex, 1].Value = "순번"; + ws.Cells[rowIndex, 2].Value = "선거명"; + ws.Cells[rowIndex, 3].Value = "시도명"; + ws.Cells[rowIndex, 4].Value = "선거구명"; + ws.Cells[rowIndex, 5].Value = "층(" + clusterMax + "개층)"; + ws.Cells[rowIndex, 6].Value = "읍면동"; + ws.Cells[rowIndex, 7].Value = "투표구명"; + ws.Cells[rowIndex, 8].Value = "선거인수"; + ws.Cells[rowIndex, 9].Value = "기호1"; + ws.Cells[rowIndex, 10].Value = "기호2"; + ws.Cells[rowIndex, 11].Value = "기호3"; + ws.Cells[rowIndex, 12].Value = "유효\n득표수계"; + ws.Cells[rowIndex, 13].Value = "기호1"; + ws.Cells[rowIndex, 14].Value = "기호2"; + ws.Cells[rowIndex, 15].Value = "기호3"; + ws.Cells[rowIndex + 1, 9].Value = candidateNames[0]; + ws.Cells[rowIndex + 1, 10].Value = candidateNames[1]; + ws.Cells[rowIndex + 1, 11].Value = candidateNames[2]; + ws.Cells[rowIndex + 1, 13].Value = "득표율"; + ws.Cells[rowIndex + 1, 14].Value = "득표율"; + ws.Cells[rowIndex + 1, 15].Value = "득표율"; + FillHeaderGray(ws, rowIndex, 1, rowIndex + 1, 15); + ws.Cells[rowIndex, 1, rowIndex + 1, 15].Style.WrapText = true; + } + + /// + /// 자가 검증-요약분석 시트를 작성합니다(전체/층별 득표율 및 오차 요약). + /// + /// 대상 워크시트. + /// 선거명 또는 연월. + /// 시도명. + /// 후보자 표시명 목록. + /// 검증 요약 행 목록. + /// 군집(층) 최대 개수. + private static void WriteVerificationSummarySheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List rows, int clusterMax) + { + ws.Cells[1, 1].Value = areaName; + MergeAndSet(ws, 1, 2, 1, 7, "정렬(" + clusterMax + "개층)"); + MergeAndSet(ws, 1, 8, 1, 18, electionName + " 층화 후 득표율 기준 자가(self) 검증"); + + ws.Cells[2, 1, 3, 1].Merge = true; + ws.Cells[2, 2, 3, 2].Merge = true; + ws.Cells[2, 3, 3, 3].Merge = true; + ws.Cells[2, 4, 3, 4].Merge = true; + MergeAndSet(ws, 2, 5, 2, 7, "추출 득표율"); + MergeAndSet(ws, 2, 8, 2, 10, "실제 득표율"); + MergeAndSet(ws, 2, 11, 2, 14, "전체 오차비교"); + MergeAndSet(ws, 2, 15, 2, 18, "층내 오차비교"); + ws.Cells[2, 1].Value = "투표구수"; + ws.Cells[2, 2].Value = "해당층"; + ws.Cells[2, 3].Value = "층의비율"; + ws.Cells[2, 4].Value = "추출\n투표구수"; + ws.Cells[3, 5].Value = candidateNames[0]; + ws.Cells[3, 6].Value = candidateNames[1]; + ws.Cells[3, 7].Value = candidateNames[2]; + ws.Cells[3, 8].Value = candidateNames[0]; + ws.Cells[3, 9].Value = candidateNames[1]; + ws.Cells[3, 10].Value = candidateNames[2]; + ws.Cells[3, 11].Value = "기호1오차"; + ws.Cells[3, 12].Value = "기호2오차"; + ws.Cells[3, 13].Value = "기호3오차"; + ws.Cells[3, 14].Value = "오차합"; + ws.Cells[3, 15].Value = "기호1오차"; + ws.Cells[3, 16].Value = "기호2오차"; + ws.Cells[3, 17].Value = "기호3오차"; + ws.Cells[3, 18].Value = "오차합"; + FillHeaderGray(ws, 1, 1, 3, 18); + + int rowIndex = 4; + foreach (VerificationSummaryRow row in rows) + { + ws.Cells[rowIndex, 1].Value = row.RowLabel == "전체" ? row.SampleCount + "개" : null; + ws.Cells[rowIndex, 2].Value = row.RowLabel; + ws.Cells[rowIndex, 3].Value = row.ClusterRatio; + ws.Cells[rowIndex, 4].Value = row.SampleCount; + ws.Cells[rowIndex, 5].Value = row.Extracted1; + ws.Cells[rowIndex, 6].Value = row.Extracted2; + ws.Cells[rowIndex, 7].Value = row.Extracted3; + ws.Cells[rowIndex, 8].Value = row.Actual1; + ws.Cells[rowIndex, 9].Value = row.Actual2; + ws.Cells[rowIndex, 10].Value = row.Actual3; + ws.Cells[rowIndex, 11].Value = row.WeightedError1; + ws.Cells[rowIndex, 12].Value = row.WeightedError2; + ws.Cells[rowIndex, 13].Value = row.WeightedError3; + ws.Cells[rowIndex, 14].Value = row.WeightedErrorSum; + ws.Cells[rowIndex, 15].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterError1; + ws.Cells[rowIndex, 16].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterError2; + ws.Cells[rowIndex, 17].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterError3; + ws.Cells[rowIndex, 18].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterErrorSum; + if (row.RowLabel == "전체") + { + FillHeaderGray(ws, rowIndex, 1, rowIndex, 18); + } + rowIndex++; + } + + ApplyCommonFormatting(ws, 18); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }, "0.0"); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 3 }, "0.00000"); + } + + /// + /// 자가 검증-세부분석 시트를 작성합니다(층/구간별 상세 지표 포함). + /// + /// 대상 워크시트. + /// 선거명 또는 연월. + /// 시도명. + /// 후보자 표시명 목록. + /// 후보자 득표 키 목록. + /// 추출 표본 행 목록. + /// 검증 요약 행 목록. + /// 군집(층) 최대 개수. + private static void WriteVerificationDetailSheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List candidateVoteKeys, List rows, List summaryRows, int clusterMax) + { + ws.Cells[1, 1].Value = areaName; + MergeAndSet(ws, 1, 2, 1, 7, "정렬(" + clusterMax + "개층)"); + MergeAndSet(ws, 1, 8, 1, 18, electionName + " 층화 후 득표율 기준 자가(self) 검증-세부분석"); + + ws.Cells[2, 1, 3, 1].Merge = true; + ws.Cells[2, 2, 3, 2].Merge = true; + ws.Cells[2, 3, 3, 3].Merge = true; + ws.Cells[2, 4, 3, 4].Merge = true; + MergeAndSet(ws, 2, 5, 2, 7, "추출 득표율"); + MergeAndSet(ws, 2, 8, 2, 10, "실제 득표율"); + MergeAndSet(ws, 2, 11, 2, 14, "선거구 오차비교"); + MergeAndSet(ws, 2, 15, 2, 18, "층내 오차비교"); + ws.Cells[2, 1].Value = "해당층"; + ws.Cells[2, 2].Value = "투표구별"; + ws.Cells[2, 3].Value = "층의비율"; + ws.Cells[2, 4].Value = "추출\n투표구수"; + ws.Cells[3, 5].Value = candidateNames[0]; + ws.Cells[3, 6].Value = candidateNames[1]; + ws.Cells[3, 7].Value = candidateNames[2]; + ws.Cells[3, 8].Value = candidateNames[0]; + ws.Cells[3, 9].Value = candidateNames[1]; + ws.Cells[3, 10].Value = candidateNames[2]; + ws.Cells[3, 11].Value = "기호1오차"; + ws.Cells[3, 12].Value = "기호2오차"; + ws.Cells[3, 13].Value = "기호3오차"; + ws.Cells[3, 14].Value = "오차합"; + ws.Cells[3, 15].Value = "기호1오차"; + ws.Cells[3, 16].Value = "기호2오차"; + ws.Cells[3, 17].Value = "기호3오차"; + ws.Cells[3, 18].Value = "오차합"; + FillHeaderGray(ws, 1, 1, 3, 18); + + VerificationSummaryRow total = summaryRows.FirstOrDefault(x => x.RowLabel == "전체"); + int rowIndex = 4; + if (total != null) + { + WriteSummaryLikeDetailRow(ws, rowIndex++, total, "전체", "전체", false); + } + + foreach (IGrouping group in rows.GroupBy(x => x.ClusterNo).OrderBy(x => x.Key)) + { + VerificationSummaryRow clusterSummary = summaryRows.FirstOrDefault(x => x.RowLabel == group.Key + " 층"); + if (clusterSummary != null) + { + WriteSummaryLikeDetailRow(ws, rowIndex++, clusterSummary, group.Key + " 층계", null, true); + } + + foreach (ExtractionRow row in group.OrderBy(x => x.ClusterOrder)) + { + decimal rowRatio1 = ComputeDisplayedRowRatio(row, candidateVoteKeys[0]); + decimal rowRatio2 = ComputeDisplayedRowRatio(row, candidateVoteKeys[1]); + decimal rowRatio3 = ComputeDisplayedRowRatio(row, candidateVoteKeys[2]); + ws.Cells[rowIndex, 2].Value = BuildTownLabel(row) + " " + row.PollingPlaceNo + "투"; + ws.Cells[rowIndex, 4].Value = "-"; + ws.Cells[rowIndex, 5].Value = rowRatio1; + ws.Cells[rowIndex, 6].Value = rowRatio2; + ws.Cells[rowIndex, 7].Value = rowRatio3; + if (total != null) + { + decimal err1 = Round1(rowRatio1 - total.Actual1); + decimal err2 = Round1(rowRatio2 - total.Actual2); + decimal err3 = Round1(rowRatio3 - total.Actual3); + ws.Cells[rowIndex, 11].Value = err1; + ws.Cells[rowIndex, 12].Value = err2; + ws.Cells[rowIndex, 13].Value = err3; + ws.Cells[rowIndex, 14].Value = Round1(Math.Abs(err1) + Math.Abs(err2) + Math.Abs(err3)); + } + if (clusterSummary != null) + { + decimal err1 = Round1(rowRatio1 - clusterSummary.Actual1); + decimal err2 = Round1(rowRatio2 - clusterSummary.Actual2); + decimal err3 = Round1(rowRatio3 - clusterSummary.Actual3); + ws.Cells[rowIndex, 15].Value = err1; + ws.Cells[rowIndex, 16].Value = err2; + ws.Cells[rowIndex, 17].Value = err3; + ws.Cells[rowIndex, 18].Value = Round1(Math.Abs(err1) + Math.Abs(err2) + Math.Abs(err3)); + } + rowIndex++; + } + } + + ApplyCommonFormatting(ws, 18); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18 }, "0.0"); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 3 }, "0.00000"); + } + + /// + /// 요약 행 데이터를 세부 형식과 동일하게 한 줄로 출력합니다. + /// + /// 대상 워크시트. + /// 기록할 시작 행. + /// 요약 데이터. + /// 왼쪽 라벨. + /// 오른쪽 라벨. + /// 군집 내 오차 컬럼 포함 여부. + private static void WriteSummaryLikeDetailRow(ExcelWorksheet ws, int rowIndex, VerificationSummaryRow row, string label1, string label2, bool includeClusterError) + { + ws.Cells[rowIndex, 1].Value = label1; + ws.Cells[rowIndex, 2].Value = label2; + ws.Cells[rowIndex, 3].Value = row.ClusterRatio; + ws.Cells[rowIndex, 4].Value = row.SampleCount; + ws.Cells[rowIndex, 5].Value = row.Extracted1; + ws.Cells[rowIndex, 6].Value = row.Extracted2; + ws.Cells[rowIndex, 7].Value = row.Extracted3; + ws.Cells[rowIndex, 8].Value = row.Actual1; + ws.Cells[rowIndex, 9].Value = row.Actual2; + ws.Cells[rowIndex, 10].Value = row.Actual3; + ws.Cells[rowIndex, 11].Value = row.WeightedError1; + ws.Cells[rowIndex, 12].Value = row.WeightedError2; + ws.Cells[rowIndex, 13].Value = row.WeightedError3; + ws.Cells[rowIndex, 14].Value = row.WeightedErrorSum; + if (includeClusterError) + { + ws.Cells[rowIndex, 15].Value = row.InClusterError1; + ws.Cells[rowIndex, 16].Value = row.InClusterError2; + ws.Cells[rowIndex, 17].Value = row.InClusterError3; + ws.Cells[rowIndex, 18].Value = row.InClusterErrorSum; + } + } + + /// + /// 최종 투표소 추출현황 시트를 작성합니다(모집단 내 각 행과 후보 득표수/비율 표시). + /// + /// 대상 워크시트. + /// 선거명 또는 연월. + /// 시도명. + /// 후보자 표시명 목록. + /// 후보자 득표 키 목록. + /// 모집단 행 목록. + /// 군집(층) 최대 개수. + private static void WriteFinalStatusSheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List candidateVoteKeys, List rows, int clusterMax) + { + ws.Cells[1, 1].Value = areaName; + ws.Cells[3, 1].Value = clusterMax + "개층"; + ws.Cells[1, 2, 3, 2].Merge = true; + ws.Cells[1, 3, 3, 3].Merge = true; + ws.Cells[1, 2].Value = "ID"; + ws.Cells[1, 3].Value = "시군구"; + MergeAndSet(ws, 1, 4, 1, 9, "Target 선거 출구조사 투표소 현황"); + MergeAndSet(ws, 1, 10, 1, 13, "정렬기준(" + electionName + ")"); + ws.Cells[1, 14, 3, 14].Merge = true; + ws.Cells[1, 15, 3, 15].Merge = true; + ws.Cells[1, 14].Value = "투표소\n중복여부"; + ws.Cells[1, 15].Value = "비고 - 기타"; + for (int col = 4; col <= 10; col++) + { + if (col != 10) + { + ws.Cells[2, col, 3, col].Merge = true; + } + } + ws.Cells[2, 4].Value = "투표구명"; + ws.Cells[2, 5].Value = "유권자수"; + ws.Cells[2, 6].Value = "투표 장소(건물명)"; + ws.Cells[2, 7].Value = "투표 장소(주소)"; + ws.Cells[2, 8].Value = "자동\n추출"; + ws.Cells[2, 9].Value = "조정"; + ws.Cells[2, 10, 3, 10].Merge = true; + ws.Cells[2, 10].Value = "득표수\n계"; + MergeAndSet(ws, 2, 11, 2, 13, "득표율"); + ws.Cells[3, 11].Value = candidateNames[0]; + ws.Cells[3, 12].Value = candidateNames[1]; + ws.Cells[3, 13].Value = candidateNames[2]; + FillHeaderGray(ws, 1, 1, 3, 15); + + int rowIndex = 4; + foreach (IGrouping group in rows.GroupBy(x => x.ClusterNo).OrderBy(x => x.Key)) + { + ws.Cells[rowIndex, 1].Value = group.Key + "층계"; + ws.Cells[rowIndex, 2].Value = "-"; + ws.Cells[rowIndex, 3].Value = "-"; + ws.Cells[rowIndex, 4].Value = "-"; + ws.Cells[rowIndex, 5].Value = group.Sum(x => x.EligibleVoterCount); + ws.Cells[rowIndex, 6].Value = "-"; + ws.Cells[rowIndex, 7].Value = "-"; + ws.Cells[rowIndex, 8].Value = "-"; + ws.Cells[rowIndex, 10].Value = group.Sum(x => x.TotalCandidateVoteCount); + ws.Cells[rowIndex, 11].Value = ComputeClusterActualRatio(group.ToList(), candidateVoteKeys[0]); + ws.Cells[rowIndex, 12].Value = ComputeClusterActualRatio(group.ToList(), candidateVoteKeys[1]); + ws.Cells[rowIndex, 13].Value = ComputeClusterActualRatio(group.ToList(), candidateVoteKeys[2]); + FillHeaderGray(ws, rowIndex, 1, rowIndex, 15); + rowIndex++; + + foreach (ExtractionRow row in group.OrderBy(x => x.OriginalOrder)) + { + ws.Cells[rowIndex, 1].Value = row.ClusterNo; + ws.Cells[rowIndex, 2].Value = row.OriginalOrder; + ws.Cells[rowIndex, 3].Value = row.DistrictName; + ws.Cells[rowIndex, 4].Value = row.EupMyeonDong + " " + row.PollingPlaceNo + "투"; + ws.Cells[rowIndex, 5].Value = row.EligibleVoterCount; + ws.Cells[rowIndex, 6].Value = row.BuildingName; + ws.Cells[rowIndex, 7].Value = row.Address1; + ws.Cells[rowIndex, 8].Value = (row.IsAutoSelected || row.IsAdjustedSelected) ? "★" : null; + ws.Cells[rowIndex, 9].Value = row.IsAdjustedSelected ? "★" : (row.IsAutoSelected ? "★" : null); + ws.Cells[rowIndex, 10].Value = row.TotalCandidateVoteCount; + ws.Cells[rowIndex, 11].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[0]); + ws.Cells[rowIndex, 12].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[1]); + ws.Cells[rowIndex, 13].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[2]); + ws.Cells[rowIndex, 14].Value = row.DuplicateFlag; + ws.Cells[rowIndex, 15].Value = row.Note; + rowIndex++; + } + } + + ApplyCommonFormatting(ws, 15); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 5, 10 }, "#,##0"); + SetNumberFormats(ws, 4, rowIndex - 1, new[] { 11, 12, 13 }, "0.0"); + } + + /// + /// 층별 시군구 리스트 시트를 작성합니다(군집별로 읍면동 묶음 출력). + /// + /// 대상 워크시트. + /// 선거명 또는 연월. + /// 시도명. + /// 모집단 행 목록. + private static void WriteClusterListSheet(ExcelWorksheet ws, string electionName, string areaName, List rows) + { + ws.Cells[1, 1].Value = "선거명"; + ws.Cells[1, 2].Value = "시도명"; + ws.Cells[1, 3].Value = "선거구명"; + ws.Cells[1, 4].Value = "군집"; + ws.Cells[1, 5].Value = "읍면동"; + FillHeaderGray(ws, 1, 1, 1, 5); + int rowIndex = 2; + foreach (var row in rows.GroupBy(x => new { x.DistrictName, x.ClusterNo }).OrderBy(x => x.Key.ClusterNo).ThenBy(x => x.Key.DistrictName)) + { + ws.Cells[rowIndex, 1].Value = electionName; + ws.Cells[rowIndex, 2].Value = areaName; + ws.Cells[rowIndex, 3].Value = row.Key.DistrictName; + ws.Cells[rowIndex, 4].Value = row.Key.ClusterNo; + rowIndex++; + } + ApplyCommonFormatting(ws, 5); + } + + /// + /// 기준설정 Mode 시트를 작성합니다(군집 요약과 모집단 정보를 활용한 기준표). + /// + /// 대상 워크시트. + /// 선거명 또는 연월. + /// 군집 요약 행 목록. + /// 모집단 행 목록. + private static void WriteModeSheet(ExcelWorksheet ws, string electionName, List rows, List populationRows) + { + MergeAndSet(ws, 1, 1, 1, 7, electionName); + ws.Cells[2, 1].Value = "층"; + ws.Cells[2, 2].Value = "투표구수"; + ws.Cells[2, 3].Value = "층의비율"; + ws.Cells[2, 4].Value = "유권자수"; + ws.Cells[2, 5].Value = "투표인수"; + ws.Cells[2, 6].Value = "후보별득표수계"; + ws.Cells[2, 7].Value = "투표율"; + FillHeaderGray(ws, 1, 1, 2, 7); + + int rowIndex = 3; + foreach (ClusterSummaryRow row in rows.OrderBy(x => x.ClusterNo)) + { + List clusterPopulation = populationRows.Where(x => x.ClusterNo == row.ClusterNo).ToList(); + int electorate = clusterPopulation.Sum(x => x.ElectorateCount); + int voteCount = clusterPopulation.Sum(x => x.VoteCount); + int totalVotes = clusterPopulation.Sum(x => x.TotalCandidateVoteCount); + ws.Cells[rowIndex, 1].Value = row.ClusterNo + " 층"; + ws.Cells[rowIndex, 2].Value = row.PollingPlaceCount; + ws.Cells[rowIndex, 3].Value = row.Ratio; + ws.Cells[rowIndex, 4].Value = electorate; + ws.Cells[rowIndex, 5].Value = voteCount; + ws.Cells[rowIndex, 6].Value = totalVotes; + ws.Cells[rowIndex, 7].Value = electorate == 0 ? 0m : Round1((decimal)voteCount / electorate * 100m); + rowIndex++; + } + + ws.Cells[rowIndex, 1].Value = "합계"; + ws.Cells[rowIndex, 2].Value = rows.Sum(x => x.PollingPlaceCount); + ws.Cells[rowIndex, 3].Value = rows.Sum(x => x.Ratio); + ws.Cells[rowIndex, 4].Value = populationRows.Sum(x => x.ElectorateCount); + ws.Cells[rowIndex, 5].Value = populationRows.Sum(x => x.VoteCount); + ws.Cells[rowIndex, 6].Value = populationRows.Sum(x => x.TotalCandidateVoteCount); + ws.Cells[rowIndex, 7].Value = populationRows.Sum(x => x.ElectorateCount) == 0 ? 0m : Round1((decimal)populationRows.Sum(x => x.VoteCount) / populationRows.Sum(x => x.ElectorateCount) * 100m); + + ApplyCommonFormatting(ws, 7); + SetNumberFormats(ws, 3, rowIndex, new[] { 2, 4, 5, 6 }, "#,##0"); + SetNumberFormats(ws, 3, rowIndex, new[] { 3 }, "0.00000"); + SetNumberFormats(ws, 3, rowIndex, new[] { 7 }, "0.0"); + } + + /// + /// 기준설정 Mode Target 시트를 작성합니다(군집별 타깃 비교 표). + /// + /// 대상 워크시트. + /// 군집 요약 행 목록. + /// 모집단 행 목록. + private static void WriteModeTargetSheet(ExcelWorksheet ws, List clusterRows, List rows) + { + MergeAndSet(ws, 1, 1, 1, 6, "Target 층별 현황"); + ws.Cells[2, 1].Value = "층"; + ws.Cells[2, 2].Value = "총투표구수"; + ws.Cells[2, 3].Value = "유권자수"; + ws.Cells[2, 4].Value = "층의 유권자비율"; + ws.Cells[2, 5].Value = "추출투표구수"; + ws.Cells[2, 6].Value = "해당지역"; + FillHeaderGray(ws, 1, 1, 2, 6); + + int rowIndex = 3; + foreach (ClusterSummaryRow row in clusterRows.OrderBy(x => x.ClusterNo)) + { + List clusterPopulation = rows.Where(x => x.ClusterNo == row.ClusterNo).OrderBy(x => x.OriginalOrder).ToList(); + string areas = string.Join(string.Empty, clusterPopulation.Where(x => x.IsAutoSelected || x.IsAdjustedSelected).Select(x => x.EupMyeonDong + "-" + x.PollingPlaceNo + "투, ")); + ws.Cells[rowIndex, 1].Value = row.ClusterNo + " 층"; + ws.Cells[rowIndex, 2].Value = row.PollingPlaceCount; + ws.Cells[rowIndex, 3].Value = null; + ws.Cells[rowIndex, 4].Value = row.Ratio; + ws.Cells[rowIndex, 5].Value = row.SampleCount; + ws.Cells[rowIndex, 6].Value = areas; + rowIndex++; + } + ws.Cells[rowIndex, 1].Value = "합계"; + ws.Cells[rowIndex, 2].Value = clusterRows.Sum(x => x.PollingPlaceCount); + ws.Cells[rowIndex, 3].Value = 0; + ws.Cells[rowIndex, 4].Value = clusterRows.Sum(x => x.Ratio); + ws.Cells[rowIndex, 5].Value = clusterRows.Sum(x => x.SampleCount); + + ApplyCommonFormatting(ws, 6); + SetNumberFormats(ws, 3, rowIndex, new[] { 2, 5 }, "#,##0"); + SetNumberFormats(ws, 3, rowIndex, new[] { 4 }, "0.00000"); + } + + /// + /// 클러스터(층) 타이틀 텍스트를 생성합니다(표본 수/정렬/오프셋 등 메타 포함). + /// + /// 실 추출 결과 메타. + /// 군집(층) 번호. + /// 해당 층의 표본 수. + /// 표시용 타이틀 문자열. + private static string BuildClusterTitle(RealExtractionResult result, int clusterNo, int sampleCount) + { + string allocationText = result.IsAutoAllocation ? "추출 투표구수 자동 지정" : "추출 투표구수 수동 지정"; + string sortText = string.IsNullOrWhiteSpace(result.SortDisplayName) ? "투표인수" : result.SortDisplayName; + string directionText = result.SortDescending ? "내림차순" : "오름차순"; + string offsetText = BuildOffsetTitle(result.OffsetDescription); + return string.Format("{0}, 득표율 소트 : {1} - {2}, {3}, 총 {4}개짜리 층중 {5} 번째 층 추출 투표구 수 {6}개(총 {7}개) 추출", allocationText, sortText, directionText, offsetText, result.ClusterMax, clusterNo, sampleCount, result.TotalSampleCount); + } + + /// + /// 오프셋 설명 텍스트를 생성합니다. + /// + /// 사용자에게 표시할 오프셋 설명. + /// 표시용 오프셋 설명 문자열. + private static string BuildOffsetTitle(string offsetDescription) + { + if (string.IsNullOrWhiteSpace(offsetDescription)) + { + return "추출위치 기본값"; + } + + string text = offsetDescription.Trim(); + if (text.StartsWith("n - ")) + { + return "추출위치에서 -" + text.Substring(4) + " 옵션"; + } + if (text.StartsWith("n + ")) + { + return "추출위치에서 +" + text.Substring(4) + " 옵션"; + } + if (text == "n") + { + return "추출위치 기본값"; + } + return text; + } + + /// + /// 후보자 이름/득표키/비율키 목록을 최소 3개까지 보정합니다. + /// + /// 후보자 표시명 목록(부족 시 기본값 채움). + /// 후보자 득표 키 목록(부족 시 기본값 채움). + /// 후보자 득표율 키 목록(부족 시 기본값 채움). + private static void NormalizeCandidateLists(List candidateNames, List candidateVoteKeys, List candidateRatioKeys) + { + while (candidateNames.Count < 3) + { + candidateNames.Add("후보" + (candidateNames.Count + 1)); + } + while (candidateVoteKeys.Count < 3) + { + candidateVoteKeys.Add("cand_" + (candidateVoteKeys.Count + 1)); + } + while (candidateRatioKeys.Count < 3) + { + candidateRatioKeys.Add("cand_ratio_" + (candidateRatioKeys.Count + 1)); + } + } + + /// + /// 읍면동 라벨을 생성합니다(시군구가 있으면 "시군구-읍면동"). + /// + /// 대상 행. + /// 표시용 읍면동 라벨. + private static string BuildTownLabel(ExtractionRow row) + { + return string.IsNullOrWhiteSpace(row.SiGunGu) ? row.EupMyeonDong : row.SiGunGu + "-" + row.EupMyeonDong; + } + + /// + /// 추출/모집단 행에서 지정 후보의 득표수를 반환합니다. + /// + /// 대상 행. + /// 후보자 득표 키(예: cand_1). + /// 득표수. 키 없거나 null이면 0. + private static decimal GetVoteByKey(ExtractionRow row, string candidateVoteKey) + { + if (row == null || row.CandidateVotes == null || string.IsNullOrWhiteSpace(candidateVoteKey)) + { + return 0m; + } + + return row.CandidateVotes.ContainsKey(candidateVoteKey) ? row.CandidateVotes[candidateVoteKey] : 0m; + } + + /// + /// 행에 저장된 후보 득표율(%)을 반환합니다. 없으면 0. + /// + /// 대상 행. + /// 후보자 득표 키(예: cand_1). + /// 저장된 득표율(%). 없으면 0. + private static decimal GetStoredRatioByKey(ExtractionRow row, string candidateVoteKey) + { + if (row == null || row.CandidateRatios == null || string.IsNullOrWhiteSpace(candidateVoteKey)) + { + return 0m; + } + + string ratioKey = candidateVoteKey.Replace("cand_", "cand_ratio_"); + return row.CandidateRatios.ContainsKey(ratioKey) ? row.CandidateRatios[ratioKey] : 0m; + } + + /// + /// 행 단위 표시 득표율(%)을 계산합니다. 저장된 비율이 있으면 그것을 우선 사용합니다. + /// + /// 대상 행. + /// 후보자 득표 키. + /// 표시용 득표율(%). + private static decimal ComputeDisplayedRowRatio(ExtractionRow row, string candidateVoteKey) + { + if (row == null || row.TotalCandidateVoteCount <= 0) + { + return 0m; + } + + decimal storedRatio = GetStoredRatioByKey(row, candidateVoteKey); + if (storedRatio > 0m) + { + return Round1(storedRatio); + } + + return Round1(GetVoteByKey(row, candidateVoteKey) / row.TotalCandidateVoteCount * 100m); + } + + /// + /// 클러스터(그룹) 내 실제 득표율(%)을 계산합니다. + /// + /// 대상 행 목록. + /// 후보자 득표 키. + /// 득표율(%), 분모가 0이면 0. + private static decimal ComputeClusterActualRatio(List rows, string candidateVoteKey) + { + int totalVotes = rows.Sum(x => x.TotalCandidateVoteCount); + if (totalVotes <= 0) + { + return 0m; + } + + decimal vote = rows.Sum(x => GetVoteByKey(x, candidateVoteKey)); + return Round1(Round2(vote / totalVotes * 100m)); + } + + /// + /// 그룹(임의 묶음) 내 득표율(%)을 계산합니다. + /// + /// 대상 행 목록. + /// 후보자 득표 키. + /// 득표율(%), 분모가 0이면 0. + private static decimal ComputeGroupRatio(List rows, string candidateVoteKey) + { + int totalVotes = rows.Sum(x => x.TotalCandidateVoteCount); + if (totalVotes <= 0) + { + return 0m; + } + + decimal vote = rows.Sum(x => GetVoteByKey(x, candidateVoteKey)); + return Round1(vote / totalVotes * 100m); + } + + /// + /// 소수점 첫째 자리에서 반올림(away from zero)합니다. + /// + /// 반올림할 값. + /// 소수 첫째 자리 반올림 값. + private static decimal Round1(decimal value) + { + return Math.Round(value, 1, MidpointRounding.AwayFromZero); + } + + /// + /// 소수점 둘째 자리에서 반올림(away from zero)합니다. + /// + /// 반올림할 값. + /// 소수 둘째 자리 반올림 값. + private static decimal Round2(decimal value) + { + return Math.Round(value, 2, MidpointRounding.AwayFromZero); + } + + private static void MergeAndSet(ExcelWorksheet ws, int fromRow, int fromCol, int toRow, int toCol, object value) + { + ws.Cells[fromRow, fromCol, toRow, toCol].Merge = true; + ws.Cells[fromRow, fromCol].Value = value; + } + + private static void FillHeaderGray(ExcelWorksheet ws, int fromRow, int fromCol, int toRow, int toCol) + { + using (ExcelRange range = ws.Cells[fromRow, fromCol, toRow, toCol]) + { + range.Style.Fill.PatternType = ExcelFillStyle.Solid; + range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(242, 242, 242)); + range.Style.Font.Bold = true; + range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; + range.Style.VerticalAlignment = ExcelVerticalAlignment.Center; + range.Style.WrapText = true; + } + } + + private static void ApplyCommonFormatting(ExcelWorksheet ws, int columnCount) + { + if (ws.Dimension == null) + { + return; + } + + using (ExcelRange range = ws.Cells[1, 1, ws.Dimension.End.Row, columnCount]) + { + range.Style.Font.Name = "맑은 고딕"; + range.Style.Font.Size = 9; + range.Style.Border.Top.Style = ExcelBorderStyle.Thin; + range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; + range.Style.Border.Left.Style = ExcelBorderStyle.Thin; + range.Style.Border.Right.Style = ExcelBorderStyle.Thin; + range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; + range.Style.VerticalAlignment = ExcelVerticalAlignment.Center; + } + + for (int i = 1; i <= columnCount; i++) + { + if (i == 1) + { + ws.Column(i).Width = 16; + } + else if (i <= 4) + { + ws.Column(i).Width = 14; + } + else if (i <= 7) + { + ws.Column(i).Width = 20; + } + else if (i == 15) + { + ws.Column(i).Width = 45; + } + else + { + ws.Column(i).Width = 12; + } + } + } + + private static void SetNumberFormats(ExcelWorksheet ws, int fromRow, int toRow, IEnumerable columns, string numberFormat) + { + foreach (int col in columns) + { + ws.Cells[fromRow, col, toRow, col].Style.Numberformat.Format = numberFormat; + } + } + } +} diff --git a/Keps.WinForms/Services/LegacySqlCatalog.cs b/Keps.WinForms/Services/LegacySqlCatalog.cs new file mode 100644 index 0000000..87babe2 --- /dev/null +++ b/Keps.WinForms/Services/LegacySqlCatalog.cs @@ -0,0 +1,29 @@ +namespace Keps.WinForms.Services +{ + /// + /// 레거시 데이터베이스에 사용하는 SQL 문자열 상수 모음입니다. + /// + public static class LegacySqlCatalog + { + /// 프로그램 버전 조회. + public const string ProgramVersion = "SELECT ver FROM information WHERE program = 'keps'"; + /// 활성화된 선거 연월 목록 조회. + public const string ElectionYears = "SELECT ele_ym FROM elections WHERE flag = '1' ORDER BY ele_ym DESC"; + /// 실 데이터에 존재하는 선거명 목록. + public const string DistinctRealElections = "SELECT 선거명 FROM poll_data GROUP BY 선거명 ORDER BY 선거명"; + /// 특정 선거명에 대한 시도명 목록. + public const string DistinctRealAreas = "SELECT 시도명 FROM poll_data WHERE 선거명 = @electionName GROUP BY 시도명 ORDER BY 시도명"; + /// 특정 선거/지역에 대한 군집 최대값 목록. + public const string RealClusterMax = "SELECT 군집최대값 FROM 군집별비율 WHERE 선거명 = @electionName AND 시도명 = @areaName GROUP BY 군집최대값 ORDER BY 군집최대값"; + /// 특정 선거/지역/군집최대값에 대한 군집별 비율. + public const string RealClusterRatio = "SELECT 군집, 비율 FROM 군집별비율 WHERE 선거명 = @electionName AND 시도명 = @areaName AND 군집최대값 = @clusterMax ORDER BY 군집"; + /// 군집별 투표구 수 카운트 쿼리 템플릿. + public const string RealClusterCountTemplate = "SELECT COUNT(*) FROM poll_data WHERE ele_ym = @electionName AND 비고 = 1 AND 선거명 = @electionName AND 시도명 = @areaName AND [군집{0}개] = @clusterNo"; + /// 후보자 이름/번호 조회. + public const string RealCandidateNames = "SELECT cand_no, cand_name FROM cand_name WHERE ele_ym = @electionName ORDER BY CAST(cand_no AS int), cand_no"; + /// 실 데이터에서 투표구 행들을 조회하는 템플릿(군집 컬럼 개수 가변). + public const string RealPollingRowsTemplate = + "SELECT ele_ym, 선거명, 시도명, 선거구명, 시군구, 읍면동, 투표구명, t_유권자수, 선거인수, 투표인수, cand, cand_ratio, 후보별득표수계, 투표소_중복여부, 관할구역, 건물명, 주소1, 비고_기타, [군집{0}개] AS 선택군집 " + + "FROM poll_data WHERE ele_ym = @electionName AND 비고 = 1 AND 선거명 = @electionName AND 시도명 = @areaName"; + } +} diff --git a/Keps.WinForms/Services/LookupService.cs b/Keps.WinForms/Services/LookupService.cs new file mode 100644 index 0000000..e36f55c --- /dev/null +++ b/Keps.WinForms/Services/LookupService.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using Keps.WinForms.Infrastructure; +using Keps.WinForms.Models; + +namespace Keps.WinForms.Services +{ + /// + /// 조회(룩업)용 데이터 로딩을 담당하는 서비스입니다. + /// + public sealed class LookupService + { + private readonly SqlConnectionFactory _connectionFactory; + + /// + /// 조회 관련 서비스 인스턴스를 생성합니다. + /// + /// DB 연결을 제공하는 팩토리. + public LookupService(SqlConnectionFactory connectionFactory) + { + _connectionFactory = connectionFactory; + } + + /// + /// 실 데이터(poll_data)에 존재하는 선거명 목록을 조회합니다. + /// + /// 선거명 문자열 목록. + public List LoadRealElections() + { + return LoadSingleColumnList(LegacySqlCatalog.DistinctRealElections, null); + } + + /// + /// 특정 선거명에 대해 시도명(지역) 목록을 조회합니다. + /// + /// 선거명(예: "201804" 등). + /// 지역명 문자열 목록. + public List LoadRealAreas(string electionName) + { + SqlParameter[] parameters = { new SqlParameter("@electionName", electionName) }; + return LoadSingleColumnList(LegacySqlCatalog.DistinctRealAreas, parameters); + } + + /// + /// 특정 선거명과 지역에 대해 설정된 군집 최대값 목록을 조회합니다. + /// + /// 선거명. + /// 지역명. + /// 군집 최대값 정수 목록. + public List LoadRealClusterMaxList(string electionName, string areaName) + { + List result = new List(); + + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(LegacySqlCatalog.RealClusterMax, connection)) + { + command.Parameters.AddWithValue("@electionName", electionName); + command.Parameters.AddWithValue("@areaName", areaName); + + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(Convert.ToInt32(reader[0])); + } + } + } + + return result; + } + + /// + /// 특정 선거명에 대해 후보자 옵션 목록을 조회합니다. + /// + /// 선거명 또는 선거 번호. + /// 후보자 표시 이름과 키를 담은 옵션 목록. + public List LoadCandidateOptions(string electionName) + { + List result = new List(); + + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(LegacySqlCatalog.RealCandidateNames, connection)) + { + int electionNo; + if (int.TryParse(electionName, out electionNo)) + { + command.Parameters.AddWithValue("@electionName", electionNo); + } + else + { + command.Parameters.AddWithValue("@electionName", electionName); + } + + try + { + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + string candNo = Convert.ToString(reader["cand_no"]); + string candName = Convert.ToString(reader["cand_name"]); + result.Add(new CandidateOption + { + Key = "cand_ratio_" + candNo, + DisplayName = candName + "(" + candNo + ")" + }); + } + } + } + catch + { + } + } + + result.Add(new CandidateOption { Key = "투표인수", DisplayName = "투표인수" }); + return result; + } + + /// + /// 단일 컬럼을 반환하는 쿼리를 실행하여 문자열 목록으로 변환합니다. + /// + /// 실행할 SQL. + /// 바인딩할 매개변수 배열. null일 수 있습니다. + /// 첫 번째 컬럼 값을 문자열로 담은 목록. + private List LoadSingleColumnList(string sql, SqlParameter[] parameters) + { + List result = new List(); + + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(sql, connection)) + { + if (parameters != null) + { + command.Parameters.AddRange(parameters); + } + + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(Convert.ToString(reader[0])); + } + } + } + + return result; + } + } +} diff --git a/Keps.WinForms/Services/SamplingService.cs b/Keps.WinForms/Services/SamplingService.cs new file mode 100644 index 0000000..38e11f4 --- /dev/null +++ b/Keps.WinForms/Services/SamplingService.cs @@ -0,0 +1,711 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using Keps.WinForms.Infrastructure; +using Keps.WinForms.Models; + +namespace Keps.WinForms.Services +{ + /// + /// 표본 추출(실 데이터 기준) 관련 로직을 제공하는 서비스입니다. + /// + public sealed class SamplingService + { + private sealed class CandidateMeta + { + public string Name { get; set; } + public string VoteKey { get; set; } + public string RatioKey { get; set; } + } + + private readonly SqlConnectionFactory _connectionFactory; + + /// + /// 표본 추출 서비스 인스턴스를 생성합니다. + /// + /// DB 연결을 제공하는 팩토리. + public SamplingService(SqlConnectionFactory connectionFactory) + { + _connectionFactory = connectionFactory; + } + + /// + /// 실 추출 화면 구성을 위한 초기 컨텍스트를 로드합니다. + /// + /// 선거명 또는 연월. + /// 시도명. + /// 군집(층) 최대 개수. + /// 자동/수동 행과 정렬 옵션을 포함한 컨텍스트. + public RealScenarioContext LoadRealScenario(string electionName, string areaName, int clusterMax) + { + List rows = new List(); + + using (SqlConnection connection = _connectionFactory.Open()) + { + Dictionary ratioMap = new Dictionary(); + using (SqlCommand ratioCommand = new SqlCommand(LegacySqlCatalog.RealClusterRatio, connection)) + { + ratioCommand.Parameters.AddWithValue("@electionName", electionName); + ratioCommand.Parameters.AddWithValue("@areaName", areaName); + ratioCommand.Parameters.AddWithValue("@clusterMax", clusterMax); + + using (SqlDataReader reader = ratioCommand.ExecuteReader()) + { + while (reader.Read()) + { + ratioMap[Convert.ToInt32(reader["군집"])] = Convert.ToDecimal(reader["비율"]); + } + } + } + + for (int clusterNo = 1; clusterNo <= clusterMax; clusterNo++) + { + string countSql = string.Format(LegacySqlCatalog.RealClusterCountTemplate, clusterMax); + int count = 0; + using (SqlCommand countCommand = new SqlCommand(countSql, connection)) + { + countCommand.Parameters.AddWithValue("@electionName", electionName); + countCommand.Parameters.AddWithValue("@areaName", areaName); + countCommand.Parameters.AddWithValue("@clusterNo", clusterNo); + object scalar = countCommand.ExecuteScalar(); + count = scalar == null || scalar == DBNull.Value ? 0 : Convert.ToInt32(scalar); + } + + decimal ratio = ratioMap.ContainsKey(clusterNo) ? ratioMap[clusterNo] : 0m; + rows.Add(new ClusterSummaryRow + { + ClusterNo = clusterNo, + ClusterLabel = clusterNo + " 층", + PollingPlaceCount = count, + Ratio = ratio, + SampleCount = 0 + }); + } + } + + LookupService lookupService = new LookupService(_connectionFactory); + return new RealScenarioContext + { + AutoRows = CloneRows(rows), + ManualRows = CloneRows(rows), + SortOptions = lookupService.LoadCandidateOptions(electionName) + }; + } + + /// + /// 군집별 비율에 따라 총 표본 수를 자동 배분합니다(소수점 버림 후 잔여는 앞쪽부터 1개씩 할당). + /// + /// 군집 비율 및 개수 정보를 담은 행 목록. + /// 전체 표본 수. + /// 배분된 표본 수가 채워진 새 목록. + public List AllocateAutoSampleCounts(List rows, int totalSampleCount) + { + List result = CloneRows(rows); + if (rows == null || rows.Count == 0 || totalSampleCount <= 0) + { + return result; + } + + int assigned = 0; + List> sampleTu = new List>(); + for (int i = 0; i < result.Count; i++) + { + decimal exact = totalSampleCount * result[i].Ratio; + int floor = (int)Math.Floor(exact); + result[i].SampleCount = floor; + assigned += floor; + sampleTu.Add(new Tuple(result[i], exact - floor, i + 1)); + } + + int remaining = totalSampleCount - assigned; + /*********************************버그 살림*************************************/ + if (remaining > 0) + { + if (sampleTu.Count >= 2 && sampleTu[0].Item2 < sampleTu[1].Item2) + { + Tuple temp = sampleTu[0]; + sampleTu[0] = sampleTu[1]; + sampleTu[1] = temp; + } + + for (int i = 0; i < sampleTu.Count && remaining > 0; i++) + { + sampleTu[i].Item1.SampleCount += 1; + remaining--; + } + } + /*********************************버그 살림*************************************/ + + /*********************************정상 구동*************************************/ + /* + if (remaining > 0) + { + var ranked = sampleTu + .OrderByDescending(x => x.Item2) // 소수부 큰 순 + .ThenBy(x => x.Item1.ClusterNo) // 동률이면 군집번호 작은 순 + .ToList(); + + for (int i = 0; i < ranked.Count && remaining > 0; i++) + { + ranked[i].Item1.SampleCount += 1; + remaining--; + } + } + */ + /*********************************정상 구동*************************************/ + + return result; + } + + /// + /// 실 데이터에서 군집별 표본을 등간격으로 추출하고, 관련 산출물(보정, 검증, 모집단 목록)을 생성합니다. + /// + /// 선거명 또는 연월. + /// 시도명. + /// 군집(층) 최대 개수. + /// 정렬 기준 키(예: "투표인수" 또는 cand_ratio_*). + /// 정렬 기준 표시 이름. + /// 내림차순 여부. + /// 군집별 배분 정보(표본 수 포함). + /// 등간격 오프셋(양수/음수). + /// 오프셋 설명 문자열. + /// 자동 배분으로 생성되었는지 여부. + /// 실 추출 결과 DTO. + public RealExtractionResult RunRealExtraction( + string electionName, + string areaName, + int clusterMax, + string sortKey, + string sortDisplayName, + bool descending, + List allocationRows, + int signedOffset, + string offsetDescription, + bool isAutoAllocation) + { + List allRows = LoadRealPollingRows(electionName, areaName, clusterMax); + List candidateMeta = LoadCandidateMeta(electionName, allRows); + List extractedRows = new List(); + List populationRows = new List(); + List extractedSourceRows = new List(); + + foreach (ClusterSummaryRow allocation in allocationRows.OrderBy(x => x.ClusterNo)) + { + List clusterRows = allRows.Where(x => x.ClusterValue == allocation.ClusterNo).ToList(); + clusterRows = descending + ? clusterRows.OrderByDescending(x => x.GetSortValue(sortKey)).ThenBy(x => x.EupMyeonDong).ThenBy(x => GetPollingPlaceSortValue(x.PollingPlaceNo)).ThenBy(x => x.PollingPlaceNo).ToList() + : clusterRows.OrderBy(x => x.GetSortValue(sortKey)).ThenBy(x => x.EupMyeonDong).ThenBy(x => GetPollingPlaceSortValue(x.PollingPlaceNo)).ThenBy(x => x.PollingPlaceNo).ToList(); + + int interval; + int startPosition; + List extractIds = SelectLegacyExtractIds(clusterRows.Count, allocation.SampleCount, signedOffset, out interval, out startPosition); + HashSet selectedPositions = new HashSet(extractIds); + + for (int i = 0; i < clusterRows.Count; i++) + { + int originalOrder = i + 1; + PollingPlaceRecord row = clusterRows[i]; + populationRows.Add(CreateExtractionRow(row, allocation.ClusterNo, originalOrder, originalOrder, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), selectedPositions.Contains(originalOrder), selectedPositions.Contains(originalOrder))); + } + + for (int i = 0; i < extractIds.Count; i++) + { + int extractId = extractIds[i]; + if (extractId < 1 || extractId > clusterRows.Count) + { + continue; + } + + PollingPlaceRecord row = clusterRows[extractId - 1]; + extractedSourceRows.Add(row); + extractedRows.Add(CreateExtractionRow(row, allocation.ClusterNo, i + 1, extractId, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), true, true)); + } + } + + List candidateNames = candidateMeta.Select(x => x.Name).ToList(); + List candidateVoteKeys = candidateMeta.Select(x => x.VoteKey).ToList(); + List candidateRatioKeys = candidateMeta.Select(x => x.RatioKey).ToList(); + + return new RealExtractionResult + { + CandidateNames = candidateNames, + CandidateVoteKeys = candidateVoteKeys, + CandidateRatioKeys = candidateRatioKeys, + ExtractedRows = extractedRows.OrderBy(x => x.ClusterNo).ThenBy(x => x.ClusterOrder).ToList(), + PopulationRows = populationRows.OrderBy(x => x.ClusterNo).ThenBy(x => x.OriginalOrder).ToList(), + AdjustmentRows = BuildAdjustmentRows(extractedRows), + VerificationRows = BuildVerificationRows(allRows, extractedSourceRows, allocationRows, candidateMeta), + ClusterMax = clusterMax, + TotalSampleCount = allocationRows.Sum(x => x.SampleCount), + IsAutoAllocation = isAutoAllocation, + SortDisplayName = sortDisplayName, + SortDescending = descending, + OffsetDescription = offsetDescription + }; + } + + /// + /// 실 데이터 테이블에서 투표구 행들을 조회하여 도메인 모델로 변환합니다. + /// + /// 선거명 또는 연월. + /// 시도명. + /// 군집(층) 최대 개수(동적 군집 컬럼 선택에 사용). + /// 조회된 투표구 원시 행 목록. + private List LoadRealPollingRows(string electionName, string areaName, int clusterMax) + { + List result = new List(); + string sql = string.Format(LegacySqlCatalog.RealPollingRowsTemplate, clusterMax); + + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(sql, connection)) + { + command.Parameters.AddWithValue("@electionName", electionName); + command.Parameters.AddWithValue("@areaName", areaName); + + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + PollingPlaceRecord row = new PollingPlaceRecord(); + row.ElectionName = Convert.ToString(reader["선거명"]); + row.AreaName = Convert.ToString(reader["시도명"]); + row.DistrictName = Convert.ToString(reader["선거구명"]); + row.SiGunGu = Convert.ToString(reader["시군구"]); + row.EupMyeonDong = Convert.ToString(reader["읍면동"]); + row.PollingPlaceNo = Convert.ToString(reader["투표구명"]); + row.PollingPlaceName = row.EupMyeonDong + " " + row.PollingPlaceNo + "투"; + row.ClusterValue = reader["선택군집"] == DBNull.Value ? 0 : Convert.ToInt32(reader["선택군집"]); + row.EligibleVoterCount = reader["t_유권자수"] == DBNull.Value ? 0 : Convert.ToInt32(reader["t_유권자수"]); + row.ElectorateCount = reader["선거인수"] == DBNull.Value ? 0 : Convert.ToInt32(reader["선거인수"]); + row.VoteCount = reader["투표인수"] == DBNull.Value ? 0 : Convert.ToInt32(reader["투표인수"]); + row.TotalCandidateVoteCount = reader["후보별득표수계"] == DBNull.Value ? 0 : Convert.ToInt32(reader["후보별득표수계"]); + row.DuplicateFlag = Convert.ToString(reader["투표소_중복여부"]); + row.BuildingName = Convert.ToString(reader["건물명"]); + row.Address1 = Convert.ToString(reader["주소1"]); + row.AreaDetail = Convert.ToString(reader["관할구역"]); + row.Note = Convert.ToString(reader["비고_기타"]); + row.CandidateVotes = JsonHelper.ParseDecimalMap(Convert.ToString(reader["cand"])); + row.CandidateRatios = JsonHelper.ParseDecimalMap(Convert.ToString(reader["cand_ratio"])); + result.Add(row); + } + } + } + + return result; + } + + /// + /// 후보자 메타 정보(표시명, 득표/비율 키)를 DB 또는 데이터에서 유추하여 생성합니다. + /// + /// 선거명 또는 연월. + /// 후보자 득표/비율 정보가 포함될 수 있는 모집단 행 목록. + /// 정렬용 후보 메타 정보 목록. + private List LoadCandidateMeta(string electionName, List rows) + { + List result = new List(); + + using (SqlConnection connection = _connectionFactory.Open()) + using (SqlCommand command = new SqlCommand(LegacySqlCatalog.RealCandidateNames, connection)) + { + int electionNo; + if (int.TryParse(electionName, out electionNo)) + { + command.Parameters.AddWithValue("@electionName", electionNo); + } + else + { + command.Parameters.AddWithValue("@electionName", electionName); + } + + try + { + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + string candNo = Convert.ToString(reader["cand_no"]); + string candName = Convert.ToString(reader["cand_name"]); + if (string.IsNullOrWhiteSpace(candNo)) + { + continue; + } + + int candNoValue; + if (!int.TryParse(candNo, out candNoValue)) + { + continue; + } + + result.Add(new CandidateMeta + { + Name = string.IsNullOrWhiteSpace(candName) ? "cand_" + candNoValue : candName, + VoteKey = "cand_" + candNoValue, + RatioKey = "cand_ratio_" + candNoValue + }); + } + } + } + catch + { + } + } + + result = result + .GroupBy(x => x.VoteKey) + .Select(x => x.First()) + .OrderBy(x => ExtractCandidateKeyNumber(x.VoteKey)) + .ToList(); + + if (result.Count == 0) + { + List keys = rows + .Where(x => x.CandidateVotes != null) + .SelectMany(x => x.CandidateVotes.Keys) + .Distinct() + .OrderBy(ExtractCandidateKeyNumber) + .ToList(); + + foreach (string key in keys) + { + result.Add(new CandidateMeta + { + Name = key, + VoteKey = key, + RatioKey = key.Replace("cand_", "cand_ratio_") + }); + } + } + + return result.Take(3).ToList(); + } + + /// + /// 투표구 원시 행을 보고서/엑셀 출력용 추출 행 DTO로 변환합니다. + /// + /// 원본 투표구 행. + /// 군집 번호. + /// 군집 내 추출 순번. + /// 정렬 모집단 상의 원래 순번. + /// 등간격 간격. + /// 등간격 시작 위치. + /// 오프셋 설명. + /// 정렬 기준 값. + /// 자동 추출 여부. + /// 보정 반영 여부. + /// 변환된 추출 행. + private static ExtractionRow CreateExtractionRow(PollingPlaceRecord row, int clusterNo, int clusterOrder, int originalOrder, int interval, int startPosition, string offsetDescription, decimal sortValue, bool isAutoSelected, bool isAdjustedSelected) + { + return new ExtractionRow + { + ClusterNo = clusterNo, + ClusterOrder = clusterOrder, + OriginalOrder = originalOrder, + StartPosition = startPosition, + Interval = interval, + OffsetDescription = offsetDescription, + AreaName = row.AreaName, + DistrictName = row.DistrictName, + SiGunGu = row.SiGunGu, + EupMyeonDong = row.EupMyeonDong, + PollingPlaceName = row.PollingPlaceName, + PollingPlaceNo = row.PollingPlaceNo, + EligibleVoterCount = row.EligibleVoterCount, + ElectorateCount = row.ElectorateCount, + VoteCount = row.VoteCount, + TotalCandidateVoteCount = row.TotalCandidateVoteCount, + DuplicateFlag = row.DuplicateFlag, + BuildingName = row.BuildingName, + Address1 = row.Address1, + Note = row.Note, + SortValue = sortValue, + IsAutoSelected = isAutoSelected, + IsAdjustedSelected = isAdjustedSelected, + CandidateVotes = row.CandidateVotes == null ? new Dictionary() : new Dictionary(row.CandidateVotes), + CandidateRatios = row.CandidateRatios == null ? new Dictionary() : new Dictionary(row.CandidateRatios) + }; + } + + /// + /// 레거시 규칙에 맞춰 등간격 추출 ID 목록을 계산합니다. + /// + /// 모집단 크기(정렬된 투표구 수). + /// 추출할 표본 수. + /// 시작 위치 보정값(양수면 뒤로, 음수면 앞으로 이동). + /// 계산된 등간격 간격(출력). + /// 계산된 시작 위치(출력). + /// 1부터 시작하는 추출 대상 인덱스 목록. + private static List SelectLegacyExtractIds(int totalCount, int sampleCount, int signedOffset, out int interval, out int startPosition) + { + List extractIds = new List(); + interval = 1; + startPosition = 1; + + if (totalCount <= 0 || sampleCount <= 0) + { + return extractIds; + } + + if (sampleCount >= totalCount) + { + for (int i = 1; i <= totalCount; i++) + { + extractIds.Add(i); + } + return extractIds; + } + + interval = (int)Math.Floor((decimal)totalCount / sampleCount); + if (interval <= 0) + { + interval = 1; + } + + int start = interval / 2; + int endPoint = start + (interval * (sampleCount - 1)); + int x1 = totalCount - endPoint; + int x2 = start - 1; + start = Convert.ToInt32(Math.Round((x1 + x2) / 2d, 0, MidpointRounding.AwayFromZero)); + start += signedOffset; + + if (start <= 0) + { + start = 1; + } + if (start > totalCount) + { + start = totalCount; + } + + startPosition = start; + int current = start; + while (current <= totalCount && extractIds.Count < sampleCount) + { + extractIds.Add(current); + current += interval; + } + + return extractIds; + } + + /// + /// 추출된 표본 행들에서 보정 내역(원래 순번/보정 순번)을 생성합니다. + /// + /// 최종 추출 표본 행 목록. + /// 보정 내역 행 목록. + private static List BuildAdjustmentRows(List extractedRows) + { + return extractedRows + .OrderBy(x => x.ClusterNo) + .ThenBy(x => x.OriginalOrder) + .Select(x => new AdjustmentRow + { + ClusterNo = x.ClusterNo, + ExtractId = x.OriginalOrder, + AdjustId = null + }) + .ToList(); + } + + /// + /// 추출 표본과 모집단을 비교하여 요약 검증 지표(가중 오차, 군집 내 오차 등)를 계산합니다. + /// + /// 모집단(전체) 원시 행 목록. + /// 추출된 원시 행 목록. + /// 군집별 비율 및 표본 수 정보. + /// 후보자 메타 정보(표시명/키). + /// 검증 요약 행 목록. + private static List BuildVerificationRows( + List populationRows, + List extractedRows, + List allocationRows, + List candidateMeta) + { + List result = new List(); + while (candidateMeta.Count < 3) + { + candidateMeta.Add(new CandidateMeta { Name = "후보" + (candidateMeta.Count + 1), VoteKey = "cand_" + (candidateMeta.Count + 1), RatioKey = "cand_ratio_" + (candidateMeta.Count + 1) }); + } + + decimal totalActual1 = Round1(ComputeCandidateRatioExact(populationRows, candidateMeta[0].VoteKey)); + decimal totalActual2 = Round1(ComputeCandidateRatioExact(populationRows, candidateMeta[1].VoteKey)); + decimal totalActual3 = Round1(ComputeCandidateRatioExact(populationRows, candidateMeta[2].VoteKey)); + + decimal totalExtractedWeighted1 = 0m; + decimal totalExtractedWeighted2 = 0m; + decimal totalExtractedWeighted3 = 0m; + + foreach (ClusterSummaryRow allocation in allocationRows.OrderBy(x => x.ClusterNo)) + { + List clusterPopulation = populationRows.Where(x => x.ClusterValue == allocation.ClusterNo).ToList(); + List clusterExtracted = extractedRows.Where(x => x.ClusterValue == allocation.ClusterNo).ToList(); + + decimal clusterExtracted1 = Round1(ComputeCandidateRatioExact(clusterExtracted, candidateMeta[0].VoteKey)); + decimal clusterExtracted2 = Round1(ComputeCandidateRatioExact(clusterExtracted, candidateMeta[1].VoteKey)); + decimal clusterExtracted3 = Round1(ComputeCandidateRatioExact(clusterExtracted, candidateMeta[2].VoteKey)); + decimal clusterActual1 = Round1(Round2(ComputeCandidateRatioExact(clusterPopulation, candidateMeta[0].VoteKey))); + decimal clusterActual2 = Round1(Round2(ComputeCandidateRatioExact(clusterPopulation, candidateMeta[1].VoteKey))); + decimal clusterActual3 = Round1(Round2(ComputeCandidateRatioExact(clusterPopulation, candidateMeta[2].VoteKey))); + + totalExtractedWeighted1 += allocation.Ratio * ComputeCandidateRatioExact(clusterExtracted, candidateMeta[0].VoteKey); + totalExtractedWeighted2 += allocation.Ratio * ComputeCandidateRatioExact(clusterExtracted, candidateMeta[1].VoteKey); + totalExtractedWeighted3 += allocation.Ratio * ComputeCandidateRatioExact(clusterExtracted, candidateMeta[2].VoteKey); + + decimal overallError1 = Round1(clusterExtracted1 - totalActual1); + decimal overallError2 = Round1(clusterExtracted2 - totalActual2); + decimal overallError3 = Round1(clusterExtracted3 - totalActual3); + decimal inClusterError1 = Round1(clusterExtracted1 - clusterActual1); + decimal inClusterError2 = Round1(clusterExtracted2 - clusterActual2); + decimal inClusterError3 = Round1(clusterExtracted3 - clusterActual3); + + result.Add(new VerificationSummaryRow + { + RowLabel = allocation.ClusterNo + " 층", + ClusterRatio = allocation.Ratio, + SampleCount = allocation.SampleCount, + Extracted1 = clusterExtracted1, + Extracted2 = clusterExtracted2, + Extracted3 = clusterExtracted3, + Actual1 = clusterActual1, + Actual2 = clusterActual2, + Actual3 = clusterActual3, + WeightedError1 = overallError1, + WeightedError2 = overallError2, + WeightedError3 = overallError3, + WeightedErrorSum = Round1(Math.Abs(overallError1) + Math.Abs(overallError2) + Math.Abs(overallError3)), + InClusterError1 = inClusterError1, + InClusterError2 = inClusterError2, + InClusterError3 = inClusterError3, + InClusterErrorSum = Round1(Math.Abs(inClusterError1) + Math.Abs(inClusterError2) + Math.Abs(inClusterError3)) + }); + } + + decimal totalExtracted1 = Round1(totalExtractedWeighted1); + decimal totalExtracted2 = Round1(totalExtractedWeighted2); + decimal totalExtracted3 = Round1(totalExtractedWeighted3); + decimal totalOverallError1 = Round1(totalExtracted1 - totalActual1); + decimal totalOverallError2 = Round1(totalExtracted2 - totalActual2); + decimal totalOverallError3 = Round1(totalExtracted3 - totalActual3); + + result.Insert(0, new VerificationSummaryRow + { + RowLabel = "전체", + ClusterRatio = 1m, + SampleCount = allocationRows.Sum(x => x.SampleCount), + Extracted1 = totalExtracted1, + Extracted2 = totalExtracted2, + Extracted3 = totalExtracted3, + Actual1 = totalActual1, + Actual2 = totalActual2, + Actual3 = totalActual3, + WeightedError1 = totalOverallError1, + WeightedError2 = totalOverallError2, + WeightedError3 = totalOverallError3, + WeightedErrorSum = Round1(Math.Abs(totalOverallError1) + Math.Abs(totalOverallError2) + Math.Abs(totalOverallError3)), + InClusterError1 = 0m, + InClusterError2 = 0m, + InClusterError3 = 0m, + InClusterErrorSum = 0m + }); + + return result; + } + + /// + /// 지정한 후보 득표수 키에 대한 실제 비율(%)을 계산합니다. + /// + /// 대상 행 목록. + /// 득표수 조회 키(예: cand_1). + /// 득표율(%), 분모가 0이면 0. + private static decimal ComputeCandidateRatioExact(List rows, string voteKey) + { + if (rows == null || rows.Count == 0 || string.IsNullOrWhiteSpace(voteKey)) + { + return 0m; + } + + decimal total = rows.Sum(x => (decimal)x.TotalCandidateVoteCount); + if (total <= 0m) + { + return 0m; + } + + decimal vote = 0m; + foreach (PollingPlaceRecord row in rows) + { + if (row.CandidateVotes != null && row.CandidateVotes.ContainsKey(voteKey)) + { + vote += row.CandidateVotes[voteKey]; + } + } + + return (vote / total) * 100m; + } + + + /// + /// 소수점 둘째 자리에서 반올림(away from zero)합니다. + /// + /// 반올림할 값. + /// 소수 둘째 자리 반올림 값. + private static decimal Round2(decimal value) + { + return Math.Round(value, 2, MidpointRounding.AwayFromZero); + } + + /// + /// 투표구 번호 문자열에서 정렬용 숫자 값을 추출합니다(예: "제1투" → 1). + /// + /// 투표구 번호 문자열. + /// 정렬용 정수 값. 추출 실패 시 매우 큰 값으로 취급합니다. + private static int GetPollingPlaceSortValue(string pollingPlaceNo) + { + int value; + return int.TryParse(pollingPlaceNo, out value) ? value : int.MaxValue; + } + + /// + /// 후보 득표 키에서 번호를 추출합니다(예: "cand_3" → 3). 실패 시 큰 값 반환. + /// + /// 후보 득표 키. + /// 숫자 값. 파싱 실패 시 int.MaxValue. + private static int ExtractCandidateKeyNumber(string key) + { + if (string.IsNullOrWhiteSpace(key)) + { + return int.MaxValue; + } + + string text = new string(key.Where(char.IsDigit).ToArray()); + int value; + return int.TryParse(text, out value) ? value : int.MaxValue; + } + + /// + /// 소수점 첫째 자리에서 반올림(away from zero)합니다. + /// + /// 반올림할 값. + /// 소수 첫째 자리 반올림 값. + private static decimal Round1(decimal value) + { + return Math.Round(value, 1, MidpointRounding.AwayFromZero); + } + + /// + /// 군집 요약 행 목록을 얕은 복사하여 변경 부작용을 방지합니다. + /// + /// 원본 행 목록. + /// 복제된 새 목록. + private static List CloneRows(List rows) + { + return rows.Select(x => new ClusterSummaryRow + { + ClusterNo = x.ClusterNo, + ClusterLabel = x.ClusterLabel, + PollingPlaceCount = x.PollingPlaceCount, + Ratio = x.Ratio, + SampleCount = x.SampleCount + }).ToList(); + } + } +} diff --git a/KepsMigration.sln b/KepsMigration.sln new file mode 100644 index 0000000..6e3cdad --- /dev/null +++ b/KepsMigration.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Keps.WinForms", "Keps.WinForms\Keps.WinForms.csproj", "{A2FE4BAE-AF5E-4F9F-9A64-09F43B9DB17B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A2FE4BAE-AF5E-4F9F-9A64-09F43B9DB17B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A2FE4BAE-AF5E-4F9F-9A64-09F43B9DB17B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A2FE4BAE-AF5E-4F9F-9A64-09F43B9DB17B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A2FE4BAE-AF5E-4F9F-9A64-09F43B9DB17B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/keps_db_free_migration_notes.md b/keps_db_free_migration_notes.md new file mode 100644 index 0000000..1890a2c --- /dev/null +++ b/keps_db_free_migration_notes.md @@ -0,0 +1,104 @@ +# keps 마이그레이션 메모 (DB 스키마 없이 진행 기준) + +## 결론 +- `FarPoint Spread`는 `DataGridView`로 대체해도 됨 +- 현재 업로드된 `00.투표구추출용.22대총선_전체(0310)_수정.xlsx` 기준으로 + - 엑셀 파서 + - 후보 컬럼 추출 + - 메모리 기반 집계 + - DataGridView 표시 + - 최종 추출 결과 내보내기 + 는 **DB 스키마 없이도 진행 가능** +- 다만 아래 기능은 DB 또는 과거 데이터가 있어야 완전 재현 가능 + - 프로그램 버전 체크 / FTP 업데이트 + - `elections` 목록 조회 + - 과거 선거 기반 시뮬레이션(Source/Target 비교) + - 기존 SQL 기반 결과와 100% 동일성 검증 + +## 업로드된 엑셀에서 확인한 점 +- 사용 가능한 시트: `85개` (`Sheet1`은 빈 시트) +- 대부분의 시트 헤더는 동일 +- 후보 컬럼은 `투표수` 다음부터 `계` 직전까지 존재 +- 확인된 대표 헤더: + - 선거구명 + - 시군구 + - 층코드 + - 층명 + - 읍면동 + - 투표소 + - 전체 선거인수 + - 투표수 + - 이재명 ~ 김민찬 + - 계 + - 건물명 + - 투표소주소 + - 비고 + - 중복여부 + - 투표구 관할구역 +- 일부 시트는 뒤쪽에 빈 컬럼이 더 붙어 있음 -> 파서에서 무시 가능 + +## DB 없이 먼저 만들 수 있는 범위 +1. 메인 MDI + WinForms UI +2. 엑셀 파일 선택 / 시트 선택 / 전체 일괄 파싱 +3. 후보명 자동 인식 (헤더 기반) +4. 내부 모델 생성 +5. 군집 계산 로직 C# 이식 +6. 자동 추출 / 수동 보정 UI +7. 결과 Excel/CSV 저장 + +## DB 없이 진행 시 권장 구조 +- `ExcelParser` +- `PollRow` +- `CandidateVote` +- `ClusterCalculator` +- `SamplingEngine` +- `ResultExporter` +- `AppSettings.json` (DB/FTP 대신 로컬 설정) + +## 나중에 찾으면 좋은 DB 테이블 우선순위 +### 1순위 (있으면 좋음) +#### poll_data +원본 VB6에서 확인된 핵심 컬럼: +- ele_ym +- 선거명 +- 시도명 +- 선거구명 +- 시군구 +- 읍면동 +- 투표구명 +- t_유권자수 +- 선거인수 +- 투표인수 +- cand +- cand_ratio +- 후보별득표수계 +- 투표소_중복여부 +- 관할구역 +- 건물명 +- 주소1 +- 비고_기타 +- 군집1개 ~ 군집7개 +- 비고 + +### 2순위 (시뮬레이션 재현 시 필요) +- poll_data_simul_2017 또는 poll_data_simul_{year} +- cand_name / cand_name_{year} +- 군집별비율 / 군집별비율_simul +- 시군구별유권자수와군집 / 시군구별유권자수와군집_simul + +### 3순위 (없어도 진행 가능) +- elections +- information + +## 기대 결과를 모를 때 검증 포인트 +- 프로젝트 zip 내부 `prt` 폴더의 기존 출력 xls 파일들을 회귀 검증 기준으로 활용 가능 +- 즉, 결과 규칙을 모르더라도 + - 같은 입력 + - 같은 조건 + - 기존 출력과 비교 + 방식으로 맞춰갈 수 있음 + +## 실무 권장 방향 +- 1차 목표: **DB 없는 독립형 WinForms 버전** 완성 +- 2차 목표: 나중에 DB 구조를 찾으면 저장/조회 기능만 추가 +- 이렇게 가야 현재처럼 내부 지식이 끊긴 레거시 프로젝트를 가장 안전하게 살릴 수 있음