ПИбд-23. Кадышев М.И. Лабораторная работа 3 #3

Closed
nezui wants to merge 6 commits from LabWork_3 into LabWork_2
16 changed files with 307 additions and 111 deletions
Showing only changes of commit 56812e25df - Show all commits

View File

@ -8,16 +8,16 @@ namespace ProjectCompRepair.Entities;
public class AccessoiresOrder
{
public int Id { get; private set; }
public int OrderId { get; private set; }
public int AccessoriesId { get; private set; }
public int Count { get; private set; }
public static AccessoiresOrder CreateElement(int id, int orderId, int count)
public static AccessoiresOrder CreateElement(int orderId, int count, int accessoriesId)
{
return new AccessoiresOrder { Id = id, OrderId = orderId, Count = count };
return new AccessoiresOrder { OrderId = orderId, Count = count, AccessoriesId = accessoriesId};
}
}

View File

@ -37,4 +37,18 @@ public class Order
};
}
public static Order CreateElement(TempAccessoriesOrder tempAccessoriesOrder, IEnumerable<AccessoiresOrder> accessoiresOrder)
{
return new Order
{
Id = tempAccessoriesOrder.Id,
Name = tempAccessoriesOrder.Name,
Coment = tempAccessoriesOrder.Coment,
Date = tempAccessoriesOrder.Date,
MasterID = tempAccessoriesOrder.MasterID,
AccessoiresOrders = accessoiresOrder,
ServicesOrders = tempAccessoriesOrder.ServicesOrders
};
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectCompRepair.Entities;
public class TempAccessoriesOrder
{
public int Id { get; private set; }
public string Name { get; private set; }
public string Coment { get; private set; }
public DateTime Date { get; private set; }
public int MasterID { get; private set; }
public int AccessoriesId { get; private set; }
public int Count { get; private set; }
public IEnumerable<AccessoiresOrder> AccessoiresOrders { get; private set; }
public IEnumerable<ServicesOrder> ServicesOrders { get; private set; }
}

View File

@ -112,7 +112,7 @@
//
excelToolStripMenuItem.Name = "excelToolStripMenuItem";
excelToolStripMenuItem.Size = new Size(294, 26);
excelToolStripMenuItem.Text = "Excel";
excelToolStripMenuItem.Text = "Поток комплектующих";
excelToolStripMenuItem.Click += excelToolStripMenuItem_Click;
//
// FormCompRepair

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Microsoft ResX Schema
Version 2.0
@ -48,7 +48,7 @@
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter

View File

@ -0,0 +1,128 @@
namespace ProjectCompRepair.Forms
{
partial class FormAccessoriesOrderReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonSelectFileName = new Button();
labelFileName = new Label();
dateTimePicker = new DateTimePicker();
labelDate = new Label();
buttonCreate = new Button();
comboBoxAccessories = new ComboBox();
labelAccessories = new Label();
SuspendLayout();
//
// buttonSelectFileName
//
buttonSelectFileName.Location = new Point(12, 25);
buttonSelectFileName.Name = "buttonSelectFileName";
buttonSelectFileName.Size = new Size(94, 29);
buttonSelectFileName.TabIndex = 0;
buttonSelectFileName.Text = "Выбрать";
buttonSelectFileName.UseVisualStyleBackColor = true;
//
// labelFileName
//
labelFileName.AutoSize = true;
labelFileName.Location = new Point(136, 29);
labelFileName.Name = "labelFileName";
labelFileName.Size = new Size(45, 20);
labelFileName.TabIndex = 1;
labelFileName.Text = "Файл";
//
// dateTimePicker
//
dateTimePicker.Location = new Point(67, 97);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(250, 27);
dateTimePicker.TabIndex = 2;
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(19, 100);
labelDate.Name = "labelDate";
labelDate.Size = new Size(44, 20);
labelDate.TabIndex = 3;
labelDate.Text = "Дата:";
//
// buttonCreate
//
buttonCreate.Location = new Point(136, 178);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(94, 29);
buttonCreate.TabIndex = 4;
buttonCreate.Text = "Сформировать";
buttonCreate.UseVisualStyleBackColor = true;
//
// comboBoxAccessories
//
comboBoxAccessories.FormattingEnabled = true;
comboBoxAccessories.Location = new Point(376, 100);
comboBoxAccessories.Name = "comboBoxAccessories";
comboBoxAccessories.Size = new Size(151, 28);
comboBoxAccessories.TabIndex = 5;
//
// labelAccessories
//
labelAccessories.AutoSize = true;
labelAccessories.Location = new Point(387, 66);
labelAccessories.Name = "labelAccessories";
labelAccessories.Size = new Size(124, 20);
labelAccessories.TabIndex = 6;
labelAccessories.Text = "Комплектующие";
//
// FormAccessoriesOrderReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(539, 219);
Controls.Add(labelAccessories);
Controls.Add(comboBoxAccessories);
Controls.Add(buttonCreate);
Controls.Add(labelDate);
Controls.Add(dateTimePicker);
Controls.Add(labelFileName);
Controls.Add(buttonSelectFileName);
Name = "FormAccessoriesOrderReport";
Text = "FormAccessoriesType";
ResumeLayout(false);
PerformLayout();
Review

Заголовок формы оформлен неверно

Заголовок формы оформлен неверно
}
#endregion
private Button buttonSelectFileName;
private Label labelFileName;
private DateTimePicker dateTimePicker;
private Label labelDate;
private Button buttonCreate;
private ComboBox comboBoxAccessories;
private Label labelAccessories;
}
}

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectCompRepair.Entities.Enums;
using ProjectCompRepair.Reports;
using ProjectCompRepair.Repositories;
using Unity;
namespace ProjectCompRepair.Forms
{
public partial class FormAccessoriesOrderReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormAccessoriesOrderReport(IUnityContainer container, IAccessoriesRepository accessoriesRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
comboBoxAccessories.DataSource = Enum.GetValues(typeof(AccessoriesType));
}
private void ButtonSelectFileName_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
_fileName = sfd.FileName;
labelFileName.Text = Path.GetFileName(_fileName);
}
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if
(_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePicker.Value, (int)comboBoxAccessories.SelectedIndex!))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Microsoft ResX Schema
Version 2.0
@ -48,7 +48,7 @@
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter

