Лаба4, промежуток.

This commit is contained in:
MariaBelkina 2024-12-25 11:42:32 +04:00
parent 76db4ba2e3
commit c9d4eb055c
22 changed files with 270 additions and 95 deletions

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -11,18 +12,27 @@ public class Agent
{
public int Id { get; private set; }
[DisplayName("Имя")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Фамилия")]
public string Surname { get; private set; } = string.Empty;
[DisplayName("Квалификация")]
public Qualification Qualification { get; private set; }
[DisplayName("Категория")]
public Category Category { get; private set; }
public static Agent CreateEntity(int id, string name, Qualification qualification, Category category)
public string FullName => $"{Name} {Surname}";
public static Agent CreateEntity(int id, string name, string surname, Qualification qualification, Category category)
{
return new Agent
{
Id = id,
Name = name ?? string.Empty,
Surname = surname ?? string.Empty,
Qualification = qualification,
Category = category
};

View File

@ -1,5 +1,7 @@
using System;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,12 +12,27 @@ public class Contract
{
public int ID { get; private set; }
[DisplayName("Дата продажи")]
public DateTime SaleDate { get; private set; }
[Browsable(false)]
public int PurchasingCompanyID { get; private set; }
[Browsable(false)]
public int AgentsID { get; private set; }
[DisplayName("Агент-реализатор")]
public string AgentsName { get; private set; } = string.Empty;
[DisplayName("Компания-закупщик")]
public string CompanyName { get; private set; } = string.Empty;
[DisplayName("Номенклатура")]
public string Product => ProductSales != null ?
string.Join(", ", ProductSales.Select(x => $"{x.ProductName} {x.ProductQuantity}")) :
string.Empty;
[Browsable(false)]
public IEnumerable<ProductSales> ProductSales { get; private set; } = [];
public static Contract CreateOperation(int contractID, int purchasingCompanyID, int agentsID, IEnumerable<ProductSales> productSales)
@ -30,16 +47,11 @@ public class Contract
};
}
public static Contract CreateOperation(TempProductSales tempProductSales,
IEnumerable<ProductSales> productSales)
public void SetProductSales(IEnumerable<ProductSales> productSales)
{
return new Contract
if (productSales != null && productSales.Any())
{
ID = tempProductSales.ID,
AgentsID = tempProductSales.AgentsId,
SaleDate = tempProductSales.SaleDate,
PurchasingCompanyID = tempProductSales.PurchasingCompanyId,
ProductSales = productSales
};
ProductSales = productSales;
}
}
}

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -9,12 +10,25 @@ namespace TradeAndProcurementEnterprice.Entities;
public class DelegateToAgents
{
public int Id { get; private set; }
[Browsable(false)]
public int ProductArticle { get; private set; }
[Browsable(false)]
public int AgentsID { get; private set; }
[DisplayName("Номенклатура")]
public string ProductName { get; private set; } = string.Empty;
[DisplayName("Имя агента")]
public string AgentsName { get; private set; } = string.Empty;
[DisplayName("Количество товара")]
public int Quantity { get; private set; }
[DisplayName("Дата передачи")]
public DateTime Date { get; private set; }
public static DelegateToAgents CreateOperation(int id, int productArticle, int agentsID, int quantity)

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using TradeAndProcurementEnterprice.Entities.Enums;
namespace TradeAndProcurementEnterprice.Entities;
@ -11,14 +7,20 @@ public class Product
{
public int Article { get; private set; }
[DisplayName("Номенклатура")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Цена")]
public decimal SellingPrice { get; private set; }
[DisplayName("Единица измерения")]
public Units Unit { get; private set; }
[DisplayName("Категория")]
public Category Category { get; private set; }
[DisplayName("Количество на складе")]
public int InventoryQuantity { get; private set; }
public static Product CreateEntity(int article, string name, decimal sellingPrice, Units unit,

View File

@ -12,6 +12,8 @@ public class ProductSales
public int ProductArticle { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public int ProductQuantity { get; private set; }
public static ProductSales CreateElement(int id, int prodictArticle, int productQuantity)

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,6 +11,7 @@ public class PurchasingCompany
{
public int Id { get; private set; }
[DisplayName("Наименование компании")]
public string Name { get; private set; } = string.Empty;
public static PurchasingCompany CreateEntity(int id, string name)

View File

@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities;
public class TempProductSales
{
public int ID { get; private set; }
public int AgentsId { get; private set; }
public DateTime SaleDate { get; private set; }
public int PurchasingCompanyId { get; private set; }
public int ProductArticle { get; private set; }
public int ProductQuantity { get; private set; }
}

View File

@ -36,15 +36,16 @@
labelQualification = new Label();
labelName = new Label();
checkedListBoxCategory = new CheckedListBox();
labelSurname = new Label();
textBoxSurname = new TextBox();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(280, 412);
buttonCancel.Margin = new Padding(6, 6, 6, 6);
buttonCancel.Location = new Point(151, 227);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(156, 49);
buttonCancel.Size = new Size(84, 23);
buttonCancel.TabIndex = 16;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@ -53,10 +54,9 @@
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(80, 412);
buttonSave.Margin = new Padding(6, 6, 6, 6);
buttonSave.Location = new Point(43, 227);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(156, 49);
buttonSave.Size = new Size(84, 23);
buttonSave.TabIndex = 17;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
@ -67,76 +67,88 @@
comboBoxQualification.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxQualification.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxQualification.FormattingEnabled = true;
comboBoxQualification.Location = new Point(217, 124);
comboBoxQualification.Margin = new Padding(6, 6, 6, 6);
comboBoxQualification.Location = new Point(115, 103);
comboBoxQualification.Name = "comboBoxQualification";
comboBoxQualification.Size = new Size(273, 40);
comboBoxQualification.Size = new Size(149, 23);
comboBoxQualification.TabIndex = 14;
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxName.Location = new Point(217, 38);
textBoxName.Margin = new Padding(6, 6, 6, 6);
textBoxName.Location = new Point(117, 18);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(273, 39);
textBoxName.Size = new Size(149, 23);
textBoxName.TabIndex = 11;
//
// labelCategory
//
labelCategory.AutoSize = true;
labelCategory.Location = new Point(39, 220);
labelCategory.Margin = new Padding(6, 0, 6, 0);
labelCategory.Location = new Point(19, 148);
labelCategory.Name = "labelCategory";
labelCategory.Size = new Size(126, 32);
labelCategory.Size = new Size(63, 15);
labelCategory.TabIndex = 7;
labelCategory.Text = "Категория";
//
// labelQualification
//
labelQualification.AutoSize = true;
labelQualification.Location = new Point(43, 130);
labelQualification.Margin = new Padding(6, 0, 6, 0);
labelQualification.Location = new Point(21, 106);
labelQualification.Name = "labelQualification";
labelQualification.Size = new Size(174, 32);
labelQualification.Size = new Size(88, 15);
labelQualification.TabIndex = 8;
labelQualification.Text = "Квалификация";
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(39, 53);
labelName.Margin = new Padding(6, 0, 6, 0);
labelName.Location = new Point(21, 25);
labelName.Name = "labelName";
labelName.Size = new Size(67, 32);
labelName.Size = new Size(31, 15);
labelName.TabIndex = 10;
labelName.Text = "ФИО";
labelName.Text = "Имя";
//
// checkedListBoxCategory
//
checkedListBoxCategory.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
checkedListBoxCategory.FormattingEnabled = true;
checkedListBoxCategory.Location = new Point(217, 211);
checkedListBoxCategory.Margin = new Padding(6, 6, 6, 6);
checkedListBoxCategory.Location = new Point(115, 144);
checkedListBoxCategory.Name = "checkedListBoxCategory";
checkedListBoxCategory.Size = new Size(273, 148);
checkedListBoxCategory.Size = new Size(149, 58);
checkedListBoxCategory.TabIndex = 18;
//
// labelSurname
//
labelSurname.AutoSize = true;
labelSurname.Location = new Point(21, 66);
labelSurname.Name = "labelSurname";
labelSurname.Size = new Size(58, 15);
labelSurname.TabIndex = 10;
labelSurname.Text = "Фамилия";
//
// textBoxSurname
//
textBoxSurname.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxSurname.Location = new Point(117, 59);
textBoxSurname.Name = "textBoxSurname";
textBoxSurname.Size = new Size(149, 23);
textBoxSurname.TabIndex = 12;
//
// FormAgent
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(549, 504);
ClientSize = new Size(301, 285);
Controls.Add(checkedListBoxCategory);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(comboBoxQualification);
Controls.Add(textBoxSurname);
Controls.Add(textBoxName);
Controls.Add(labelCategory);
Controls.Add(labelSurname);
Controls.Add(labelQualification);
Controls.Add(labelName);
Margin = new Padding(6, 6, 6, 6);
MinimumSize = new Size(575, 575);
MinimumSize = new Size(317, 290);
Name = "FormAgent";
StartPosition = FormStartPosition.CenterParent;
Text = "Агент-реализатор";
@ -154,5 +166,7 @@
private Label labelQualification;
private Label labelName;
private CheckedListBox checkedListBoxCategory;
private Label labelSurname;
private TextBox textBoxSurname;
}
}

View File

@ -35,6 +35,7 @@ namespace TradeAndProcurementEnterprice.Forms
}
textBoxName.Text = agent.Name;
textBoxSurname.Text = agent.Surname;
comboBoxQualification.SelectedItem = agent.Qualification; foreach (Category elem in Enum.GetValues(typeof(Category)))
{
if ((elem & agent.Category) != 0)
@ -69,7 +70,8 @@ namespace TradeAndProcurementEnterprice.Forms
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text) || checkedListBoxCategory.CheckedItems.Count == 0 || comboBoxQualification.SelectedIndex < 1)
if (string.IsNullOrWhiteSpace(textBoxName.Text) || string.IsNullOrWhiteSpace(textBoxSurname.Text) ||
checkedListBoxCategory.CheckedItems.Count == 0 || comboBoxQualification.SelectedIndex < 1)
{
throw new Exception("Имеются незаполненные поля!");
}
@ -101,7 +103,7 @@ namespace TradeAndProcurementEnterprice.Forms
category |= (Category)elem;
}
return Agent.CreateEntity(id, textBoxName.Text, (Qualification)comboBoxQualification.SelectedItem,
return Agent.CreateEntity(id, textBoxName.Text, textBoxSurname.Text, (Qualification)comboBoxQualification.SelectedItem,
category);
}
}

