lab4 ready

This commit is contained in:
Maxim 2024-12-17 01:21:56 +04:00
parent d308417e6a
commit 219abbc680
19 changed files with 90 additions and 39 deletions

View File

@ -47,22 +47,20 @@ public class ChartReport
{ {
try try
{ {
var advocateEarnings = _caseRepository return _caseAdvocateRepository
.ReadCases() .ReadCaseAdvocates(dateTo: dateTime.Date.AddDays(1))
.Where(x => x.CreatedAt.Date <= dateTime.Date) .Join(_caseRepository.ReadCases(dateTime.Date.AddDays(1)),
.Join(_caseAdvocateRepository.ReadCaseAdvocates().Where(x => x.CreatedAt.Date <= dateTime.Date), caseItem => caseItem.CaseId,
caseItem => caseItem.Id, caseCaseId => caseCaseId.Id,
caseAdvocate => caseAdvocate.CaseId, (caseItem, caseCase) => new
(caseItem, caseAdvocate) => new { caseItem, caseAdvocate }) {
.GroupBy(x => x.caseAdvocate.AdvocateId, (key, group) => new caseItem.AdvocateName, caseCase.Payment, caseCase.Verdict, caseCase.Price, caseCase.VictoryPrice
{ })
AdvocateName = _advocateRepository.ReadAdvocateById(key)?.Name ?? "Unknown", .GroupBy(x => x.AdvocateName)
Earnings = group.Sum(x => x.caseItem.Payment ? (x.caseItem.Verdict ? x.caseItem.VictoryPrice : x.caseItem.Price) : 0) .Select(g => (g.Key,
}) Sum: g.Sum(x =>
.Select(x => (x.AdvocateName, (double)x.Earnings)) x.Payment ? (x.Verdict ? (double)(x.Price + x.VictoryPrice) : (double)x.Price) : 0)))
.ToList(); .ToList();
return advocateEarnings;
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -33,7 +33,7 @@ internal class TableReport
{ {
new ExcelBuilder(filePath) new ExcelBuilder(filePath)
.AddHeader($"Сводка по делу \"{_caseRepository.ReadCaseById(caseId).Description}\"", 0, 4) .AddHeader($"Сводка по делу \"{_caseRepository.ReadCaseById(caseId).Description}\"", 0, 4)
.AddParagraph("за период", 0) .AddParagraph($"за период c {startDate:dd.MM.yyyy} по{endDate: dd.MM.yyyy}", 0)
.AddTable([10, 10, 15], GetData(caseId, startDate, .AddTable([10, 10, 15], GetData(caseId, startDate,
endDate)) endDate))
.Build(); .Build();
@ -50,6 +50,7 @@ internal class TableReport
{ {
var statusData = _statusHistoryRepository var statusData = _statusHistoryRepository
.ReadStatusHistories() .ReadStatusHistories()
// .ReadStatusHistories(startDate, endDate, caseId)
.Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate && x.CaseId == caseId) .Where(x => x.CreatedAt >= startDate && x.CreatedAt <= endDate && x.CaseId == caseId)
.GroupBy(x => (x.Status, x.CreatedAt.Date)) .GroupBy(x => (x.Status, x.CreatedAt.Date))
.Select(x => new .Select(x => new
@ -65,7 +66,7 @@ internal class TableReport
statusData statusData
.Select(x => new string[] .Select(x => new string[]
{ {
x.Status.ToString(), x.Date.ToString(), x.Count.ToString() x.Status.ToString(), x.Date.ToString("dd.MM.yyyy"), x.Count.ToString()
})) }))
.Union( .Union(
[ [

View File

@ -5,7 +5,7 @@ namespace ProjectGSM.Entities;
public class Advocate public class Advocate
{ {
[Browsable(false)] public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Имя")] public string Name { get; private set; } = string.Empty; [DisplayName("Имя")] public string Name { get; private set; } = string.Empty;

View File

@ -6,7 +6,7 @@ namespace ProjectGSM.Entities;
public class Case public class Case
{ {
[Browsable(false)] public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Тип обращения")] public TypeAppeal TypeAppeal { get; private set; } [DisplayName("Тип обращения")] public TypeAppeal TypeAppeal { get; private set; }
@ -29,11 +29,19 @@ public class Case
[DisplayName("Дата создания")] public DateTime CreatedAt { get; private set; } = DateTime.UtcNow; [DisplayName("Дата создания")] public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
[JsonIgnore] [Browsable(false)] public List<CaseAdvocate> Advocates { get; set; } = new(); [JsonIgnore] [Browsable(false)] public IEnumerable<CaseAdvocate> Advocates { get; private set; } = [];
[DisplayName("Адвокаты")] [DisplayName("Адвокаты")]
public string AdvocatesNames => string.Join(", ", Advocates.Select(x => $"{x.AdvocateName} ({x.Post})")); public string AdvocatesNames => string.Join(", ", Advocates.Select(x => $"{x.AdvocateName} ({x.Post})"));
public void SetAdvocates(IEnumerable<CaseAdvocate> advocates)
{
if (advocates != null && advocates.Any())
{
Advocates = advocates;
}
}
// Конструктор для создания сущности // Конструктор для создания сущности
public static Case CreateEntity( public static Case CreateEntity(
int id, int id,

View File

@ -4,9 +4,9 @@ namespace ProjectGSM.Entities;
public class CaseAdvocate public class CaseAdvocate
{ {
[Browsable(false)] public int CaseId { get; private set; } public int CaseId { get; private set; }
[Browsable(false)] public int AdvocateId { get; private set; } public int AdvocateId { get; private set; }
[DisplayName("Дело")] public string CaseDescription { get; private set; } = string.Empty; [DisplayName("Дело")] public string CaseDescription { get; private set; } = string.Empty;

View File

@ -4,7 +4,7 @@ namespace ProjectGSM.Entities;
public class Client public class Client
{ {
[Browsable(false)] public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Имя")] public string Name { get; private set; } = string.Empty; [DisplayName("Имя")] public string Name { get; private set; } = string.Empty;

View File

@ -4,7 +4,7 @@ namespace ProjectGSM.Entities;
public class Court public class Court
{ {
[Browsable(false)] public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Название")] public string Name { get; private set; } = string.Empty; [DisplayName("Название")] public string Name { get; private set; } = string.Empty;

View File

@ -5,7 +5,7 @@ namespace ProjectGSM.Entities;
public class StatusHistory public class StatusHistory
{ {
[Browsable(false)] public int CaseId { get; private set; } public int CaseId { get; private set; }
[DisplayName("Дело")] public string CaseDescription { get; private set; } = string.Empty; [DisplayName("Дело")] public string CaseDescription { get; private set; } = string.Empty;

View File

@ -105,6 +105,7 @@ namespace ProjectGSM.Forms
private void LoadList() { private void LoadList() {
dataGridViewAdvocats.DataSource = dataGridViewAdvocats.DataSource =
_advocateRepository.ReadAdvocates(); _advocateRepository.ReadAdvocates();
dataGridViewAdvocats.Columns["Id"].Visible = false;
dataGridViewAdvocats.Columns["CreatedAt"].DefaultCellStyle.Format = dataGridViewAdvocats.Columns["CreatedAt"].DefaultCellStyle.Format =
"dd.MM.yyyy"; "dd.MM.yyyy";
} }

View File

@ -43,7 +43,7 @@ namespace ProjectGSM.Forms
} }
Case caseE = CreateCase(0); Case caseE = CreateCase(0);
caseE.Advocates = CreateListCaseAdvocateFromDataGrid(); caseE.SetAdvocates(CreateListCaseAdvocateFromDataGrid());
_caseRepository.CreateCase(caseE); _caseRepository.CreateCase(caseE);
Close(); Close();
} }

View File

@ -85,6 +85,7 @@ namespace ProjectGSM.Forms
{ {
dataGridView.DataSource = dataGridView.DataSource =
_caseRepository.ReadCases(); _caseRepository.ReadCases();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format = dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format =
"dd.MM.yyyy"; "dd.MM.yyyy";
} }

View File

@ -105,6 +105,7 @@ namespace ProjectGSM.Forms
private void LoadList() { private void LoadList() {
dataGridView.DataSource = dataGridView.DataSource =
_clientRepository.ReadClients(); _clientRepository.ReadClients();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format = dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format =
"dd.MM.yyyy"; "dd.MM.yyyy";
} }

View File

@ -106,6 +106,7 @@ namespace ProjectGSM.Forms
{ {
dataGridView.DataSource = dataGridView.DataSource =
_courtRepository.ReadCourts(); _courtRepository.ReadCourts();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format = dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format =
"dd.MM.yyyy"; "dd.MM.yyyy";
} }

View File

@ -20,6 +20,7 @@ namespace ProjectGSM.Forms
public FormStatusesCasesReport(IUnityContainer container) public FormStatusesCasesReport(IUnityContainer container)
{ {
InitializeComponent(); InitializeComponent();
_container = container ?? _container = container ??
throw new ArgumentNullException(nameof(container)); throw new ArgumentNullException(nameof(container));
} }

View File

@ -50,6 +50,7 @@ namespace ProjectGSM.Forms
{ {
dataGridView.DataSource = dataGridView.DataSource =
_statusHistoryRepository.ReadStatusHistories(); _statusHistoryRepository.ReadStatusHistories();
dataGridView.Columns["CaseId"].Visible = false;
dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format = dataGridView.Columns["CreatedAt"].DefaultCellStyle.Format =
"dd.MM.yyyy"; "dd.MM.yyyy";
} }

View File

@ -4,7 +4,7 @@ namespace ProjectGSM.Repositories;
public interface ICaseRepository public interface ICaseRepository
{ {
IEnumerable<Case> ReadCases(); IEnumerable<Case> ReadCases(DateTime? dateTo = null);
Case ReadCaseById(int id); Case ReadCaseById(int id);
void CreateCase(Case caseEntity); void CreateCase(Case caseEntity);
void DeleteCase(int id); void DeleteCase(int id);

View File

@ -4,6 +4,7 @@ using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Npgsql; using Npgsql;
using ProjectGSM.Entities; using ProjectGSM.Entities;
using ProjectGSM.Query;
namespace ProjectGSM.Repositories.Implementations; namespace ProjectGSM.Repositories.Implementations;
@ -25,14 +26,20 @@ public class CaseAdvocatesRepository : ICaseAdvocateRepository
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
var builder = new QueryBuilder();
if (dateTo.HasValue)
{
builder.AddCondition("ca.CreatedAt <= @dateTo");
}
using var connection = new using var connection = new
NpgsqlConnection(_connectionString.ConnectionString); NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = var querySelect =
"SELECT ca.*, a.name as AdvocateName, cs.description as CaseDescription " + "SELECT ca.*, a.name as AdvocateName, cs.description as CaseDescription " +
"FROM case_advocates as ca LEFT JOIN cases as cs ON cs.id = ca.caseid " + "FROM case_advocates as ca LEFT JOIN cases as cs ON cs.id = ca.caseid " +
"LEFT JOIN advocates as a ON a.id = ca.advocateid"; $"LEFT JOIN advocates as a ON a.id = ca.advocateid {builder.Build()}";
var caseAdvocates = var caseAdvocates =
connection.Query<CaseAdvocate>(querySelect); connection.Query<CaseAdvocate>(querySelect, param: new { dateTo });
_logger.LogDebug("Полученные объекты: {json}", _logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(caseAdvocates)); JsonSerializer.Serialize(caseAdvocates));
return caseAdvocates; return caseAdvocates;

View File

@ -1,9 +1,11 @@
using System.Data.SqlClient; using System.Data.SqlClient;
using System.Text.Json;
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql; using Npgsql;
using ProjectGSM.Entities; using ProjectGSM.Entities;
using ProjectGSM.Query;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace ProjectGSM.Repositories.Implementations; namespace ProjectGSM.Repositories.Implementations;
@ -19,22 +21,51 @@ public class CaseRepository : ICaseRepository
_logger = logger; _logger = logger;
} }
public IEnumerable<Case> ReadCases() public IEnumerable<Case> ReadCases(DateTime? dateTo = null)
{ {
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
var builder = new QueryBuilder();
if (dateTo.HasValue)
{
builder.AddCondition("cases.CreatedAt <= @dateTo");
}
using var connection = new using var connection = new
NpgsqlConnection(_connectionString.ConnectionString); NpgsqlConnection(_connectionString.ConnectionString);
var querySelect =
"SELECT cases.*, courts.name as CourtName, clients.name as ClientName " +
"FROM cases LEFT JOIN courts on courts.Id = cases.courtid " +
"LEFT JOIN clients on clients.Id = cases.clientid";
var cases = connection.Query<Case>(querySelect);
var querySelect =
"SELECT cases.*, courts.name as CourtName, clients.name as ClientName, ca.caseid as CaseId, a.name as AdvocateName " +
"FROM cases " +
"LEFT JOIN courts on courts.Id = cases.courtid " +
"LEFT JOIN clients on clients.Id = cases.clientid " +
"INNER JOIN case_advocates ca ON ca.caseid = cases.Id LEFT JOIN advocates a on a.Id = ca.advocateid " +
$"{builder.Build()}";
// $"{builder.Build()}";
var casesDict = new Dictionary<int, List<CaseAdvocate>>();
;
var cases = connection.Query<Case, CaseAdvocate, Case>(querySelect,
(caseEntity, caseAdvocate) =>
{
if (!casesDict.TryGetValue(caseEntity.Id, out var ca))
{
ca = new List<CaseAdvocate>();
casesDict.Add(caseEntity.Id, ca);
}
ca.Add(caseAdvocate);
return caseEntity;
}, splitOn: "CaseId", param: new { dateTo, });
_logger.LogDebug("Полученные объекты: {json}", _logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(cases)); JsonConvert.SerializeObject(cases));
return cases; return casesDict.Select(x =>
{
var caseEntity = cases.First(y => y.Id == x.Key);
caseEntity.SetAdvocates(x.Value);
return caseEntity;
}).ToArray();
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -43,7 +43,7 @@ public class StatusHistoryRepository : IStatusHistoryRepository
using var connection = new using var connection = new
NpgsqlConnection(_connectionString.ConnectionString); NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = var querySelect =
@$"SELECT sh.*, c.description as CaseDescription FROM status_histories as sh LEFT JOIN cases as c ON c.id = sh.caseid{builder.Build()}"; @$"SELECT sh.*, c.description as CaseDescription FROM status_histories as sh LEFT JOIN cases as c ON c.id = sh.caseid {builder.Build()}";
var statusHistories = var statusHistories =
connection.Query<StatusHistory>(querySelect, new { dateForm, dateTo, caseId }); connection.Query<StatusHistory>(querySelect, new { dateForm, dateTo, caseId });
_logger.LogDebug("Полученные объекты: {json}", _logger.LogDebug("Полученные объекты: {json}",