View File

@ -1,45 +0,0 @@
namespace ProjectCompRepair.Forms
{
partial class FormAccessorieslDistributionReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
SuspendLayout();
//
// FormAccessorieslDistributionReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(432, 362);
Name = "FormAccessorieslDistributionReport";
Text = "FormAccessorieslDistributionReport";
ResumeLayout(false);
}
#endregion
}
}

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectCompRepair.Forms
{
public partial class FormAccessorieslDistributionReport : Form
{
public FormAccessorieslDistributionReport()
{
InitializeComponent();
}
}
}

View File

@ -16,7 +16,7 @@ public partial class FormOrder : Form
{
private readonly IOrderRepository _orderRepository;
private int? _orderId;
private int _orderId;
public int Id
{
@ -92,9 +92,9 @@ public partial class FormOrder : Form
{
continue;
}
list.Add(AccessoiresOrder.CreateElement(0,
Convert.ToInt32(row.Cells["ColumnAccessories"].Value),
Convert.ToInt32(row.Cells["ColumnCount"].Value)));
list.Add(AccessoiresOrder.CreateElement(
0,
Convert.ToInt32(row.Cells["ColumnCount"].Value), Convert.ToInt32(row.Cells["ColumnAccessories"].Value)));
}
return list;
}

View File

@ -1,5 +1,7 @@
using Microsoft.Extensions.Logging;
using ProjectCompRepair.Entities;
using ProjectCompRepair.Repositories;
using ProjectCompRepair.Repositories.Implemantations;
using System;
using System.Collections.Generic;
using System.Linq;
@ -10,22 +12,22 @@ namespace ProjectCompRepair.Reports;
internal class ChartReport
{
private readonly IAccessoriesRepository _accessoriesRepository;
private readonly IOrderRepository _orderRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IAccessoriesRepository accessoriesRepository, ILogger<ChartReport> logger)
public ChartReport(IOrderRepository orderRepository, ILogger<ChartReport> logger)
{
_accessoriesRepository = accessoriesRepository ?? throw new ArgumentNullException(nameof(accessoriesRepository));
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, DateTime dateTime)
public bool CreateChart(string filePath, DateTime dateTime, int accessoriesId)
{
try
{
new PdfBuilder(filePath)
.AddHeader("Комплектующих")
.AddPieChart("потраченные комплектующие", GetData(dateTime))
.AddHeader("Комплектующие")
.AddPieChart("потраченные комплектующие", GetData(dateTime, accessoriesId))
.Build();
return true;
}
@ -36,12 +38,16 @@ internal class ChartReport
}
}
private List<(string Caption, double Value)> GetData(DateTime dateTime)
private List<(string Caption, double Value)> GetData(DateTime dateTime, int accessoriesId)
{
return _accessoriesRepository
.ReadAccessories()
return _orderRepository
.ReadOrder()
.Where(x => x.Date.Date == dateTime.Date)
.GroupBy(x => x.Id, (key, group) => new { Id = key, Count = group.Sum(x => x.Count) })
.GroupBy(x => x.Id, (key, group) => new
{
Id = key,
Count = group.Sum(x => x.AccessoiresOrders.FirstOrDefault(y => y.AccessoriesId == accessoriesId)?.Count ?? 0)
})
.Select(x => (x.Id.ToString(), (double)x.Count))
.ToList();
}

