diff --git a/Keps.WinForms/Forms/RealExtractionForm.Designer.cs b/Keps.WinForms/Forms/RealExtractionForm.Designer.cs index 5d05648..e100372 100644 --- a/Keps.WinForms/Forms/RealExtractionForm.Designer.cs +++ b/Keps.WinForms/Forms/RealExtractionForm.Designer.cs @@ -42,7 +42,7 @@ namespace Keps.WinForms.Forms 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.TabControl _tabAdjustment; private System.Windows.Forms.GroupBox _grpVerification; private System.Windows.Forms.DataGridView _gridVerification; private System.Windows.Forms.GroupBox _grpResult; @@ -98,7 +98,7 @@ namespace Keps.WinForms.Forms 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._tabAdjustment = new System.Windows.Forms.TabControl(); this._grpVerification = new System.Windows.Forms.GroupBox(); this._gridVerification = new System.Windows.Forms.DataGridView(); this._grpResult = new System.Windows.Forms.GroupBox(); @@ -121,7 +121,6 @@ namespace Keps.WinForms.Forms 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(); @@ -327,7 +326,7 @@ namespace Keps.WinForms.Forms this._btnExtract.Name = "_btnExtract"; this._btnExtract.Size = new System.Drawing.Size(270, 30); this._btnExtract.TabIndex = 10; - this._btnExtract.Text = "2. 추출 및 검즘-등간 정수"; + this._btnExtract.Text = "2. 추출 및 검증-등간 정수"; this._btnExtract.UseVisualStyleBackColor = true; // // _outerSplit @@ -528,7 +527,7 @@ namespace Keps.WinForms.Forms // // _grpAdjustment // - this._grpAdjustment.Controls.Add(this._gridAdjustment); + this._grpAdjustment.Controls.Add(this._tabAdjustment); 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); @@ -538,13 +537,16 @@ namespace Keps.WinForms.Forms this._grpAdjustment.TabStop = false; this._grpAdjustment.Text = "수동 조정시 층별 ID 조정"; // - // _gridAdjustment + // _tabAdjustment // - 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; + this._tabAdjustment.Dock = System.Windows.Forms.DockStyle.Fill; + this._tabAdjustment.ItemSize = new System.Drawing.Size(42, 18); + this._tabAdjustment.Location = new System.Drawing.Point(3, 20); + this._tabAdjustment.Name = "_tabAdjustment"; + this._tabAdjustment.SelectedIndex = 0; + this._tabAdjustment.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; + this._tabAdjustment.Size = new System.Drawing.Size(203, 321); + this._tabAdjustment.TabIndex = 0; // // _grpVerification // @@ -635,7 +637,6 @@ namespace Keps.WinForms.Forms 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); diff --git a/Keps.WinForms/Forms/RealExtractionForm.cs b/Keps.WinForms/Forms/RealExtractionForm.cs index 9fd3588..97b45fa 100644 --- a/Keps.WinForms/Forms/RealExtractionForm.cs +++ b/Keps.WinForms/Forms/RealExtractionForm.cs @@ -13,6 +13,28 @@ namespace Keps.WinForms.Forms { public sealed partial class RealExtractionForm : Form { + private sealed class AdjustmentGridView : DataGridView + { + public Action PasteRequested { get; set; } + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (keyData == (Keys.Control | Keys.C)) + { + CopyAdjustmentSelection(this); + return true; + } + + if (keyData == (Keys.Control | Keys.V)) + { + PasteRequested?.Invoke(this); + return true; + } + + return base.ProcessCmdKey(ref msg, keyData); + } + } + private SqlConnectionFactory _connectionFactory; private LookupService _lookupService; private SamplingService _samplingService; @@ -26,6 +48,7 @@ namespace Keps.WinForms.Forms private BindingList _resultRows = new BindingList(); private RealExtractionResult _lastResult; private List _candidateNames = new List(); + private readonly Dictionary _adjustmentGrids = new Dictionary(); public RealExtractionForm() { @@ -182,21 +205,24 @@ namespace Keps.WinForms.Forms string election = _cmbElection.SelectedItem.ToString(); string area = _cmbArea.SelectedItem.ToString(); int clusterMax = Convert.ToInt32(_cmbClusterMax.SelectedItem); - int totalSamples = GetTotalSamples(); + int totalSamples; + bool hasTotalSamples = TryGetTotalSamples(out totalSamples); RealScenarioContext context = _samplingService.LoadRealScenario(election, area, clusterMax); _preparedContext = context; - _autoRows = new BindingList(_samplingService.AllocateAutoSampleCounts(context.AutoRows, totalSamples)); + _autoRows = new BindingList(hasTotalSamples + ? _samplingService.AllocateAutoSampleCounts(context.AutoRows, totalSamples) + : context.AutoRows.Select(CloneRow).ToList()); _manualRows = new BindingList(context.ManualRows.Select(CloneRow).ToList()); - for (int i = 0; i < _manualRows.Count && i < _autoRows.Count; i++) + if (hasTotalSamples) { - _manualRows[i].SampleCount = _autoRows[i].SampleCount; + 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; + ClearExtractionState(false); BindGridSources(); ApplyVerificationHeaders(); UpdateOffsetRange(); @@ -210,6 +236,7 @@ namespace Keps.WinForms.Forms return; } + EndAdjustmentEdit(); List workingRows = GetWorkingRows(); if (workingRows.Count == 0 || workingRows.All(x => x.SampleCount <= 0)) { @@ -224,9 +251,10 @@ namespace Keps.WinForms.Forms string sortKey = option == null ? "투표인수" : option.Key; bool descending = _cmbSortDirection.SelectedIndex == 0; int offset = GetSignedOffset(); + List adjustmentRows = GetAdjustmentRowsForExtraction(); SetProgress(15, "최종 추출 실행 중..."); - _lastResult = _samplingService.RunRealExtraction(election, area, clusterMax, sortKey, option == null ? "투표인수" : option.DisplayName, descending, workingRows, offset, GetOffsetDescription(), _rdoAuto.Checked); + _lastResult = _samplingService.RunRealExtraction(election, area, clusterMax, sortKey, option == null ? "투표인수" : option.DisplayName, descending, workingRows, offset, GetOffsetDescription(), _rdoAuto.Checked, adjustmentRows); _candidateNames = (_lastResult.CandidateNames ?? new List()).ToList(); _resultRows = new BindingList(_lastResult.ExtractedRows ?? new List()); _adjustmentRows = new BindingList(_lastResult.AdjustmentRows ?? new List()); @@ -250,7 +278,8 @@ namespace Keps.WinForms.Forms dialog.FileName = string.Format("층화_후_득표율_기준_{0}-{1}_최종_{2:yyyyMMdd_HHmmss}.xlsx", _cmbElection.SelectedItem, _cmbArea.SelectedItem, DateTime.Now); if (dialog.ShowDialog(this) == DialogResult.OK) { - var adjustList = ((BindingList)_gridAdjustment.DataSource).ToList(); + EndAdjustmentEdit(); + var adjustList = GetAdjustmentRows(); _excelReportService.ExportRealExtractionWorkbook(dialog.FileName, _cmbElection.SelectedItem.ToString(), _cmbArea.SelectedItem.ToString(), GetWorkingRows(), _lastResult, adjustList); MessageBox.Show(this, "엑셀 저장 완료" + Environment.NewLine + dialog.FileName, "완료", MessageBoxButtons.OK, MessageBoxIcon.Information); } @@ -265,11 +294,16 @@ namespace Keps.WinForms.Forms return; } + ClearExtractionState(false); if (_rdoAuto.Checked) { int totalSamples; if (!TryGetTotalSamples(out totalSamples)) { + _autoRows = new BindingList(_preparedContext.AutoRows.Select(CloneRow).ToList()); + _manualRows = new BindingList(_preparedContext.ManualRows.Select(CloneRow).ToList()); + BindGridSources(); + UpdateOffsetRange(); return; } @@ -287,6 +321,10 @@ namespace Keps.WinForms.Forms BindGridSources(); } + else + { + BindGridSources(); + } UpdateOffsetRange(); } @@ -399,7 +437,7 @@ namespace Keps.WinForms.Forms MessageBox.Show(this, "군집수를 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } - if (!TryGetTotalSamples(out _)) + if (false && !TryGetTotalSamples(out _)) { MessageBox.Show(this, "총 표본 수를 입력하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); _numTotalSamples.Focus(); @@ -408,6 +446,33 @@ namespace Keps.WinForms.Forms return true; } + private List GetAdjustmentRowsForExtraction() + { + List rows = GetAdjustmentRows(); + if (_lastResult == null || !rows.Any(x => x.AdjustId != null)) + { + return null; + } + + return rows; + } + + private List GetAdjustmentRows() + { + EndAdjustmentEdit(); + return _adjustmentRows == null + ? new List() + : _adjustmentRows + .Where(x => x != null) + .Select(x => new AdjustmentRow + { + ClusterNo = x.ClusterNo, + ExtractId = x.ExtractId, + AdjustId = x.AdjustId + }) + .ToList(); + } + private int GetTotalSamples() { int totalSamples; @@ -461,15 +526,77 @@ namespace Keps.WinForms.Forms return result; } + private void ClearExtractionState(bool bindSources) + { + _adjustmentRows = new BindingList(); + _verificationRows = new BindingList(); + _resultRows = new BindingList(); + _lastResult = null; + _candidateNames = new List(); + + if (bindSources) + { + BindGridSources(); + ApplyVerificationHeaders(); + } + } + private void BindGridSources() { _gridAuto.DataSource = _autoRows; _gridManual.DataSource = _manualRows; - _gridAdjustment.DataSource = _adjustmentRows; + BindAdjustmentTabs(); _gridVerification.DataSource = _verificationRows; _gridResult.DataSource = _resultRows; } + private void BindAdjustmentTabs() + { + EndAdjustmentEdit(); + int selectedCluster = 0; + if (_tabAdjustment.SelectedTab != null && _tabAdjustment.SelectedTab.Tag is int) + { + selectedCluster = (int)_tabAdjustment.SelectedTab.Tag; + } + + _tabAdjustment.TabPages.Clear(); + _adjustmentGrids.Clear(); + + if (_adjustmentRows == null || _adjustmentRows.Count == 0) + { + return; + } + + foreach (IGrouping group in _adjustmentRows.GroupBy(x => x.ClusterNo).OrderBy(x => x.Key)) + { + TabPage page = new TabPage(group.Key + "층"); + page.Tag = group.Key; + + AdjustmentGridView grid = new AdjustmentGridView(); + grid.Dock = DockStyle.Fill; + grid.PasteRequested = PasteAdjustmentRows; + ConfigureAdjustmentGrid(grid); + grid.DataSource = new BindingList(group.OrderBy(x => x.ExtractId).ToList()); + + page.Controls.Add(grid); + _tabAdjustment.TabPages.Add(page); + _adjustmentGrids[group.Key] = grid; + + if (selectedCluster == group.Key) + { + _tabAdjustment.SelectedTab = page; + } + } + } + + private void EndAdjustmentEdit() + { + foreach (DataGridView grid in _adjustmentGrids.Values) + { + grid.EndEdit(); + } + } + private void SetProgress(int percent, string text) { _progressBar.Value = Math.Max(0, Math.Min(100, percent)); @@ -481,7 +608,6 @@ namespace Keps.WinForms.Forms { ConfigureGridBase(_gridAuto); ConfigureGridBase(_gridManual); - ConfigureGridBase(_gridAdjustment); ConfigureGridBase(_gridVerification); ConfigureGridBase(_gridResult); @@ -500,6 +626,7 @@ namespace Keps.WinForms.Forms grid.RowHeadersVisible = false; grid.SelectionMode = DataGridViewSelectionMode.CellSelect; grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; + grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; grid.BackgroundColor = System.Drawing.Color.White; grid.BorderStyle = BorderStyle.FixedSingle; } @@ -516,11 +643,117 @@ namespace Keps.WinForms.Forms 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 }); + _tabAdjustment.TabPages.Clear(); + _adjustmentGrids.Clear(); + } + + private void ConfigureAdjustmentGrid(DataGridView grid) + { + ConfigureGridBase(grid); + grid.AutoGenerateColumns = false; + grid.Columns.Clear(); + grid.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ClusterNo", HeaderText = "층", ReadOnly = true, Width = 45 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "ExtractId", HeaderText = "추출ID", ReadOnly = true, Width = 70 }); + grid.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "AdjustId", HeaderText = "조정ID", Width = 70 }); + grid.AllowUserToResizeRows = false; + grid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; + grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; + grid.RowTemplate.Height = 22; + grid.KeyDown += AdjustmentGrid_KeyDown; + } + + private void AdjustmentGrid_KeyDown(object sender, KeyEventArgs e) + { + if (e.Control && e.KeyCode == Keys.V) + { + PasteAdjustmentRows(sender as DataGridView); + e.Handled = true; + e.SuppressKeyPress = true; + } + } + + private static void PasteAdjustmentRows(DataGridView grid) + { + if (grid == null || grid.CurrentCell == null || !Clipboard.ContainsText()) + { + return; + } + + string text = Clipboard.GetText(); + if (string.IsNullOrWhiteSpace(text)) + { + return; + } + + int adjustColumnIndex = FindColumnIndex(grid, "AdjustId"); + if (adjustColumnIndex < 0) + { + return; + } + + int startRow = grid.CurrentCell.RowIndex; + string[] lines = text.Replace("\r\n", "\n").Replace('\r', '\n').TrimEnd('\n').Split('\n'); + for (int i = 0; i < lines.Length && startRow + i < grid.Rows.Count; i++) + { + string[] cells = lines[i].Split('\t'); + string value = cells.Length == 0 ? string.Empty : cells[cells.Length == 1 ? 0 : cells.Length - 1]; + int? adjustId = ParseNullableInt(value); + AdjustmentRow row = grid.Rows[startRow + i].DataBoundItem as AdjustmentRow; + if (row != null) + { + row.AdjustId = adjustId; + } + grid.Rows[startRow + i].Cells[adjustColumnIndex].Value = adjustId; + } + + grid.NotifyCurrentCellDirty(true); + grid.CommitEdit(DataGridViewDataErrorContexts.Commit); + grid.EndEdit(); + CurrencyManager manager = grid.BindingContext[grid.DataSource] as CurrencyManager; + if (manager != null) + { + manager.EndCurrentEdit(); + } + + grid.Refresh(); + } + + private static void CopyAdjustmentSelection(DataGridView grid) + { + if (grid == null || grid.SelectedCells.Count == 0) + { + return; + } + + DataObject data = grid.GetClipboardContent(); + if (data != null) + { + Clipboard.SetDataObject(data, true); + } + } + + private static int FindColumnIndex(DataGridView grid, string dataPropertyName) + { + foreach (DataGridViewColumn column in grid.Columns) + { + if (column.DataPropertyName == dataPropertyName) + { + return column.Index; + } + } + + return -1; + } + + private static int? ParseNullableInt(string value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + int result; + return int.TryParse(value.Trim(), out result) ? (int?)result : null; } private void ConfigureVerificationGrid() diff --git a/Keps.WinForms/Services/SamplingService.cs b/Keps.WinForms/Services/SamplingService.cs index 2ef9f38..ae01686 100644 --- a/Keps.WinForms/Services/SamplingService.cs +++ b/Keps.WinForms/Services/SamplingService.cs @@ -182,13 +182,16 @@ namespace Keps.WinForms.Services List workingRows, int signedOffset, string offsetDescription, - bool isAutoAllocation) + bool isAutoAllocation, + List adjustmentRows = null) { List allRows = LoadRealPollingRows(electionName, areaName, clusterMax); List candidateMeta = LoadCandidateMeta(electionName, allRows); List extractedRows = new List(); List populationRows = new List(); List extractedSourceRows = new List(); + Dictionary adjustmentMap = BuildAdjustmentMap(adjustmentRows); + bool hasAdjustments = adjustmentMap.Count > 0; foreach (ClusterSummaryRow workingRow in workingRows.OrderBy(x => x.ClusterNo)) { @@ -201,25 +204,46 @@ namespace Keps.WinForms.Services int startPosition; List extractIds = SelectLegacyExtractIds(clusterRows.Count, workingRow.SampleCount, signedOffset, out interval, out startPosition); HashSet selectedPositions = new HashSet(extractIds); + HashSet adjustedPositions = new HashSet(); + List finalExtractIds = new List(); + foreach (int extractId in extractIds) + { + int finalExtractId; + if (adjustmentMap.TryGetValue(BuildAdjustmentKey(workingRow.ClusterNo, extractId), out finalExtractId)) + { + if (finalExtractId < 1 || finalExtractId > clusterRows.Count) + { + throw new InvalidOperationException( + string.Format("{0}층 조정ID {1}이 유효한 범위를 벗어났습니다. 1부터 {2} 사이로 입력하세요.", workingRow.ClusterNo, finalExtractId, clusterRows.Count)); + } + } + else + { + finalExtractId = extractId; + } + + finalExtractIds.Add(finalExtractId); + adjustedPositions.Add(finalExtractId); + } for (int i = 0; i < clusterRows.Count; i++) { int originalOrder = i + 1; PollingPlaceRecord row = clusterRows[i]; - populationRows.Add(CreateExtractionRow(row, workingRow.ClusterNo, originalOrder, originalOrder, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), selectedPositions.Contains(originalOrder), selectedPositions.Contains(originalOrder))); + populationRows.Add(CreateExtractionRow(row, workingRow.ClusterNo, originalOrder, originalOrder, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), selectedPositions.Contains(originalOrder), hasAdjustments ? adjustedPositions.Contains(originalOrder) : selectedPositions.Contains(originalOrder))); } - for (int i = 0; i < extractIds.Count; i++) + for (int i = 0; i < finalExtractIds.Count; i++) { - int extractId = extractIds[i]; - if (extractId < 1 || extractId > clusterRows.Count) + int finalExtractId = finalExtractIds[i]; + if (finalExtractId < 1 || finalExtractId > clusterRows.Count) { continue; } - PollingPlaceRecord row = clusterRows[extractId - 1]; + PollingPlaceRecord row = clusterRows[finalExtractId - 1]; extractedSourceRows.Add(row); - extractedRows.Add(CreateExtractionRow(row, workingRow.ClusterNo, i + 1, extractId, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), true, true)); + extractedRows.Add(CreateExtractionRow(row, workingRow.ClusterNo, i + 1, finalExtractId, interval, startPosition, offsetDescription, row.GetSortValue(sortKey), selectedPositions.Contains(finalExtractId), true)); } } @@ -234,7 +258,7 @@ namespace Keps.WinForms.Services 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), + AdjustmentRows = hasAdjustments ? CloneAdjustmentRows(adjustmentRows) : BuildAdjustmentRows(extractedRows), VerificationRows = BuildVerificationRows(allRows, extractedSourceRows, workingRows, candidateMeta), ClusterMax = clusterMax, TotalSampleCount = workingRows.Sum(x => x.SampleCount), @@ -245,6 +269,51 @@ namespace Keps.WinForms.Services }; } + private static Dictionary BuildAdjustmentMap(List adjustmentRows) + { + Dictionary result = new Dictionary(); + if (adjustmentRows == null) + { + return result; + } + + foreach (AdjustmentRow row in adjustmentRows) + { + if (row == null || row.AdjustId == null) + { + continue; + } + + result[BuildAdjustmentKey(row.ClusterNo, row.ExtractId)] = row.AdjustId.Value; + } + + return result; + } + + private static string BuildAdjustmentKey(int clusterNo, int extractId) + { + return clusterNo.ToString() + ":" + extractId.ToString(); + } + + private static List CloneAdjustmentRows(List adjustmentRows) + { + if (adjustmentRows == null) + { + return new List(); + } + + return adjustmentRows + .OrderBy(x => x.ClusterNo) + .ThenBy(x => x.ExtractId) + .Select(x => new AdjustmentRow + { + ClusterNo = x.ClusterNo, + ExtractId = x.ExtractId, + AdjustId = x.AdjustId + }) + .ToList(); + } + /// /// 실 데이터 테이블에서 투표구 행들을 조회하여 도메인 모델로 변환합니다. /// @@ -638,7 +707,6 @@ namespace Keps.WinForms.Services return (vote / total) * 100m; } - /// /// 소수점 둘째 자리에서 반올림(away from zero)합니다. ///