260512_01_ENH: 조정 ID로 2차 추출 및 검증 적용, 조정 ID 복붙 기능 추가 및 복수개의 층은 탭으로 분리

This commit is contained in:
2026-05-12 10:32:40 +09:00
parent c652d4ad43
commit b5e0c664c8
3 changed files with 341 additions and 39 deletions

View File

@@ -13,6 +13,28 @@ namespace Keps.WinForms.Forms
{
public sealed partial class RealExtractionForm : Form
{
private sealed class AdjustmentGridView : DataGridView
{
public Action<DataGridView> 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<ExtractionRow> _resultRows = new BindingList<ExtractionRow>();
private RealExtractionResult _lastResult;
private List<string> _candidateNames = new List<string>();
private readonly Dictionary<int, DataGridView> _adjustmentGrids = new Dictionary<int, DataGridView>();
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<ClusterSummaryRow>(_samplingService.AllocateAutoSampleCounts(context.AutoRows, totalSamples));
_autoRows = new BindingList<ClusterSummaryRow>(hasTotalSamples
? _samplingService.AllocateAutoSampleCounts(context.AutoRows, totalSamples)
: context.AutoRows.Select(CloneRow).ToList());
_manualRows = new BindingList<ClusterSummaryRow>(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<AdjustmentRow>(BuildDefaultAdjustmentRows(GetWorkingRows()));
_verificationRows = new BindingList<VerificationSummaryRow>();
_resultRows = new BindingList<ExtractionRow>();
_lastResult = null;
ClearExtractionState(false);
BindGridSources();
ApplyVerificationHeaders();
UpdateOffsetRange();
@@ -210,6 +236,7 @@ namespace Keps.WinForms.Forms
return;
}
EndAdjustmentEdit();
List<ClusterSummaryRow> 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<AdjustmentRow> 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<string>()).ToList();
_resultRows = new BindingList<ExtractionRow>(_lastResult.ExtractedRows ?? new List<ExtractionRow>());
_adjustmentRows = new BindingList<AdjustmentRow>(_lastResult.AdjustmentRows ?? new List<AdjustmentRow>());
@@ -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<AdjustmentRow>)_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<ClusterSummaryRow>(_preparedContext.AutoRows.Select(CloneRow).ToList());
_manualRows = new BindingList<ClusterSummaryRow>(_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<AdjustmentRow> GetAdjustmentRowsForExtraction()
{
List<AdjustmentRow> rows = GetAdjustmentRows();
if (_lastResult == null || !rows.Any(x => x.AdjustId != null))
{
return null;
}
return rows;
}
private List<AdjustmentRow> GetAdjustmentRows()
{
EndAdjustmentEdit();
return _adjustmentRows == null
? new List<AdjustmentRow>()
: _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<AdjustmentRow>();
_verificationRows = new BindingList<VerificationSummaryRow>();
_resultRows = new BindingList<ExtractionRow>();
_lastResult = null;
_candidateNames = new List<string>();
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<int, AdjustmentRow> 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<AdjustmentRow>(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()