first commit
This commit is contained in:
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