View File

@ -97,7 +97,12 @@ namespace TradeAndProcurementEnterprice.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _agentsRepository.ReadAgents();
private void LoadList()
{
dataGridViewData.DataSource = _agentsRepository.ReadAgents();
dataGridViewData.Columns["Id"].Visible = false;
dataGridViewData.Columns["FullName"].Visible = false;
}
private bool TryGetIdFromSelectedRow(out int id)
{

View File

@ -29,7 +29,7 @@ namespace TradeAndProcurementEnterprice.Forms
comboBoxPurchasingCompany.ValueMember = "Id";
comboBoxAgent.DataSource = agentsRepository.ReadAgents();
comboBoxAgent.DisplayMember = "Name";
comboBoxAgent.DisplayMember = "FullName";
comboBoxAgent.ValueMember = "Id";
ColumnProduct.DataSource = productRepository.ReadProducts();

View File

@ -53,6 +53,11 @@ namespace TradeAndProcurementEnterprice.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _contractRepository.ReadContracts();
private void LoadList()
{
dataGridViewData.DataSource = _contractRepository.ReadContracts();
dataGridViewData.Columns["Id"].Visible = false;
dataGridViewData.Columns["SaleDate"].DefaultCellStyle.Format = "dd.MM.yyyy";
}
}
}

