first commit
This commit is contained in:
17
Keps.WinForms/App.config
Normal file
17
Keps.WinForms/App.config
Normal file
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<appSettings>
|
||||
|
||||
<!-- 우선순위 2: 직접 입력 -->
|
||||
<add key="DbServer" value="10.10.11.7,20022" />
|
||||
<add key="DbName" value="keps" />
|
||||
<add key="DbUser" value="sa" />
|
||||
<add key="DbPassword" value="it#51304" />
|
||||
|
||||
<!-- 시뮬레이션용 기본 테이블 suffix -->
|
||||
<add key="SimulationYearSuffix" value="2017" />
|
||||
|
||||
<!-- FTP 업데이터는 별도 전환 권장 -->
|
||||
<add key="FtpEnabled" value="false" />
|
||||
</appSettings>
|
||||
</configuration>
|
||||
0
Keps.WinForms/Docs/RealExtraction_Flow_3Steps.md
Normal file
0
Keps.WinForms/Docs/RealExtraction_Flow_3Steps.md
Normal file
44
Keps.WinForms/Docs/VB_FinalExtraction_ActualFlow.md
Normal file
44
Keps.WinForms/Docs/VB_FinalExtraction_ActualFlow.md
Normal file
@@ -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를 반영한 재추출 처리
|
||||
- 반복 추출(시작/종료/간격) 실제 실행 로직
|
||||
193
Keps.WinForms/Forms/DataInputForm.Designer.cs
generated
Normal file
193
Keps.WinForms/Forms/DataInputForm.Designer.cs
generated
Normal file
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
152
Keps.WinForms/Forms/DataInputForm.cs
Normal file
152
Keps.WinForms/Forms/DataInputForm.cs
Normal file
@@ -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<string> 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<ImportProgress> progress = new Progress<ImportProgress>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
123
Keps.WinForms/Forms/DataInputForm.resx
Normal file
123
Keps.WinForms/Forms/DataInputForm.resx
Normal file
@@ -0,0 +1,123 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="_folderDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
</root>
|
||||
68
Keps.WinForms/Forms/MainMdiForm.Designer.cs
generated
Normal file
68
Keps.WinForms/Forms/MainMdiForm.Designer.cs
generated
Normal file
@@ -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();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
104
Keps.WinForms/Forms/MainMdiForm.cs
Normal file
104
Keps.WinForms/Forms/MainMdiForm.cs
Normal file
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
123
Keps.WinForms/Forms/MainMdiForm.resx
Normal file
123
Keps.WinForms/Forms/MainMdiForm.resx
Normal file
@@ -0,0 +1,123 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="_menu.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
</root>
|
||||
648
Keps.WinForms/Forms/RealExtractionForm.Designer.cs
generated
Normal file
648
Keps.WinForms/Forms/RealExtractionForm.Designer.cs
generated
Normal file
@@ -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);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
546
Keps.WinForms/Forms/RealExtractionForm.cs
Normal file
546
Keps.WinForms/Forms/RealExtractionForm.cs
Normal file
@@ -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<ClusterSummaryRow> _autoRows = new BindingList<ClusterSummaryRow>();
|
||||
private BindingList<ClusterSummaryRow> _manualRows = new BindingList<ClusterSummaryRow>();
|
||||
private BindingList<AdjustmentRow> _adjustmentRows = new BindingList<AdjustmentRow>();
|
||||
private BindingList<VerificationSummaryRow> _verificationRows = new BindingList<VerificationSummaryRow>();
|
||||
private BindingList<ExtractionRow> _resultRows = new BindingList<ExtractionRow>();
|
||||
private RealExtractionResult _lastResult;
|
||||
private List<string> _candidateNames = new List<string>();
|
||||
|
||||
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<ClusterSummaryRow>(_samplingService.AllocateAutoSampleCounts(context.AutoRows, Convert.ToInt32(_numTotalSamples.Value)));
|
||||
_manualRows = new BindingList<ClusterSummaryRow>(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<AdjustmentRow>(BuildDefaultAdjustmentRows(GetWorkingRows()));
|
||||
_verificationRows = new BindingList<VerificationSummaryRow>();
|
||||
_resultRows = new BindingList<ExtractionRow>();
|
||||
_lastResult = null;
|
||||
BindGridSources();
|
||||
ApplyVerificationHeaders();
|
||||
UpdateOffsetRange();
|
||||
SetProgress(100, "사전 단계 완료");
|
||||
}
|
||||
|
||||
private void BtnExtract_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (!ValidateScenarioInputs() || _samplingService == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
List<ClusterSummaryRow> 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<string>()).ToList();
|
||||
_resultRows = new BindingList<ExtractionRow>(_lastResult.ExtractedRows ?? new List<ExtractionRow>());
|
||||
_adjustmentRows = new BindingList<AdjustmentRow>(_lastResult.AdjustmentRows ?? new List<AdjustmentRow>());
|
||||
_verificationRows = new BindingList<VerificationSummaryRow>(_lastResult.VerificationRows ?? new List<VerificationSummaryRow>());
|
||||
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<ClusterSummaryRow>(_samplingService.AllocateAutoSampleCounts(_preparedContext.AutoRows, Convert.ToInt32(_numTotalSamples.Value)));
|
||||
|
||||
if (_manualRows == null || _manualRows.Count != _autoRows.Count)
|
||||
{
|
||||
_manualRows = new BindingList<ClusterSummaryRow>(_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<ClusterSummaryRow> 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<ClusterSummaryRow> 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<AdjustmentRow> BuildDefaultAdjustmentRows(List<ClusterSummaryRow> rows)
|
||||
{
|
||||
List<AdjustmentRow> result = new List<AdjustmentRow>();
|
||||
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<string> names = (_candidateNames ?? new List<string>()).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];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
120
Keps.WinForms/Forms/RealExtractionForm.resx
Normal file
120
Keps.WinForms/Forms/RealExtractionForm.resx
Normal file
@@ -0,0 +1,120 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
</root>
|
||||
33
Keps.WinForms/Infrastructure/DesignTimeHelper.cs
Normal file
33
Keps.WinForms/Infrastructure/DesignTimeHelper.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace Keps.WinForms.Infrastructure
|
||||
{
|
||||
internal static class DesignTimeHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 현재 실행 컨텍스트가 디자이너(디자인 타임)인지 여부를 판단합니다.
|
||||
/// WinForms 디자이너나 XAML 디자이너 프로세스에서 실행 중이면 <c>true</c>를 반환합니다.
|
||||
/// </summary>
|
||||
/// <param name="control">디자인 모드를 추가로 판별할 대상 컨트롤. null이면 프로세스 이름만으로 판별합니다.</param>
|
||||
/// <returns>디자인 타임이면 <c>true</c>, 런타임이면 <c>false</c>.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
143
Keps.WinForms/Infrastructure/ExcelEpplusReader.cs
Normal file
143
Keps.WinForms/Infrastructure/ExcelEpplusReader.cs
Normal file
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 지정된 경로의 Excel 파일(.xlsx/.xlsm)을 열고 내부 패키지를 초기화합니다.
|
||||
/// </summary>
|
||||
/// <param name="path">읽어들일 Excel 파일 경로.</param>
|
||||
/// <exception cref="FileNotFoundException">파일이 존재하지 않을 때 발생합니다.</exception>
|
||||
/// <exception cref="NotSupportedException">지원하지 않는 확장자일 때 발생합니다.</exception>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 현재 열려 있는 Excel 패키지의 모든 워크시트를 순회 가능한 형태로 반환합니다.
|
||||
/// </summary>
|
||||
/// <returns><see cref="ExcelSheet"/> 열거 시퀀스.</returns>
|
||||
/// <exception cref="InvalidOperationException">Open이 선행되지 않은 경우 발생합니다.</exception>
|
||||
public IEnumerable<ExcelSheet> ReadSheets()
|
||||
{
|
||||
if (_package == null)
|
||||
{
|
||||
throw new InvalidOperationException("먼저 Open을 호출해야 합니다.");
|
||||
}
|
||||
|
||||
foreach (ExcelWorksheet worksheet in _package.Workbook.Worksheets)
|
||||
{
|
||||
if (worksheet == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
yield return new ExcelSheet(worksheet);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 내부 Excel 패키지 리소스를 해제합니다.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_package != null)
|
||||
{
|
||||
_package.Dispose();
|
||||
_package = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ExcelSheet
|
||||
{
|
||||
private readonly ExcelWorksheet _worksheet;
|
||||
|
||||
/// <summary>
|
||||
/// EPPlus의 <see cref="ExcelWorksheet"/>를 래핑하는 시트를 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="worksheet">원본 워크시트 인스턴스.</param>
|
||||
public ExcelSheet(ExcelWorksheet worksheet)
|
||||
{
|
||||
_worksheet = worksheet;
|
||||
}
|
||||
|
||||
public string Name
|
||||
{
|
||||
get { return _worksheet.Name; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 지정한 행/열 위치의 셀 값을 반환합니다. 범위를 벗어나면 null을 반환합니다.
|
||||
/// </summary>
|
||||
/// <param name="row">1부터 시작하는 행 번호.</param>
|
||||
/// <param name="column">1부터 시작하는 열 번호.</param>
|
||||
/// <returns>셀 값 또는 범위 밖일 경우 null.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 첫 번째 행(헤더 행)에서 주어진 헤더 텍스트와 일치하는 열의 인덱스를 찾습니다.
|
||||
/// </summary>
|
||||
/// <param name="header">찾을 헤더 텍스트.</param>
|
||||
/// <param name="maxColumn">검색을 수행할 최대 열 번호(1 기반).</param>
|
||||
/// <returns>일치하는 열 번호(1 기반). 찾지 못하면 -1.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
60
Keps.WinForms/Infrastructure/JsonHelper.cs
Normal file
60
Keps.WinForms/Infrastructure/JsonHelper.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Keps.WinForms.Infrastructure
|
||||
{
|
||||
public static class JsonHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 문자열 사전(IDictionary<string, string>)을 JSON 문자열로 직렬화합니다.
|
||||
/// </summary>
|
||||
/// <param name="values">직렬화할 키-값 쌍 컬렉션. null이면 빈 사전으로 간주합니다.</param>
|
||||
/// <returns>JSON 형식의 문자열.</returns>
|
||||
public static string Serialize(IDictionary<string, string> values)
|
||||
{
|
||||
return JsonConvert.SerializeObject(values ?? new Dictionary<string, string>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON 문자열을 문자열 사전(Dictionary<string, string>)으로 파싱합니다.
|
||||
/// </summary>
|
||||
/// <param name="json">입력 JSON 문자열. null/공백이면 빈 사전을 반환합니다.</param>
|
||||
/// <returns>파싱된 문자열 사전. 파싱 실패 시 빈 사전.</returns>
|
||||
public static Dictionary<string, string> ParseStringMap(string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
|
||||
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json)
|
||||
?? new Dictionary<string, string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON 문자열을 decimal 값의 사전(Dictionary<string, decimal>)으로 파싱합니다.
|
||||
/// 내부적으로 문자열 사전을 먼저 파싱한 뒤, 각 값을 decimal로 변환합니다.
|
||||
/// </summary>
|
||||
/// <param name="json">입력 JSON 문자열.</param>
|
||||
/// <returns>키는 문자열, 값은 decimal인 사전. 숫자 변환 실패 시 해당 값은 0m으로 설정됩니다.</returns>
|
||||
public static Dictionary<string, decimal> ParseDecimalMap(string json)
|
||||
{
|
||||
Dictionary<string, string> raw = ParseStringMap(json);
|
||||
Dictionary<string, decimal> result = new Dictionary<string, decimal>();
|
||||
|
||||
foreach (KeyValuePair<string, string> pair in raw)
|
||||
{
|
||||
decimal value;
|
||||
if (!decimal.TryParse(pair.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
|
||||
{
|
||||
value = 0m;
|
||||
}
|
||||
|
||||
result[pair.Key] = value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
146
Keps.WinForms/Infrastructure/LegacyConnectionResolver.cs
Normal file
146
Keps.WinForms/Infrastructure/LegacyConnectionResolver.cs
Normal file
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// App.config 및 레거시 VB6 소스에서 DB 연결 정보를 해석하여 반환합니다.
|
||||
/// 필수 항목이 누락된 경우 예외를 발생시킵니다.
|
||||
/// </summary>
|
||||
/// <returns>해석된 <see cref="LegacyConnectionSettings"/> 인스턴스.</returns>
|
||||
/// <exception cref="InvalidOperationException">연결 정보를 완성할 수 없을 때 발생합니다.</exception>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// App.config의 <c>LegacySourceFolder</c>에 지정된 VB6 원본 폴더에서 연결 정보를 추출하려 시도합니다.
|
||||
/// </summary>
|
||||
/// <returns>완전한 연결 정보가 추출되면 해당 설정, 아니면 null.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VB6 모듈 소스(.bas) 문자열에서 연결 문자열 구성 요소를 정규식으로 추출합니다.
|
||||
/// </summary>
|
||||
/// <param name="source">VB6 원본 소스 코드 텍스트.</param>
|
||||
/// <returns>
|
||||
/// 추출된 값으로 구성된 <see cref="LegacyConnectionSettings"/>.
|
||||
/// 필수 항목을 충족하지 못하면 null.
|
||||
/// </returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 주어진 여러 정규식 패턴을 순서대로 적용하여 첫 번째로 매칭되는 그룹 값을 반환합니다.
|
||||
/// </summary>
|
||||
/// <param name="source">검색할 원본 문자열.</param>
|
||||
/// <param name="patterns">적용할 정규식 패턴 목록. 각 패턴은 그룹 1에 원하는 값을 캡처해야 합니다.</param>
|
||||
/// <returns>첫 매칭의 그룹 1 값. 매칭이 없으면 null.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// App.config의 AppSettings에서 키 값을 읽고, 비어있으면 기본값을 반환합니다.
|
||||
/// </summary>
|
||||
/// <param name="key">설정 키 이름.</param>
|
||||
/// <param name="defaultValue">키가 없거나 값이 비어있을 때 사용할 기본값.</param>
|
||||
/// <returns>설정값 또는 기본값.</returns>
|
||||
private static string GetAppSetting(string key, string defaultValue = null)
|
||||
{
|
||||
string value = ConfigurationManager.AppSettings[key];
|
||||
return string.IsNullOrWhiteSpace(value) ? defaultValue : value;
|
||||
}
|
||||
}
|
||||
}
|
||||
25
Keps.WinForms/Infrastructure/LegacyConnectionSettings.cs
Normal file
25
Keps.WinForms/Infrastructure/LegacyConnectionSettings.cs
Normal file
@@ -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; }
|
||||
|
||||
/// <summary>
|
||||
/// DB 연결 문자열을 구성하기 위한 필수 항목들이 모두 채워졌는지 확인합니다.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// <c>Server</c>, <c>Database</c>, <c>UserId</c>, <c>Password</c>가 모두 비어있지 않으면 <c>true</c>,
|
||||
/// 그 외에는 <c>false</c>.
|
||||
/// </returns>
|
||||
public bool IsComplete()
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(Server)
|
||||
&& !string.IsNullOrWhiteSpace(Database)
|
||||
&& !string.IsNullOrWhiteSpace(UserId)
|
||||
&& !string.IsNullOrWhiteSpace(Password);
|
||||
}
|
||||
}
|
||||
}
|
||||
170
Keps.WinForms/Infrastructure/LegacyValueHelper.cs
Normal file
170
Keps.WinForms/Infrastructure/LegacyValueHelper.cs
Normal file
@@ -0,0 +1,170 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Keps.WinForms.Infrastructure
|
||||
{
|
||||
/// <summary>
|
||||
/// DB에서 로드한 레거시 데이터를 정제하고 타입 변환하는 헬퍼 클래스
|
||||
/// </summary>
|
||||
public static class LegacyValueHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 객체 값을 문자열로 변환하면서 null/DBNull 체크 및 공백 제거
|
||||
/// </summary>
|
||||
/// <param name="value">변환할 객체 값. null이거나 DBNull.Value이면 빈 문자열 반환</param>
|
||||
/// <returns>정제된 문자열. 양쪽 공백이 제거되고 null은 빈 문자열로 반환</returns>
|
||||
public static string CleanString(object value)
|
||||
{
|
||||
if (value == null || value == DBNull.Value)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return Convert.ToString(value).Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 객체 값을 정수로 변환
|
||||
/// 쉼표 제거, 부동소수점 값은 소수점 버림 처리, 변환 실패시 0 반환
|
||||
/// </summary>
|
||||
/// <param name="value">변환할 객체 값. null이거나 DBNull.Value이면 0 반환</param>
|
||||
/// <returns>
|
||||
/// 정수로 변환된 값
|
||||
/// 부동소수점은 Math.Truncate로 소수점 이하 버림 처리
|
||||
/// 변환 실패시 기본값 0 반환
|
||||
/// </returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 객체 값을 decimal(십진수)로 변환
|
||||
/// 쉼표 제거, 변환 실패시 0 반환
|
||||
/// </summary>
|
||||
/// <param name="value">변환할 객체 값. null이거나 DBNull.Value이면 0m 반환</param>
|
||||
/// <returns>decimal으로 변환된 값. 변환 실패시 기본값 0m 반환</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 선거구명(District)에서 지역명(Area)을 추출
|
||||
/// "[지역명_세부구분]" 또는 "지역명.세부구분" 형태에서 지역명만 추출
|
||||
/// </summary>
|
||||
/// <param name="districtName">
|
||||
/// 선거구명 문자열
|
||||
/// 형식 예시: "[강원_강릉시]", "강원.강릉시", "강원_강릉시" 등
|
||||
/// null이거나 공백이면 빈 문자열 반환
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// 추출된 지역명
|
||||
/// 양쪽 대괄호 제거 후 언더스코어(_)나 점(.)을 기준으로 앞부분만 반환
|
||||
/// 구분자가 없으면 전체 정규화된 문자열 반환
|
||||
/// </returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 투표구명(PollingPlaceName)에서 투표구 번호를 추출
|
||||
/// "제5투표소", "5 투표소", "제 5 투표" 등의 형식에서 숫자만 추출
|
||||
/// </summary>
|
||||
/// <param name="pollingPlaceName">
|
||||
/// 투표구명 문자열
|
||||
/// 형식 예시: "제1투표소", "제5투표소", "10투표소", "투표소" 등
|
||||
/// null이거나 공백이면 "0" 반환
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// 추출된 투표구 번호 문자열
|
||||
/// 정규표현식 "제?\s*(\d+)\s*투"로 매칭된 숫자 부분 반환
|
||||
/// 패턴 미매칭시 투표소로 끝나면 "1" 반환
|
||||
/// 모두 실패시 "0" 반환
|
||||
/// </returns>
|
||||
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";
|
||||
}
|
||||
}
|
||||
}
|
||||
47
Keps.WinForms/Infrastructure/SqlConnectionFactory.cs
Normal file
47
Keps.WinForms/Infrastructure/SqlConnectionFactory.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System.Data.SqlClient;
|
||||
|
||||
namespace Keps.WinForms.Infrastructure
|
||||
{
|
||||
public sealed class SqlConnectionFactory
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
|
||||
/// <summary>
|
||||
/// 주어진 레거시 DB 연결 설정으로 <see cref="SqlConnection"/>을 생성하기 위한 팩토리를 초기화합니다.
|
||||
/// </summary>
|
||||
/// <param name="settings">서버, 데이터베이스, 사용자, 비밀번호 등의 연결 정보.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 구성된 연결 문자열로 SQL Server 연결을 열어 반환합니다.
|
||||
/// </summary>
|
||||
/// <returns>열린 상태의 <see cref="SqlConnection"/>.</returns>
|
||||
public SqlConnection Open()
|
||||
{
|
||||
SqlConnection connection = new SqlConnection(_connectionString);
|
||||
connection.Open();
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 내부에서 사용되는 연결 문자열을 반환합니다.
|
||||
/// </summary>
|
||||
public string ConnectionString
|
||||
{
|
||||
get { return _connectionString; }
|
||||
}
|
||||
}
|
||||
}
|
||||
21
Keps.WinForms/Keps.WinForms.csproj
Normal file
21
Keps.WinForms/Keps.WinForms.csproj
Normal file
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
<RootNamespace>Keps.WinForms</RootNamespace>
|
||||
<AssemblyName>Keps.WinForms</AssemblyName>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="EPPlus" Version="4.5.3.3" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="System.Configuration" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
21
Keps.WinForms/Models/AdjustmentRow.cs
Normal file
21
Keps.WinForms/Models/AdjustmentRow.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 추출 표본 보정 내역을 표현하는 행 모델입니다.
|
||||
/// </summary>
|
||||
public sealed class AdjustmentRow
|
||||
{
|
||||
/// <summary>
|
||||
/// 해당 표본이 속한 군집 번호.
|
||||
/// </summary>
|
||||
public int ClusterNo { get; set; }
|
||||
/// <summary>
|
||||
/// 원래 추출 순번(Extract ID).
|
||||
/// </summary>
|
||||
public int ExtractId { get; set; }
|
||||
/// <summary>
|
||||
/// 보정된 순번(있을 경우). null이면 보정 없음.
|
||||
/// </summary>
|
||||
public int? AdjustId { get; set; }
|
||||
}
|
||||
}
|
||||
17
Keps.WinForms/Models/CandidateOption.cs
Normal file
17
Keps.WinForms/Models/CandidateOption.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 후보자 선택을 위한 표시 이름과 내부 키를 보관하는 옵션 항목입니다.
|
||||
/// </summary>
|
||||
public sealed class CandidateOption
|
||||
{
|
||||
/// <summary>
|
||||
/// UI에 표시할 후보자 이름(예: 홍길동(1)).
|
||||
/// </summary>
|
||||
public string DisplayName { get; set; }
|
||||
/// <summary>
|
||||
/// 내부 조회/정렬에 사용되는 키(예: cand_ratio_1).
|
||||
/// </summary>
|
||||
public string Key { get; set; }
|
||||
}
|
||||
}
|
||||
29
Keps.WinForms/Models/ClusterSummaryRow.cs
Normal file
29
Keps.WinForms/Models/ClusterSummaryRow.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 군집(층화) 단위 요약 정보를 담는 모델입니다.
|
||||
/// </summary>
|
||||
public sealed class ClusterSummaryRow
|
||||
{
|
||||
/// <summary>
|
||||
/// 군집 번호(1..N).
|
||||
/// </summary>
|
||||
public int ClusterNo { get; set; }
|
||||
/// <summary>
|
||||
/// 표시용 라벨(예: "1 층").
|
||||
/// </summary>
|
||||
public string ClusterLabel { get; set; }
|
||||
/// <summary>
|
||||
/// 해당 군집 내 전체 투표구 수.
|
||||
/// </summary>
|
||||
public int PollingPlaceCount { get; set; }
|
||||
/// <summary>
|
||||
/// 표본 할당 비율(0~1).
|
||||
/// </summary>
|
||||
public decimal Ratio { get; set; }
|
||||
/// <summary>
|
||||
/// 최종 할당된 표본 수.
|
||||
/// </summary>
|
||||
public int SampleCount { get; set; }
|
||||
}
|
||||
}
|
||||
61
Keps.WinForms/Models/ExtractionRow.cs
Normal file
61
Keps.WinForms/Models/ExtractionRow.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 실 추출/모집단 표의 각 행(투표구)을 표현하는 모델입니다.
|
||||
/// </summary>
|
||||
public sealed class ExtractionRow
|
||||
{
|
||||
/// <summary>군집 번호.</summary>
|
||||
public int ClusterNo { get; set; }
|
||||
/// <summary>해당 군집 내 추출 순번.</summary>
|
||||
public int ClusterOrder { get; set; }
|
||||
/// <summary>정렬 후 모집단에서의 원래 순번.</summary>
|
||||
public int OriginalOrder { get; set; }
|
||||
/// <summary>등간격 추출 간격.</summary>
|
||||
public int Interval { get; set; }
|
||||
/// <summary>등간격 추출 시작 위치.</summary>
|
||||
public int StartPosition { get; set; }
|
||||
/// <summary>오프셋(시작위치) 설명.</summary>
|
||||
public string OffsetDescription { get; set; }
|
||||
/// <summary>시도명.</summary>
|
||||
public string AreaName { get; set; }
|
||||
/// <summary>선거구명.</summary>
|
||||
public string DistrictName { get; set; }
|
||||
/// <summary>시군구.</summary>
|
||||
public string SiGunGu { get; set; }
|
||||
/// <summary>읍면동.</summary>
|
||||
public string EupMyeonDong { get; set; }
|
||||
/// <summary>투표구 표시명(예: 읍면동 + " 제N투").</summary>
|
||||
public string PollingPlaceName { get; set; }
|
||||
/// <summary>투표구 번호(예: 제1투).</summary>
|
||||
public string PollingPlaceNo { get; set; }
|
||||
/// <summary>유권자수(투표권자 수 추정/원자료 컬럼).</summary>
|
||||
public int EligibleVoterCount { get; set; }
|
||||
/// <summary>선거인수.</summary>
|
||||
public int ElectorateCount { get; set; }
|
||||
/// <summary>투표인수.</summary>
|
||||
public int VoteCount { get; set; }
|
||||
/// <summary>후보자별 득표수 합계.</summary>
|
||||
public int TotalCandidateVoteCount { get; set; }
|
||||
/// <summary>중복 투표소 여부 플래그.</summary>
|
||||
public string DuplicateFlag { get; set; }
|
||||
/// <summary>투표소 건물명.</summary>
|
||||
public string BuildingName { get; set; }
|
||||
/// <summary>주소(첫 줄).</summary>
|
||||
public string Address1 { get; set; }
|
||||
/// <summary>비고/기타 메모.</summary>
|
||||
public string Note { get; set; }
|
||||
/// <summary>정렬 기준 값(투표인수 또는 후보 득표율 등).</summary>
|
||||
public decimal SortValue { get; set; }
|
||||
/// <summary>자동 추출에 의해 선택되었는지 여부.</summary>
|
||||
public bool IsAutoSelected { get; set; }
|
||||
/// <summary>사용자 보정 선택 반영 여부.</summary>
|
||||
public bool IsAdjustedSelected { get; set; }
|
||||
/// <summary>후보자별 득표수 맵.</summary>
|
||||
public Dictionary<string, decimal> CandidateVotes { get; set; }
|
||||
/// <summary>후보자별 득표율(%) 맵.</summary>
|
||||
public Dictionary<string, decimal> CandidateRatios { get; set; }
|
||||
}
|
||||
}
|
||||
13
Keps.WinForms/Models/ImportMode.cs
Normal file
13
Keps.WinForms/Models/ImportMode.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Excel 적재 모드를 나타냅니다.
|
||||
/// </summary>
|
||||
public enum ImportMode
|
||||
{
|
||||
/// <summary>실제 데이터(poll_data) 적재.</summary>
|
||||
Real,
|
||||
/// <summary>시뮬레이션 데이터 적재(현재 미지원).</summary>
|
||||
Simulation
|
||||
}
|
||||
}
|
||||
28
Keps.WinForms/Models/ImportProgress.cs
Normal file
28
Keps.WinForms/Models/ImportProgress.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Excel 적재 과정에서의 진행 상태를 나타냅니다.
|
||||
/// </summary>
|
||||
public sealed class ImportProgress
|
||||
{
|
||||
/// <summary>
|
||||
/// 진행 상태를 초기화합니다.
|
||||
/// </summary>
|
||||
/// <param name="percent">진행률(0~100).</param>
|
||||
/// <param name="message">사용자에게 표시할 메시지.</param>
|
||||
public ImportProgress(int percent, string message)
|
||||
{
|
||||
Percent = percent;
|
||||
Message = message;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 진행률(0~100).
|
||||
/// </summary>
|
||||
public int Percent { get; private set; }
|
||||
/// <summary>
|
||||
/// 현재 단계 설명 메시지.
|
||||
/// </summary>
|
||||
public string Message { get; private set; }
|
||||
}
|
||||
}
|
||||
69
Keps.WinForms/Models/PollingPlaceRecord.cs
Normal file
69
Keps.WinForms/Models/PollingPlaceRecord.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// poll_data 원시 데이터 한 행(투표구 단위)을 표현하는 모델입니다.
|
||||
/// </summary>
|
||||
public sealed class PollingPlaceRecord
|
||||
{
|
||||
/// <summary>선거명 또는 연월.</summary>
|
||||
public string ElectionName { get; set; }
|
||||
/// <summary>시도명.</summary>
|
||||
public string AreaName { get; set; }
|
||||
/// <summary>선거구명.</summary>
|
||||
public string DistrictName { get; set; }
|
||||
/// <summary>시군구.</summary>
|
||||
public string SiGunGu { get; set; }
|
||||
/// <summary>읍면동.</summary>
|
||||
public string EupMyeonDong { get; set; }
|
||||
/// <summary>투표구 표시명(예: 읍면동 + " 제N투").</summary>
|
||||
public string PollingPlaceName { get; set; }
|
||||
/// <summary>투표구 번호.</summary>
|
||||
public string PollingPlaceNo { get; set; }
|
||||
/// <summary>계산된 군집 값.</summary>
|
||||
public int ClusterValue { get; set; }
|
||||
/// <summary>유권자수.</summary>
|
||||
public int EligibleVoterCount { get; set; }
|
||||
/// <summary>선거인수.</summary>
|
||||
public int ElectorateCount { get; set; }
|
||||
/// <summary>투표인수.</summary>
|
||||
public int VoteCount { get; set; }
|
||||
/// <summary>후보자별 득표수 합계.</summary>
|
||||
public int TotalCandidateVoteCount { get; set; }
|
||||
/// <summary>중복 투표소 여부 플래그.</summary>
|
||||
public string DuplicateFlag { get; set; }
|
||||
/// <summary>투표소 건물명.</summary>
|
||||
public string BuildingName { get; set; }
|
||||
/// <summary>주소(첫 줄).</summary>
|
||||
public string Address1 { get; set; }
|
||||
/// <summary>관할구역/세부지역.</summary>
|
||||
public string AreaDetail { get; set; }
|
||||
/// <summary>비고/기타 메모.</summary>
|
||||
public string Note { get; set; }
|
||||
/// <summary>후보자별 득표수.</summary>
|
||||
public Dictionary<string, decimal> CandidateVotes { get; set; }
|
||||
/// <summary>후보자별 득표율(%)</summary>
|
||||
public Dictionary<string, decimal> CandidateRatios { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 지정된 정렬 키에 대한 값을 반환합니다.
|
||||
/// </summary>
|
||||
/// <param name="sortKey">정렬 키(예: "투표인수" 또는 cand_ratio_*).</param>
|
||||
/// <returns>정렬용 수치 값.</returns>
|
||||
public decimal GetSortValue(string sortKey)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sortKey) || sortKey == "투표인수")
|
||||
{
|
||||
return VoteCount;
|
||||
}
|
||||
|
||||
if (CandidateRatios != null && CandidateRatios.ContainsKey(sortKey))
|
||||
{
|
||||
return CandidateRatios[sortKey];
|
||||
}
|
||||
|
||||
return 0m;
|
||||
}
|
||||
}
|
||||
}
|
||||
37
Keps.WinForms/Models/RealExtractionResult.cs
Normal file
37
Keps.WinForms/Models/RealExtractionResult.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 실 추출 실행 결과 전체를 포함하는 DTO입니다.
|
||||
/// </summary>
|
||||
public sealed class RealExtractionResult
|
||||
{
|
||||
/// <summary>후보자 표시 이름 목록.</summary>
|
||||
public List<string> CandidateNames { get; set; }
|
||||
/// <summary>후보자 득표수 조회 키 목록.</summary>
|
||||
public List<string> CandidateVoteKeys { get; set; }
|
||||
/// <summary>후보자 득표율 조회 키 목록.</summary>
|
||||
public List<string> CandidateRatioKeys { get; set; }
|
||||
/// <summary>최종 추출 표본 행 목록.</summary>
|
||||
public List<ExtractionRow> ExtractedRows { get; set; }
|
||||
/// <summary>모집단(전체) 행 목록.</summary>
|
||||
public List<ExtractionRow> PopulationRows { get; set; }
|
||||
/// <summary>보정 정보 목록.</summary>
|
||||
public List<AdjustmentRow> AdjustmentRows { get; set; }
|
||||
/// <summary>검증(요약) 행 목록.</summary>
|
||||
public List<VerificationSummaryRow> VerificationRows { get; set; }
|
||||
/// <summary>군집 최대값.</summary>
|
||||
public int ClusterMax { get; set; }
|
||||
/// <summary>전체 표본 수.</summary>
|
||||
public int TotalSampleCount { get; set; }
|
||||
/// <summary>자동 할당 여부.</summary>
|
||||
public bool IsAutoAllocation { get; set; }
|
||||
/// <summary>정렬 기준 표시 이름.</summary>
|
||||
public string SortDisplayName { get; set; }
|
||||
/// <summary>정렬 내림차순 여부.</summary>
|
||||
public bool SortDescending { get; set; }
|
||||
/// <summary>오프셋 설명.</summary>
|
||||
public string OffsetDescription { get; set; }
|
||||
}
|
||||
}
|
||||
17
Keps.WinForms/Models/RealScenarioContext.cs
Normal file
17
Keps.WinForms/Models/RealScenarioContext.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 실 추출 화면에 필요한 초기 데이터 컨텍스트입니다.
|
||||
/// </summary>
|
||||
public sealed class RealScenarioContext
|
||||
{
|
||||
/// <summary>자동 할당용 군집 행 목록.</summary>
|
||||
public List<ClusterSummaryRow> AutoRows { get; set; }
|
||||
/// <summary>수동 할당용 군집 행 목록.</summary>
|
||||
public List<ClusterSummaryRow> ManualRows { get; set; }
|
||||
/// <summary>정렬 기준 선택 옵션 목록.</summary>
|
||||
public List<CandidateOption> SortOptions { get; set; }
|
||||
}
|
||||
}
|
||||
36
Keps.WinForms/Models/VerificationSummaryRow.cs
Normal file
36
Keps.WinForms/Models/VerificationSummaryRow.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
namespace Keps.WinForms.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 검증 요약(가중 오차/군집 내 오차 등)을 담는 행 모델입니다.
|
||||
/// </summary>
|
||||
public sealed class VerificationSummaryRow
|
||||
{
|
||||
public string RowLabel { get; set; }
|
||||
/// <summary>해당 행(군집 또는 전체)의 비율.</summary>
|
||||
public decimal ClusterRatio { get; set; }
|
||||
/// <summary>해당 행의 표본 수.</summary>
|
||||
public int SampleCount { get; set; }
|
||||
|
||||
/// <summary>표본에서 계산된 후보1/2/3의 비율.</summary>
|
||||
public decimal Extracted1 { get; set; }
|
||||
public decimal Extracted2 { get; set; }
|
||||
public decimal Extracted3 { get; set; }
|
||||
|
||||
/// <summary>실제(모집단) 후보1/2/3의 비율.</summary>
|
||||
public decimal Actual1 { get; set; }
|
||||
public decimal Actual2 { get; set; }
|
||||
public decimal Actual3 { get; set; }
|
||||
|
||||
/// <summary>가중 오차(후보1/2/3 및 합).</summary>
|
||||
public decimal WeightedError1 { get; set; }
|
||||
public decimal WeightedError2 { get; set; }
|
||||
public decimal WeightedError3 { get; set; }
|
||||
public decimal WeightedErrorSum { get; set; }
|
||||
|
||||
/// <summary>군집 내 오차(후보1/2/3 및 합).</summary>
|
||||
public decimal InClusterError1 { get; set; }
|
||||
public decimal InClusterError2 { get; set; }
|
||||
public decimal InClusterError3 { get; set; }
|
||||
public decimal InClusterErrorSum { get; set; }
|
||||
}
|
||||
}
|
||||
25
Keps.WinForms/Program.cs
Normal file
25
Keps.WinForms/Program.cs
Normal file
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
37
Keps.WinForms/Services/AppVersionService.cs
Normal file
37
Keps.WinForms/Services/AppVersionService.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using Keps.WinForms.Infrastructure;
|
||||
|
||||
namespace Keps.WinForms.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 데이터베이스에 저장된 현재 프로그램 버전을 조회하는 서비스입니다.
|
||||
/// </summary>
|
||||
public sealed class AppVersionService
|
||||
{
|
||||
private readonly SqlConnectionFactory _connectionFactory;
|
||||
|
||||
/// <summary>
|
||||
/// 애플리케이션 버전 조회 서비스를 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">DB 연결을 생성하는 팩토리.</param>
|
||||
public AppVersionService(SqlConnectionFactory connectionFactory)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 데이터베이스의 정보 테이블에서 현재 프로그램 버전을 조회합니다.
|
||||
/// </summary>
|
||||
/// <returns>버전 문자열. 조회 결과가 없으면 빈 문자열.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
264
Keps.WinForms/Services/ClusterMaintenanceService.cs
Normal file
264
Keps.WinForms/Services/ClusterMaintenanceService.cs
Normal file
@@ -0,0 +1,264 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using Keps.WinForms.Infrastructure;
|
||||
|
||||
namespace Keps.WinForms.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 군집(층화) 관련 중간 테이블 생성 및 poll_data 반영 작업을 수행하는 유지보수용 서비스입니다.
|
||||
/// </summary>
|
||||
public sealed class ClusterMaintenanceService
|
||||
{
|
||||
private readonly SqlConnectionFactory _connectionFactory;
|
||||
|
||||
/// <summary>
|
||||
/// 군집 관련 유지보수 작업을 수행하는 서비스를 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">DB 연결을 제공하는 팩토리.</param>
|
||||
public ClusterMaintenanceService(SqlConnectionFactory connectionFactory)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 주어진 선거 연도에 대해 군집 관련 중간 테이블을 재구축하고 poll_data에 반영합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionYear">선거 연도(예: "201804").</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 대상 선거 연도의 작업용 테이블 데이터를 초기화합니다.
|
||||
/// </summary>
|
||||
/// <param name="connection">열린 DB 연결.</param>
|
||||
/// <param name="electionYear">선거 연도.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 시군구별 유권자수와 군집 정보를 계산하여 매핑 테이블에 적재합니다.
|
||||
/// </summary>
|
||||
/// <param name="connection">열린 DB 연결.</param>
|
||||
/// <param name="electionYear">선거 연도.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 선거명/시도명별로 군집 비율(득표수 기반)을 계산하여 적재합니다.
|
||||
/// </summary>
|
||||
/// <param name="connection">열린 DB 연결.</param>
|
||||
/// <param name="electionYear">선거 연도.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// poll_data 테이블의 군집 관련 컬럼 값을 초기화합니다.
|
||||
/// </summary>
|
||||
/// <param name="connection">열린 DB 연결.</param>
|
||||
/// <param name="electionYear">선거 연도.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 시군구별 군집 값을 poll_data 테이블의 해당 행들에 반영합니다.
|
||||
/// </summary>
|
||||
/// <param name="connection">열린 DB 연결.</param>
|
||||
/// <param name="electionYear">선거 연도.</param>
|
||||
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<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
|
||||
while (reader.Read())
|
||||
{
|
||||
Dictionary<string, object> row = new Dictionary<string, object>();
|
||||
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<string, object> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 공통 파라미터(<c>@eleYm</c>)를 바인딩하여 지정된 SQL을 실행합니다.
|
||||
/// </summary>
|
||||
/// <param name="connection">열린 DB 연결.</param>
|
||||
/// <param name="sql">실행할 SQL 문.</param>
|
||||
/// <param name="electionYear">바인딩할 선거 연도 값.</param>
|
||||
private void Execute(SqlConnection connection, string sql, string electionYear)
|
||||
{
|
||||
using (SqlCommand command = new SqlCommand(sql, connection))
|
||||
{
|
||||
command.Parameters.AddWithValue("@eleYm", electionYear);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
333
Keps.WinForms/Services/ExcelImportService.cs
Normal file
333
Keps.WinForms/Services/ExcelImportService.cs
Normal file
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Excel 파일에서 실데이터를 읽어 DB에 적재하는 서비스입니다.
|
||||
/// </summary>
|
||||
public sealed class ExcelImportService
|
||||
{
|
||||
private readonly SqlConnectionFactory _connectionFactory;
|
||||
private readonly ClusterMaintenanceService _clusterMaintenanceService;
|
||||
|
||||
/// <summary>
|
||||
/// Excel 적재 서비스 인스턴스를 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">DB 연결을 제공하는 팩토리.</param>
|
||||
public ExcelImportService(SqlConnectionFactory connectionFactory)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_clusterMaintenanceService = new ClusterMaintenanceService(connectionFactory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// elections 테이블에서 사용 가능한 선거 연월 목록을 조회합니다.
|
||||
/// </summary>
|
||||
/// <returns>연월 문자열 목록(내림차순).</returns>
|
||||
public List<string> LoadElectionYears()
|
||||
{
|
||||
List<string> years = new List<string>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 지정한 폴더의 Excel 파일(.xlsx/.xlsm)을 읽어 실데이터를 DB에 적재합니다.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">Excel 파일들이 위치한 폴더 경로.</param>
|
||||
/// <param name="electionYear">적재 대상 선거 연월(예: "201804").</param>
|
||||
/// <param name="mode">적재 모드(현재 Real만 지원).</param>
|
||||
/// <param name="progress">진행 상황을 보고받을 프로그레스 리스너.</param>
|
||||
/// <exception cref="InvalidOperationException">폴더가 없거나 지원 확장자가 없을 때 발생.</exception>
|
||||
/// <exception cref="NotSupportedException">미지원 모드일 때 발생.</exception>
|
||||
public void Import(string folderPath, string electionYear, ImportMode mode, IProgress<ImportProgress> progress)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(folderPath) || !Directory.Exists(folderPath))
|
||||
{
|
||||
throw new InvalidOperationException("유효한 폴더를 선택하세요.");
|
||||
}
|
||||
|
||||
List<string> 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<string> candidateNames = new List<string>();
|
||||
|
||||
using (ExcelEpplusReader reader = new ExcelEpplusReader())
|
||||
{
|
||||
reader.Open(firstFile);
|
||||
List<ExcelSheet> sheets = new List<ExcelSheet>(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, "완료"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// elections 테이블에 대상 연월이 없으면 1건을 삽입하여 존재를 보장합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionYear">선거 연월(예: "201804").</param>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 실데이터 적재 전 기존 poll_data 및 관련 테이블에서 대상 연월의 데이터를 정리합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionYear">선거 연월.</param>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 실데이터 Excel 시트 한 개를 파싱하여 poll_data 등 테이블에 적재합니다.
|
||||
/// </summary>
|
||||
/// <param name="sheet">EPPlus로 읽은 시트.</param>
|
||||
/// <param name="electionYear">선거 연월.</param>
|
||||
/// <param name="candidateNames">발견된 후보자명 누적 리스트(출력 가변).</param>
|
||||
private void ImportRealSheet(ExcelSheet sheet, string electionYear, List<string> 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<string, string> cand = new Dictionary<string, string>();
|
||||
Dictionary<string, string> candRatio = new Dictionary<string, string>();
|
||||
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++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 레거시 표기에서 투표구 번호 텍스트를 추출합니다(예: "제1투" → "1").
|
||||
/// </summary>
|
||||
/// <param name="pollingPlaceText">원본 텍스트.</param>
|
||||
/// <returns>정규화된 투표구 번호 문자열.</returns>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// cand_name 테이블에 후보자명을 upsert(없으면 삽입, 있으면 유지)합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionYear">선거 연월.</param>
|
||||
/// <param name="candidateNames">후보자명 목록.</param>
|
||||
private void UpsertCandidateNames(string electionYear, List<string> 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
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
835
Keps.WinForms/Services/ExcelReportService.cs
Normal file
835
Keps.WinForms/Services/ExcelReportService.cs
Normal file
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 실 추출 결과를 Excel 워크북(.xlsx)으로 내보내는 서비스입니다.
|
||||
/// </summary>
|
||||
public sealed class ExcelReportService
|
||||
{
|
||||
/// <summary>
|
||||
/// 실 추출 결과와 관련 시트를 포함한 Excel 워크북을 저장합니다.
|
||||
/// </summary>
|
||||
/// <param name="filePath">저장할 파일 경로.</param>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="clusterRows">군집 요약 행 목록(모드 시트 등에 사용).</param>
|
||||
/// <param name="result">실 추출 결과 DTO.</param>
|
||||
public void ExportRealExtractionWorkbook(string filePath, string electionName, string areaName, List<ClusterSummaryRow> 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<string> candidateNames = (result.CandidateNames ?? new List<string>()).ToList();
|
||||
List<string> candidateVoteKeys = (result.CandidateVoteKeys ?? new List<string>()).ToList();
|
||||
List<string> candidateRatioKeys = (result.CandidateRatioKeys ?? new List<string>()).ToList();
|
||||
NormalizeCandidateLists(candidateNames, candidateVoteKeys, candidateRatioKeys);
|
||||
|
||||
WriteExtractedSheet(package.Workbook.Worksheets.Add(areaName + "-추출결과"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List<ExtractionRow>(), result.PopulationRows ?? new List<ExtractionRow>(), result);
|
||||
WriteVerificationSummarySheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-요약분석"), electionName, areaName, candidateNames, result.VerificationRows ?? new List<VerificationSummaryRow>(), result.ClusterMax);
|
||||
WriteVerificationDetailSheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-세부분석"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List<ExtractionRow>(), result.VerificationRows ?? new List<VerificationSummaryRow>(), result.ClusterMax);
|
||||
WriteFinalStatusSheet(package.Workbook.Worksheets.Add(areaName + "-최종 투표소 추출현황"), electionName, areaName, candidateNames, candidateVoteKeys, result.PopulationRows ?? new List<ExtractionRow>(), result.ClusterMax);
|
||||
WriteClusterListSheet(package.Workbook.Worksheets.Add(areaName + "-층별 시군구 리스트"), electionName, areaName, result.PopulationRows ?? new List<ExtractionRow>());
|
||||
WriteModeSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode"), electionName, clusterRows ?? new List<ClusterSummaryRow>(), result.PopulationRows ?? new List<ExtractionRow>());
|
||||
WriteModeTargetSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode Target"), clusterRows ?? new List<ClusterSummaryRow>(), result.PopulationRows ?? new List<ExtractionRow>());
|
||||
|
||||
package.SaveAs(new FileInfo(filePath));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 추출 결과 시트를 작성합니다(클러스터별 표본과 모집단 요약 포함).
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="candidateNames">후보자 표시명 목록(최소 3개로 보정됨).</param>
|
||||
/// <param name="candidateVoteKeys">후보자 득표 키 목록(최소 3개로 보정됨).</param>
|
||||
/// <param name="rows">추출 표본 행 목록.</param>
|
||||
/// <param name="populationRows">모집단 행 목록.</param>
|
||||
/// <param name="result">추출 실행 메타(정렬/오프셋 등).</param>
|
||||
private static void WriteExtractedSheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<string> candidateVoteKeys, List<ExtractionRow> rows, List<ExtractionRow> populationRows, RealExtractionResult result)
|
||||
{
|
||||
int rowIndex = 1;
|
||||
foreach (IGrouping<int, ExtractionRow> 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<ExtractionRow> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 추출 결과 시트의 헤더(타이틀/열 병합/후보 라벨)를 설정합니다.
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="rowIndex">헤더를 쓸 시작 행.</param>
|
||||
/// <param name="candidateNames">후보자 표시명 목록.</param>
|
||||
/// <param name="clusterMax">층(군집) 최대 개수.</param>
|
||||
private static void SetExtractHeader(ExcelWorksheet ws, int rowIndex, List<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 자가 검증-요약분석 시트를 작성합니다(전체/층별 득표율 및 오차 요약).
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="candidateNames">후보자 표시명 목록.</param>
|
||||
/// <param name="rows">검증 요약 행 목록.</param>
|
||||
/// <param name="clusterMax">군집(층) 최대 개수.</param>
|
||||
private static void WriteVerificationSummarySheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<VerificationSummaryRow> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 자가 검증-세부분석 시트를 작성합니다(층/구간별 상세 지표 포함).
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="candidateNames">후보자 표시명 목록.</param>
|
||||
/// <param name="candidateVoteKeys">후보자 득표 키 목록.</param>
|
||||
/// <param name="rows">추출 표본 행 목록.</param>
|
||||
/// <param name="summaryRows">검증 요약 행 목록.</param>
|
||||
/// <param name="clusterMax">군집(층) 최대 개수.</param>
|
||||
private static void WriteVerificationDetailSheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<string> candidateVoteKeys, List<ExtractionRow> rows, List<VerificationSummaryRow> 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<int, ExtractionRow> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 요약 행 데이터를 세부 형식과 동일하게 한 줄로 출력합니다.
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="rowIndex">기록할 시작 행.</param>
|
||||
/// <param name="row">요약 데이터.</param>
|
||||
/// <param name="label1">왼쪽 라벨.</param>
|
||||
/// <param name="label2">오른쪽 라벨.</param>
|
||||
/// <param name="includeClusterError">군집 내 오차 컬럼 포함 여부.</param>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 최종 투표소 추출현황 시트를 작성합니다(모집단 내 각 행과 후보 득표수/비율 표시).
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="candidateNames">후보자 표시명 목록.</param>
|
||||
/// <param name="candidateVoteKeys">후보자 득표 키 목록.</param>
|
||||
/// <param name="rows">모집단 행 목록.</param>
|
||||
/// <param name="clusterMax">군집(층) 최대 개수.</param>
|
||||
private static void WriteFinalStatusSheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<string> candidateVoteKeys, List<ExtractionRow> 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<int, ExtractionRow> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 층별 시군구 리스트 시트를 작성합니다(군집별로 읍면동 묶음 출력).
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="rows">모집단 행 목록.</param>
|
||||
private static void WriteClusterListSheet(ExcelWorksheet ws, string electionName, string areaName, List<ExtractionRow> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 기준설정 Mode 시트를 작성합니다(군집 요약과 모집단 정보를 활용한 기준표).
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="rows">군집 요약 행 목록.</param>
|
||||
/// <param name="populationRows">모집단 행 목록.</param>
|
||||
private static void WriteModeSheet(ExcelWorksheet ws, string electionName, List<ClusterSummaryRow> rows, List<ExtractionRow> 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<ExtractionRow> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 기준설정 Mode Target 시트를 작성합니다(군집별 타깃 비교 표).
|
||||
/// </summary>
|
||||
/// <param name="ws">대상 워크시트.</param>
|
||||
/// <param name="clusterRows">군집 요약 행 목록.</param>
|
||||
/// <param name="rows">모집단 행 목록.</param>
|
||||
private static void WriteModeTargetSheet(ExcelWorksheet ws, List<ClusterSummaryRow> clusterRows, List<ExtractionRow> 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<ExtractionRow> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 클러스터(층) 타이틀 텍스트를 생성합니다(표본 수/정렬/오프셋 등 메타 포함).
|
||||
/// </summary>
|
||||
/// <param name="result">실 추출 결과 메타.</param>
|
||||
/// <param name="clusterNo">군집(층) 번호.</param>
|
||||
/// <param name="sampleCount">해당 층의 표본 수.</param>
|
||||
/// <returns>표시용 타이틀 문자열.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 오프셋 설명 텍스트를 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="offsetDescription">사용자에게 표시할 오프셋 설명.</param>
|
||||
/// <returns>표시용 오프셋 설명 문자열.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 후보자 이름/득표키/비율키 목록을 최소 3개까지 보정합니다.
|
||||
/// </summary>
|
||||
/// <param name="candidateNames">후보자 표시명 목록(부족 시 기본값 채움).</param>
|
||||
/// <param name="candidateVoteKeys">후보자 득표 키 목록(부족 시 기본값 채움).</param>
|
||||
/// <param name="candidateRatioKeys">후보자 득표율 키 목록(부족 시 기본값 채움).</param>
|
||||
private static void NormalizeCandidateLists(List<string> candidateNames, List<string> candidateVoteKeys, List<string> 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 읍면동 라벨을 생성합니다(시군구가 있으면 "시군구-읍면동").
|
||||
/// </summary>
|
||||
/// <param name="row">대상 행.</param>
|
||||
/// <returns>표시용 읍면동 라벨.</returns>
|
||||
private static string BuildTownLabel(ExtractionRow row)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(row.SiGunGu) ? row.EupMyeonDong : row.SiGunGu + "-" + row.EupMyeonDong;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 추출/모집단 행에서 지정 후보의 득표수를 반환합니다.
|
||||
/// </summary>
|
||||
/// <param name="row">대상 행.</param>
|
||||
/// <param name="candidateVoteKey">후보자 득표 키(예: cand_1).</param>
|
||||
/// <returns>득표수. 키 없거나 null이면 0.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 행에 저장된 후보 득표율(%)을 반환합니다. 없으면 0.
|
||||
/// </summary>
|
||||
/// <param name="row">대상 행.</param>
|
||||
/// <param name="candidateVoteKey">후보자 득표 키(예: cand_1).</param>
|
||||
/// <returns>저장된 득표율(%). 없으면 0.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 행 단위 표시 득표율(%)을 계산합니다. 저장된 비율이 있으면 그것을 우선 사용합니다.
|
||||
/// </summary>
|
||||
/// <param name="row">대상 행.</param>
|
||||
/// <param name="candidateVoteKey">후보자 득표 키.</param>
|
||||
/// <returns>표시용 득표율(%).</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 클러스터(그룹) 내 실제 득표율(%)을 계산합니다.
|
||||
/// </summary>
|
||||
/// <param name="rows">대상 행 목록.</param>
|
||||
/// <param name="candidateVoteKey">후보자 득표 키.</param>
|
||||
/// <returns>득표율(%), 분모가 0이면 0.</returns>
|
||||
private static decimal ComputeClusterActualRatio(List<ExtractionRow> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 그룹(임의 묶음) 내 득표율(%)을 계산합니다.
|
||||
/// </summary>
|
||||
/// <param name="rows">대상 행 목록.</param>
|
||||
/// <param name="candidateVoteKey">후보자 득표 키.</param>
|
||||
/// <returns>득표율(%), 분모가 0이면 0.</returns>
|
||||
private static decimal ComputeGroupRatio(List<ExtractionRow> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 소수점 첫째 자리에서 반올림(away from zero)합니다.
|
||||
/// </summary>
|
||||
/// <param name="value">반올림할 값.</param>
|
||||
/// <returns>소수 첫째 자리 반올림 값.</returns>
|
||||
private static decimal Round1(decimal value)
|
||||
{
|
||||
return Math.Round(value, 1, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 소수점 둘째 자리에서 반올림(away from zero)합니다.
|
||||
/// </summary>
|
||||
/// <param name="value">반올림할 값.</param>
|
||||
/// <returns>소수 둘째 자리 반올림 값.</returns>
|
||||
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<int> columns, string numberFormat)
|
||||
{
|
||||
foreach (int col in columns)
|
||||
{
|
||||
ws.Cells[fromRow, col, toRow, col].Style.Numberformat.Format = numberFormat;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
Keps.WinForms/Services/LegacySqlCatalog.cs
Normal file
29
Keps.WinForms/Services/LegacySqlCatalog.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
namespace Keps.WinForms.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 레거시 데이터베이스에 사용하는 SQL 문자열 상수 모음입니다.
|
||||
/// </summary>
|
||||
public static class LegacySqlCatalog
|
||||
{
|
||||
/// <summary>프로그램 버전 조회.</summary>
|
||||
public const string ProgramVersion = "SELECT ver FROM information WHERE program = 'keps'";
|
||||
/// <summary>활성화된 선거 연월 목록 조회.</summary>
|
||||
public const string ElectionYears = "SELECT ele_ym FROM elections WHERE flag = '1' ORDER BY ele_ym DESC";
|
||||
/// <summary>실 데이터에 존재하는 선거명 목록.</summary>
|
||||
public const string DistinctRealElections = "SELECT 선거명 FROM poll_data GROUP BY 선거명 ORDER BY 선거명";
|
||||
/// <summary>특정 선거명에 대한 시도명 목록.</summary>
|
||||
public const string DistinctRealAreas = "SELECT 시도명 FROM poll_data WHERE 선거명 = @electionName GROUP BY 시도명 ORDER BY 시도명";
|
||||
/// <summary>특정 선거/지역에 대한 군집 최대값 목록.</summary>
|
||||
public const string RealClusterMax = "SELECT 군집최대값 FROM 군집별비율 WHERE 선거명 = @electionName AND 시도명 = @areaName GROUP BY 군집최대값 ORDER BY 군집최대값";
|
||||
/// <summary>특정 선거/지역/군집최대값에 대한 군집별 비율.</summary>
|
||||
public const string RealClusterRatio = "SELECT 군집, 비율 FROM 군집별비율 WHERE 선거명 = @electionName AND 시도명 = @areaName AND 군집최대값 = @clusterMax ORDER BY 군집";
|
||||
/// <summary>군집별 투표구 수 카운트 쿼리 템플릿.</summary>
|
||||
public const string RealClusterCountTemplate = "SELECT COUNT(*) FROM poll_data WHERE ele_ym = @electionName AND 비고 = 1 AND 선거명 = @electionName AND 시도명 = @areaName AND [군집{0}개] = @clusterNo";
|
||||
/// <summary>후보자 이름/번호 조회.</summary>
|
||||
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";
|
||||
/// <summary>실 데이터에서 투표구 행들을 조회하는 템플릿(군집 컬럼 개수 가변).</summary>
|
||||
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";
|
||||
}
|
||||
}
|
||||
150
Keps.WinForms/Services/LookupService.cs
Normal file
150
Keps.WinForms/Services/LookupService.cs
Normal file
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 조회(룩업)용 데이터 로딩을 담당하는 서비스입니다.
|
||||
/// </summary>
|
||||
public sealed class LookupService
|
||||
{
|
||||
private readonly SqlConnectionFactory _connectionFactory;
|
||||
|
||||
/// <summary>
|
||||
/// 조회 관련 서비스 인스턴스를 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">DB 연결을 제공하는 팩토리.</param>
|
||||
public LookupService(SqlConnectionFactory connectionFactory)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 실 데이터(poll_data)에 존재하는 선거명 목록을 조회합니다.
|
||||
/// </summary>
|
||||
/// <returns>선거명 문자열 목록.</returns>
|
||||
public List<string> LoadRealElections()
|
||||
{
|
||||
return LoadSingleColumnList(LegacySqlCatalog.DistinctRealElections, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 특정 선거명에 대해 시도명(지역) 목록을 조회합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionName">선거명(예: "201804" 등).</param>
|
||||
/// <returns>지역명 문자열 목록.</returns>
|
||||
public List<string> LoadRealAreas(string electionName)
|
||||
{
|
||||
SqlParameter[] parameters = { new SqlParameter("@electionName", electionName) };
|
||||
return LoadSingleColumnList(LegacySqlCatalog.DistinctRealAreas, parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 특정 선거명과 지역에 대해 설정된 군집 최대값 목록을 조회합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionName">선거명.</param>
|
||||
/// <param name="areaName">지역명.</param>
|
||||
/// <returns>군집 최대값 정수 목록.</returns>
|
||||
public List<int> LoadRealClusterMaxList(string electionName, string areaName)
|
||||
{
|
||||
List<int> result = new List<int>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 특정 선거명에 대해 후보자 옵션 목록을 조회합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionName">선거명 또는 선거 번호.</param>
|
||||
/// <returns>후보자 표시 이름과 키를 담은 옵션 목록.</returns>
|
||||
public List<CandidateOption> LoadCandidateOptions(string electionName)
|
||||
{
|
||||
List<CandidateOption> result = new List<CandidateOption>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 단일 컬럼을 반환하는 쿼리를 실행하여 문자열 목록으로 변환합니다.
|
||||
/// </summary>
|
||||
/// <param name="sql">실행할 SQL.</param>
|
||||
/// <param name="parameters">바인딩할 매개변수 배열. null일 수 있습니다.</param>
|
||||
/// <returns>첫 번째 컬럼 값을 문자열로 담은 목록.</returns>
|
||||
private List<string> LoadSingleColumnList(string sql, SqlParameter[] parameters)
|
||||
{
|
||||
List<string> result = new List<string>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
711
Keps.WinForms/Services/SamplingService.cs
Normal file
711
Keps.WinForms/Services/SamplingService.cs
Normal file
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 표본 추출(실 데이터 기준) 관련 로직을 제공하는 서비스입니다.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 표본 추출 서비스 인스턴스를 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">DB 연결을 제공하는 팩토리.</param>
|
||||
public SamplingService(SqlConnectionFactory connectionFactory)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 실 추출 화면 구성을 위한 초기 컨텍스트를 로드합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="clusterMax">군집(층) 최대 개수.</param>
|
||||
/// <returns>자동/수동 행과 정렬 옵션을 포함한 컨텍스트.</returns>
|
||||
public RealScenarioContext LoadRealScenario(string electionName, string areaName, int clusterMax)
|
||||
{
|
||||
List<ClusterSummaryRow> rows = new List<ClusterSummaryRow>();
|
||||
|
||||
using (SqlConnection connection = _connectionFactory.Open())
|
||||
{
|
||||
Dictionary<int, decimal> ratioMap = new Dictionary<int, decimal>();
|
||||
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)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 군집별 비율에 따라 총 표본 수를 자동 배분합니다(소수점 버림 후 잔여는 앞쪽부터 1개씩 할당).
|
||||
/// </summary>
|
||||
/// <param name="rows">군집 비율 및 개수 정보를 담은 행 목록.</param>
|
||||
/// <param name="totalSampleCount">전체 표본 수.</param>
|
||||
/// <returns>배분된 표본 수가 채워진 새 목록.</returns>
|
||||
public List<ClusterSummaryRow> AllocateAutoSampleCounts(List<ClusterSummaryRow> rows, int totalSampleCount)
|
||||
{
|
||||
List<ClusterSummaryRow> result = CloneRows(rows);
|
||||
if (rows == null || rows.Count == 0 || totalSampleCount <= 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
int assigned = 0;
|
||||
List<Tuple<ClusterSummaryRow, decimal, int>> sampleTu = new List<Tuple<ClusterSummaryRow, decimal, int>>();
|
||||
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<ClusterSummaryRow, decimal, int>(result[i], exact - floor, i + 1));
|
||||
}
|
||||
|
||||
int remaining = totalSampleCount - assigned;
|
||||
/*********************************버그 살림*************************************/
|
||||
if (remaining > 0)
|
||||
{
|
||||
if (sampleTu.Count >= 2 && sampleTu[0].Item2 < sampleTu[1].Item2)
|
||||
{
|
||||
Tuple<ClusterSummaryRow, decimal, int> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 실 데이터에서 군집별 표본을 등간격으로 추출하고, 관련 산출물(보정, 검증, 모집단 목록)을 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="clusterMax">군집(층) 최대 개수.</param>
|
||||
/// <param name="sortKey">정렬 기준 키(예: "투표인수" 또는 cand_ratio_*).</param>
|
||||
/// <param name="sortDisplayName">정렬 기준 표시 이름.</param>
|
||||
/// <param name="descending">내림차순 여부.</param>
|
||||
/// <param name="allocationRows">군집별 배분 정보(표본 수 포함).</param>
|
||||
/// <param name="signedOffset">등간격 오프셋(양수/음수).</param>
|
||||
/// <param name="offsetDescription">오프셋 설명 문자열.</param>
|
||||
/// <param name="isAutoAllocation">자동 배분으로 생성되었는지 여부.</param>
|
||||
/// <returns>실 추출 결과 DTO.</returns>
|
||||
public RealExtractionResult RunRealExtraction(
|
||||
string electionName,
|
||||
string areaName,
|
||||
int clusterMax,
|
||||
string sortKey,
|
||||
string sortDisplayName,
|
||||
bool descending,
|
||||
List<ClusterSummaryRow> allocationRows,
|
||||
int signedOffset,
|
||||
string offsetDescription,
|
||||
bool isAutoAllocation)
|
||||
{
|
||||
List<PollingPlaceRecord> allRows = LoadRealPollingRows(electionName, areaName, clusterMax);
|
||||
List<CandidateMeta> candidateMeta = LoadCandidateMeta(electionName, allRows);
|
||||
List<ExtractionRow> extractedRows = new List<ExtractionRow>();
|
||||
List<ExtractionRow> populationRows = new List<ExtractionRow>();
|
||||
List<PollingPlaceRecord> extractedSourceRows = new List<PollingPlaceRecord>();
|
||||
|
||||
foreach (ClusterSummaryRow allocation in allocationRows.OrderBy(x => x.ClusterNo))
|
||||
{
|
||||
List<PollingPlaceRecord> 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<int> extractIds = SelectLegacyExtractIds(clusterRows.Count, allocation.SampleCount, signedOffset, out interval, out startPosition);
|
||||
HashSet<int> selectedPositions = new HashSet<int>(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<string> candidateNames = candidateMeta.Select(x => x.Name).ToList();
|
||||
List<string> candidateVoteKeys = candidateMeta.Select(x => x.VoteKey).ToList();
|
||||
List<string> 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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 실 데이터 테이블에서 투표구 행들을 조회하여 도메인 모델로 변환합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="areaName">시도명.</param>
|
||||
/// <param name="clusterMax">군집(층) 최대 개수(동적 군집 컬럼 선택에 사용).</param>
|
||||
/// <returns>조회된 투표구 원시 행 목록.</returns>
|
||||
private List<PollingPlaceRecord> LoadRealPollingRows(string electionName, string areaName, int clusterMax)
|
||||
{
|
||||
List<PollingPlaceRecord> result = new List<PollingPlaceRecord>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 후보자 메타 정보(표시명, 득표/비율 키)를 DB 또는 데이터에서 유추하여 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="electionName">선거명 또는 연월.</param>
|
||||
/// <param name="rows">후보자 득표/비율 정보가 포함될 수 있는 모집단 행 목록.</param>
|
||||
/// <returns>정렬용 후보 메타 정보 목록.</returns>
|
||||
private List<CandidateMeta> LoadCandidateMeta(string electionName, List<PollingPlaceRecord> rows)
|
||||
{
|
||||
List<CandidateMeta> result = new List<CandidateMeta>();
|
||||
|
||||
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<string> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 투표구 원시 행을 보고서/엑셀 출력용 추출 행 DTO로 변환합니다.
|
||||
/// </summary>
|
||||
/// <param name="row">원본 투표구 행.</param>
|
||||
/// <param name="clusterNo">군집 번호.</param>
|
||||
/// <param name="clusterOrder">군집 내 추출 순번.</param>
|
||||
/// <param name="originalOrder">정렬 모집단 상의 원래 순번.</param>
|
||||
/// <param name="interval">등간격 간격.</param>
|
||||
/// <param name="startPosition">등간격 시작 위치.</param>
|
||||
/// <param name="offsetDescription">오프셋 설명.</param>
|
||||
/// <param name="sortValue">정렬 기준 값.</param>
|
||||
/// <param name="isAutoSelected">자동 추출 여부.</param>
|
||||
/// <param name="isAdjustedSelected">보정 반영 여부.</param>
|
||||
/// <returns>변환된 추출 행.</returns>
|
||||
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<string, decimal>() : new Dictionary<string, decimal>(row.CandidateVotes),
|
||||
CandidateRatios = row.CandidateRatios == null ? new Dictionary<string, decimal>() : new Dictionary<string, decimal>(row.CandidateRatios)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 레거시 규칙에 맞춰 등간격 추출 ID 목록을 계산합니다.
|
||||
/// </summary>
|
||||
/// <param name="totalCount">모집단 크기(정렬된 투표구 수).</param>
|
||||
/// <param name="sampleCount">추출할 표본 수.</param>
|
||||
/// <param name="signedOffset">시작 위치 보정값(양수면 뒤로, 음수면 앞으로 이동).</param>
|
||||
/// <param name="interval">계산된 등간격 간격(출력).</param>
|
||||
/// <param name="startPosition">계산된 시작 위치(출력).</param>
|
||||
/// <returns>1부터 시작하는 추출 대상 인덱스 목록.</returns>
|
||||
private static List<int> SelectLegacyExtractIds(int totalCount, int sampleCount, int signedOffset, out int interval, out int startPosition)
|
||||
{
|
||||
List<int> extractIds = new List<int>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 추출된 표본 행들에서 보정 내역(원래 순번/보정 순번)을 생성합니다.
|
||||
/// </summary>
|
||||
/// <param name="extractedRows">최종 추출 표본 행 목록.</param>
|
||||
/// <returns>보정 내역 행 목록.</returns>
|
||||
private static List<AdjustmentRow> BuildAdjustmentRows(List<ExtractionRow> extractedRows)
|
||||
{
|
||||
return extractedRows
|
||||
.OrderBy(x => x.ClusterNo)
|
||||
.ThenBy(x => x.OriginalOrder)
|
||||
.Select(x => new AdjustmentRow
|
||||
{
|
||||
ClusterNo = x.ClusterNo,
|
||||
ExtractId = x.OriginalOrder,
|
||||
AdjustId = null
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 추출 표본과 모집단을 비교하여 요약 검증 지표(가중 오차, 군집 내 오차 등)를 계산합니다.
|
||||
/// </summary>
|
||||
/// <param name="populationRows">모집단(전체) 원시 행 목록.</param>
|
||||
/// <param name="extractedRows">추출된 원시 행 목록.</param>
|
||||
/// <param name="allocationRows">군집별 비율 및 표본 수 정보.</param>
|
||||
/// <param name="candidateMeta">후보자 메타 정보(표시명/키).</param>
|
||||
/// <returns>검증 요약 행 목록.</returns>
|
||||
private static List<VerificationSummaryRow> BuildVerificationRows(
|
||||
List<PollingPlaceRecord> populationRows,
|
||||
List<PollingPlaceRecord> extractedRows,
|
||||
List<ClusterSummaryRow> allocationRows,
|
||||
List<CandidateMeta> candidateMeta)
|
||||
{
|
||||
List<VerificationSummaryRow> result = new List<VerificationSummaryRow>();
|
||||
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<PollingPlaceRecord> clusterPopulation = populationRows.Where(x => x.ClusterValue == allocation.ClusterNo).ToList();
|
||||
List<PollingPlaceRecord> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 지정한 후보 득표수 키에 대한 실제 비율(%)을 계산합니다.
|
||||
/// </summary>
|
||||
/// <param name="rows">대상 행 목록.</param>
|
||||
/// <param name="voteKey">득표수 조회 키(예: cand_1).</param>
|
||||
/// <returns>득표율(%), 분모가 0이면 0.</returns>
|
||||
private static decimal ComputeCandidateRatioExact(List<PollingPlaceRecord> 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;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 소수점 둘째 자리에서 반올림(away from zero)합니다.
|
||||
/// </summary>
|
||||
/// <param name="value">반올림할 값.</param>
|
||||
/// <returns>소수 둘째 자리 반올림 값.</returns>
|
||||
private static decimal Round2(decimal value)
|
||||
{
|
||||
return Math.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 투표구 번호 문자열에서 정렬용 숫자 값을 추출합니다(예: "제1투" → 1).
|
||||
/// </summary>
|
||||
/// <param name="pollingPlaceNo">투표구 번호 문자열.</param>
|
||||
/// <returns>정렬용 정수 값. 추출 실패 시 매우 큰 값으로 취급합니다.</returns>
|
||||
private static int GetPollingPlaceSortValue(string pollingPlaceNo)
|
||||
{
|
||||
int value;
|
||||
return int.TryParse(pollingPlaceNo, out value) ? value : int.MaxValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 후보 득표 키에서 번호를 추출합니다(예: "cand_3" → 3). 실패 시 큰 값 반환.
|
||||
/// </summary>
|
||||
/// <param name="key">후보 득표 키.</param>
|
||||
/// <returns>숫자 값. 파싱 실패 시 int.MaxValue.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 소수점 첫째 자리에서 반올림(away from zero)합니다.
|
||||
/// </summary>
|
||||
/// <param name="value">반올림할 값.</param>
|
||||
/// <returns>소수 첫째 자리 반올림 값.</returns>
|
||||
private static decimal Round1(decimal value)
|
||||
{
|
||||
return Math.Round(value, 1, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 군집 요약 행 목록을 얕은 복사하여 변경 부작용을 방지합니다.
|
||||
/// </summary>
|
||||
/// <param name="rows">원본 행 목록.</param>
|
||||
/// <returns>복제된 새 목록.</returns>
|
||||
private static List<ClusterSummaryRow> CloneRows(List<ClusterSummaryRow> rows)
|
||||
{
|
||||
return rows.Select(x => new ClusterSummaryRow
|
||||
{
|
||||
ClusterNo = x.ClusterNo,
|
||||
ClusterLabel = x.ClusterLabel,
|
||||
PollingPlaceCount = x.PollingPlaceCount,
|
||||
Ratio = x.Ratio,
|
||||
SampleCount = x.SampleCount
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user