View File

@ -63,10 +63,10 @@ internal class ExcelBuilder
{
throw new ArgumentNullException(nameof(data));
}
//if (data.Any(x => x.Length != columnsWidths.Length))
//{
// throw new InvalidOperationException("widths.Length != data.Length");
//}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;

View File

@ -29,7 +29,7 @@ internal class TableReport
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по движению корма", 0, 4)
.AddHeader("Поставка комплектующих", 0, 3)
.AddParagraph("за период", 0)
.AddTable([10, 15, 15], GetData(accessoriesId, startDate, endDate))
.Build();
@ -45,21 +45,21 @@ internal class TableReport
private List<string[]> GetData(int accessoriesId, DateTime startDate, DateTime endDate)
{
var data = _orderRepository.ReadOrder()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.AccessoiresOrders.Any(y => y.Id == y.Id))
.Select(x => new {Date = x.Date, CountIn = x.AccessoiresOrders.FirstOrDefault(y => y.Id == accessoriesId)?.Count, CountOut = (int?)null })
.Where(x => x.Date >= startDate && x.Date <= endDate && x.AccessoiresOrders.Any(y => y.AccessoriesId == accessoriesId))
.Select(x => new {Date = x.Date, CountIn = (int?)null, CountOut = x.AccessoiresOrders.FirstOrDefault(y => y.AccessoriesId == accessoriesId)?.Count, })
.Union(
_accessoriesRepository
.ReadAccessories()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.Id == accessoriesId)
.Select(x => new {Date = x.Date, CountIn = (int?)null, CountOut = (int?)x.Count }))
.Select(x => new {Date = x.Date, CountIn = (int?)x.Count, CountOut = (int?)null }))
.OrderBy(x => x.Date);
return new List<string[]>() { item }
.Union(
data
.Select(x => new string[] { x.Date.ToString(), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Select(x => new string[] { x.Date.ToString("yyyy-MM-dd"), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Union(
[["Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]])
[["Всего", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]])
.ToList();
}
}

View File

@ -11,7 +11,7 @@ namespace ProjectCompRepair.Repositories;
public interface IOrderRepository
{
IEnumerable<Order> ReadOrder();
IEnumerable<Order> ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null, int? serviceId = null);
Order ReadOrderById(int id);

View File

@ -41,14 +41,15 @@
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
var querySubInsertAccessories = @"
INSERT INTO AccessoriesOrder (OrderId, Count)
VALUES (@OrderId, @Count)";
INSERT INTO AccessoriesOrder (AccessoriesId, OrderId, Count)
VALUES (@AccessoriesId,@OrderId, @Count)";
foreach (var elem in order.AccessoiresOrders)
{
connection.Execute(querySubInsertAccessories, new
{
OrderId = orderId,
{
elem.AccessoriesId,
orderId,
elem.Count
}, transaction);
}
@ -121,7 +122,7 @@
}
}
public IEnumerable<Order> ReadOrder()
public IEnumerable<Order> ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null, int? serviceId = null)
{
_logger.LogInformation("Получение всех объектов");
try
@ -129,20 +130,25 @@
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Orderl";
var order = connection.Query<Order>(querySelect);
var querySelect = @"SELECT o.*, ao.AccessoriesId, ao.Count
FROM Orderl o
INNER JOIN AccessoriesOrder ao ON ao.OrderId = o.ID;";
var order = connection.Query<TempAccessoriesOrder>(querySelect);
_logger.LogDebug("Полученные объекты : {json}", JsonConvert.SerializeObject(order));
return order;
}
return order.GroupBy(x => x.Id, y => y,
(key, value) => Order.CreateElement(value.First(),
value.Select(z => AccessoiresOrder.CreateElement(0, z.AccessoriesId, z.Count)))).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}