View File

@ -28,7 +28,7 @@ namespace TradeAndProcurementEnterprice.Forms
comboBoxProduct.ValueMember = "Article";
comboBoxAgent.DataSource = agentsRepository.ReadAgents();
comboBoxAgent.DisplayMember = "Name";
comboBoxAgent.DisplayMember = "FullName";
comboBoxAgent.ValueMember = "Id";
}

View File

@ -51,6 +51,11 @@ namespace TradeAndProcurementEnterprice.Forms
MessageBox.Show(ex.Message, "Ошибка при добавлении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _delegateToAgentRepository.ReadDelegatesToAgent();
private void LoadList()
{
dataGridViewData.DataSource = _delegateToAgentRepository.ReadDelegatesToAgent();
dataGridViewData.Columns["Id"].Visible = false;
dataGridViewData.Columns["Date"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm";
}
}
}

View File

@ -95,7 +95,11 @@ namespace TradeAndProcurementEnterprice.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _productRepository.ReadProducts();
private void LoadList()
{
dataGridViewData.DataSource = _productRepository.ReadProducts();
dataGridViewData.Columns["Article"].Visible = false;
}
private bool TryGetIdFromSelectedRow(out int id)
{

View File

@ -97,8 +97,11 @@ namespace TradeAndProcurementEnterprice.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _companyRepository.ReadCompanies();
private void LoadList()
{
dataGridViewData.DataSource = _companyRepository.ReadCompanies();
dataGridViewData.Columns["Id"].Visible = false;
}
private bool TryGetIdFromSelectedRow(out int id)
{
id = 0;

View File

@ -35,7 +35,7 @@ internal class TableReport
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по передвижению товара", 0, 4)
.AddParagraph("За период", 0)
.AddParagraph($"За период с {startDate: dd.MM.yyyy} по {endDate: dd.MM.yyyy}", 0)
.AddTable([10, 10, 15, 15], GetData(productArticle, startDate, endDate))
.Build();
@ -51,11 +51,10 @@ internal class TableReport
private List<string[]> GetData(int productArticle, DateTime startDate, DateTime endDate)
{
var data = _contractRepository
.ReadContracts()
.Where(x => x.SaleDate >= startDate && x.SaleDate <= endDate && x.ProductSales.Any(y => y.ProductArticle == productArticle))
.ReadContracts(dateFrom: startDate, dateTo: endDate, productArticle: productArticle)
.Select(x => new
{
x.AgentsID,
x.AgentsName,
CurrentDate = x.SaleDate,
CountIn = (int?)null,
CountOut = x.ProductSales.FirstOrDefault(y => y.ProductArticle == productArticle)?.ProductQuantity
@ -66,7 +65,7 @@ internal class TableReport
.Where(x => x.Date >= startDate && x.Date <= endDate && x.ProductArticle == productArticle)
.Select(x => new
{
x.AgentsID,
x.AgentsName,
CurrentDate = x.Date,
CountIn = (int?)x.Quantity,
CountOut = (int?)null

View File

@ -10,7 +10,7 @@ namespace TradeAndProcurementEnterprice.Repositories;
public interface IContractRepository
{
IEnumerable<Contract> ReadContracts(DateTime? dateFrom = null, DateTime? dateTo = null,
int? productArticle = null, int? agentID = null, int? purchasingCompaniID = null);
int? productArticle = null, int? agentID = null, int? purchasingCompanyID = null);
void CreateContract(Contract contract);
}

View File

@ -34,8 +34,8 @@ internal class AgentsRepository : IAgentsRepository
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Agents (Name, Qualification, Category)
VALUES (@Name, @Qualification, @Category)";
INSERT INTO Agents (Name, Surname, Qualification, Category)
VALUES (@Name, @Surname, @Qualification, @Category)";
connection.Execute(queryInsert, agent);
}
catch (Exception ex)
@ -118,6 +118,7 @@ WHERE Id=@id";
UPDATE Agents
SET
Name=@Name,
Surname=@Surname,
Qualification=@Qualification,
Category=@Category
WHERE Id=@Id";

View File

@ -57,20 +57,75 @@ VALUES (@ID, @ProductArticle, @ProductQuantity)";
}
}
public IEnumerable<Contract> ReadContracts(DateTime? dateFrom = null, DateTime? dateTo = null, int? productArticle = null, int? agentID = null, int? purchasingCompaniID = null)
public IEnumerable<Contract> ReadContracts(DateTime? dateFrom = null, DateTime? dateTo = null, int? productArticle = null,
int? agentID = null, int? purchasingCompanyID = null)
{
_logger.LogInformation("Получение всех объектов.");
try
{
var builder = new QueryBuilder();
if (dateFrom.HasValue)
{
builder.AddCondition("c.SaleDate >= @dateForm");
}
if (dateTo.HasValue)
{
builder.AddCondition("c.SaleDate <= @dateTo");
}
if (productArticle.HasValue)
{
builder.AddCondition("c.ProductArticle = @productArticle");
}
if (agentID.HasValue)
{
builder.AddCondition("c.AgentsId = @agentsID");
}
if (purchasingCompanyID.HasValue)
{
builder.AddCondition("c.PurchasingCompanyID = @purchasingCompanyID");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT c.*, ps.ProductArticle, ps.ProductQuantity FROM Contracts c
INNER JOIN ProductSales ps ON ps.ID = c.ID";
var contracts = connection.Query<TempProductSales>(querySelect);
var querySelect = @$"
SELECT
c.*,
CONCAT(a.Name, ' ', a.Surname) as AgentsName,
pc.Name as CompanyName,
ps.ProductArticle,
ps.ProductQuantity,
p.Name as ProductName
FROM Contracts c
LEFT JOIN Agents a on a.Id = c.AgentsId
LEFT JOIN purchasingcompanies pc on pc.Id = c.PurchasingCompanyID
INNER JOIN ProductSales ps ON ps.ID = c.ID
LEFT JOIN Products p on p.Article = ps.ProductArticle
{builder.Build()}";
var salesDict = new Dictionary<int, List<ProductSales>>();
var contracts = connection.Query<Contract, ProductSales, Contract>(querySelect,
(sales, contract) =>
{
if (!salesDict.TryGetValue(sales.ID, out var ps))
{
ps = [];
salesDict.Add(sales.ID, ps);
}
ps.Add(contract);
return sales;
}, splitOn: "ProductArticle", param: new { dateFrom, dateTo, productArticle, agentID, purchasingCompanyID });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(contracts));
return contracts.GroupBy(x => x.ID, y => y,
(key, value) => Contract.CreateOperation(value.First(),
value.Select(z => ProductSales.CreateElement(0, z.ProductArticle, z.ProductQuantity)))).ToList();
return salesDict.Select(x =>
{
var c = contracts.First(y => y.ID == x.Key);
c.SetProductSales(x.Value);
return c;
}).ToArray();
}
catch (Exception ex)
{

View File

@ -43,13 +43,38 @@ VALUES (@ProductArticle, @AgentsID, @Quantity, @Date)";
}
}
public IEnumerable<DelegateToAgents> ReadDelegatesToAgent(DateTime? dateFrom = null, DateTime? dateTo = null, int? productArticle = null, int? agentID = null)
public IEnumerable<DelegateToAgents> ReadDelegatesToAgent(DateTime? dateFrom = null, DateTime? dateTo = null,
int? productArticle = null, int? agentID = null)
{
_logger.LogInformation("Получение всех объектов.");
try
{
/*var builder = new QueryBuilder();
if (dateFrom.HasValue)
{
builder.AddCondition("dta.Date >= @dateFrom"); }
if (dateTo.HasValue)
{
builder.AddCondition("dta.Date <= @dateTo");
}
if (productArticle.HasValue)
{
builder.AddCondition("dta.ProductArticle = @productArticle");
}
if (agentID.HasValue)
{
builder.AddCondition("dta.AgentsId = @agentsID");
}*/
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM DelegateToAgents";
var querySelect = @$"SELECT
dta.*,
p.Name as ProductName,
CONCAT(a.Name, ' ', a.Surname) as AgentsName
FROM DelegateToAgents dta
LEFT JOIN Agents a on a.Id = dta.AgentsId
LEFT JOIN Products p on p.Article = dta.ProductArticle";
//{builder.Build()}";
var delegatesToAgents = connection.Query<DelegateToAgents>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(delegatesToAgents));
return delegatesToAgents;

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Repositories.Implementations;
internal class QueryBuilder
{
private readonly StringBuilder _builder;
public QueryBuilder()
{
_builder = new();
}
public QueryBuilder AddCondition(string condition)
{
if (_builder.Length > 0)
{
_builder.Append(" AND ");
}
_builder.Append(condition);
return this;
}
public string Build()
{
if (_builder.Length == 0)
{
return string.Empty;
}
return $"WHERE {_builder}";
}
}