осталось немного починить

This commit is contained in:
RozhVan 2024-12-21 15:34:40 +04:00
parent 07e82fc4a3
commit 71a39fa73e
25 changed files with 246 additions and 102 deletions

View File

@ -1,4 +1,5 @@
using GasStation.Entities.Enums; using GasStation.Entities.Enums;
using System.ComponentModel;
namespace GasStation.Entities; namespace GasStation.Entities;
@ -6,10 +7,13 @@ public class Gasman
{ {
public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Имя заправщика")]
public string GasmanName { get; private set; } = string.Empty; public string GasmanName { get; private set; } = string.Empty;
[DisplayName("Телефон")]
public string PhoneNumber { get; private set; } = string.Empty; public string PhoneNumber { get; private set; } = string.Empty;
[DisplayName("Должность")]
public Post Post { get; private set; } public Post Post { get; private set; }
public static Gasman CreateGasman(int id, string gasmanName, string phoneNumber, Post post) public static Gasman CreateGasman(int id, string gasmanName, string phoneNumber, Post post)

View File

@ -1,4 +1,5 @@
using GasStation.Entities.Enums; using GasStation.Entities.Enums;
using System.ComponentModel;
namespace GasStation.Entities; namespace GasStation.Entities;
@ -6,15 +7,23 @@ public class Product
{ {
public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Стоимость товара")]
public int ProductCost { get; private set; } public int ProductCost { get; private set; }
[DisplayName("Тип товара")]
public ProductType ProductType { get; private set; } public ProductType ProductType { get; private set; }
public static Product CreateProduct(int id, int productCost, ProductType productType) [DisplayName("Название товара")]
public string ProductName { get; private set; } = string.Empty;
public string FullName => $"{ProductType} {ProductName}";
public static Product CreateProduct(int id, string productName, int productCost, ProductType productType)
{ {
return new Product return new Product
{ {
Id = id, Id = id,
ProductName = productName,
ProductCost = productCost, ProductCost = productCost,
ProductType = productType ProductType = productType
}; };

View File

@ -6,6 +6,8 @@ public class ProductSelling
public int ProductID { get; private set; } public int ProductID { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public int Count { get; private set; } public int Count { get; private set; }
public static ProductSelling CreateSelling(int id, int productID, int count) public static ProductSelling CreateSelling(int id, int productID, int count)

View File

@ -1,4 +1,5 @@
using System.Collections; using System.Collections;
using System.ComponentModel;
namespace GasStation.Entities; namespace GasStation.Entities;
@ -6,10 +7,19 @@ public class Selling
{ {
public int Id { get; private set; } public int Id { get; private set; }
[Browsable(false)]
public int GasmanId { get; private set; } public int GasmanId { get; private set; }
[DisplayName("Имя заправщика")]
public string GasmanName { get; private set; } = string.Empty;
[DisplayName("Товары")]
public string Product => ProdutcSellings != null ? string.Join(", ", ProdutcSellings.Select(x => $"{x.ProductName} {x.Count}")) : string.Empty;
[Browsable(false)]
public IEnumerable<ProductSelling> ProdutcSellings { get; private set; } = []; public IEnumerable<ProductSelling> ProdutcSellings { get; private set; } = [];
[DisplayName("Дата продажи")]
public DateTime SellingDateTime { get; private set; } public DateTime SellingDateTime { get; private set; }
public static Selling CreateSelling(int id, int gasmanId, IEnumerable<ProductSelling> produtcSellings) public static Selling CreateSelling(int id, int gasmanId, IEnumerable<ProductSelling> produtcSellings)
@ -23,14 +33,11 @@ public class Selling
}; };
} }
public static Selling CreateSelling(TempProductSelling tempProductSelling, IEnumerable<ProductSelling> produtcSellings) public void SetProductSelling(IEnumerable<ProductSelling> produtcSellings)
{ {
return new Selling if (produtcSellings != null && produtcSellings.Any())
{ {
Id = tempProductSelling.Id, ProdutcSellings = produtcSellings;
GasmanId = tempProductSelling.GasmanId, }
SellingDateTime = tempProductSelling.SellingDateTime,
ProdutcSellings = produtcSellings
};
} }
} }

View File

@ -1,9 +1,12 @@
namespace GasStation.Entities; using System.ComponentModel;
namespace GasStation.Entities;
public class Supplier public class Supplier
{ {
public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Имя поставщика")]
public string SupplierName { get; private set; } = string.Empty; public string SupplierName { get; private set; } = string.Empty;
public static Supplier CreateSupplier(int id, string supplierName) public static Supplier CreateSupplier(int id, string supplierName)

View File

@ -1,15 +1,27 @@
namespace GasStation.Entities; using System.ComponentModel;
namespace GasStation.Entities;
public class Supply public class Supply
{ {
public int Id { get; private set; } public int Id { get; private set; }
[Browsable(false)]
public int SupplierID { get; private set; } public int SupplierID { get; private set; }
[Browsable(false)]
public int ProductID { get; private set; } public int ProductID { get; private set; }
[DisplayName("Имя поставщика")]
public string SupplierName { get; private set; } = string.Empty;
[DisplayName("Название товара")]
public string ProductName { get; private set; } = string.Empty;
[DisplayName("Количество товара")]
public int Count { get; private set; } public int Count { get; private set; }
[DisplayName("Дата поставки")]
public DateTime SupplyDate { get; private set; } public DateTime SupplyDate { get; private set; }
public static Supply CreateSupply(int id, int supplierID, int productID, int count) public static Supply CreateSupply(int id, int supplierID, int productID, int count)

View File

@ -1,14 +0,0 @@
namespace GasStation.Entities;
public class TempProductSelling
{
public int Id { get; private set; }
public int GasmanId { get; private set; }
public int Count { get; private set; }
public DateTime SellingDateTime { get; private set; }
public int ProductID { get; private set; }
}

View File

@ -86,7 +86,11 @@ namespace GasStation.Forms
} }
} }
private void LoadList() => dataGridViewData.DataSource = _gasmanRepository.ReadGasman(); private void LoadList()
{
dataGridViewData.DataSource = _gasmanRepository.ReadGasman();
dataGridViewData.Columns["ID"].Visible = false;
}
private bool TryGetIDFromSelectedRow(out int id) private bool TryGetIDFromSelectedRow(out int id)
{ {

View File

@ -34,6 +34,8 @@
comboBoxProduct = new ComboBox(); comboBoxProduct = new ComboBox();
buttonSave = new Button(); buttonSave = new Button();
buttonCancel = new Button(); buttonCancel = new Button();
label1 = new Label();
textBoxProduct = new TextBox();
((System.ComponentModel.ISupportInitialize)numericUpDownCost).BeginInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownCost).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -42,14 +44,14 @@
label2.AutoSize = true; label2.AutoSize = true;
label2.Location = new Point(33, 29); label2.Location = new Point(33, 29);
label2.Name = "label2"; label2.Name = "label2";
label2.Size = new Size(39, 15); label2.Size = new Size(67, 15);
label2.TabIndex = 1; label2.TabIndex = 1;
label2.Text = "Товар"; label2.Text = "Тип товара";
// //
// label3 // label3
// //
label3.AutoSize = true; label3.AutoSize = true;
label3.Location = new Point(33, 99); label3.Location = new Point(33, 140);
label3.Name = "label3"; label3.Name = "label3";
label3.Size = new Size(67, 15); label3.Size = new Size(67, 15);
label3.TabIndex = 2; label3.TabIndex = 2;
@ -57,7 +59,7 @@
// //
// numericUpDownCost // numericUpDownCost
// //
numericUpDownCost.Location = new Point(178, 99); numericUpDownCost.Location = new Point(178, 140);
numericUpDownCost.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); numericUpDownCost.Minimum = new decimal(new int[] { 1, 0, 0, 0 });
numericUpDownCost.Name = "numericUpDownCost"; numericUpDownCost.Name = "numericUpDownCost";
numericUpDownCost.Size = new Size(169, 23); numericUpDownCost.Size = new Size(169, 23);
@ -75,7 +77,7 @@
// //
// buttonSave // buttonSave
// //
buttonSave.Location = new Point(33, 166); buttonSave.Location = new Point(33, 207);
buttonSave.Name = "buttonSave"; buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(88, 25); buttonSave.Size = new Size(88, 25);
buttonSave.TabIndex = 6; buttonSave.TabIndex = 6;
@ -85,7 +87,7 @@
// //
// buttonCancel // buttonCancel
// //
buttonCancel.Location = new Point(254, 166); buttonCancel.Location = new Point(254, 207);
buttonCancel.Name = "buttonCancel"; buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(93, 25); buttonCancel.Size = new Size(93, 25);
buttonCancel.TabIndex = 7; buttonCancel.TabIndex = 7;
@ -93,11 +95,29 @@
buttonCancel.UseVisualStyleBackColor = true; buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click; buttonCancel.Click += ButtonCancel_Click;
// //
// label1
//
label1.AutoSize = true;
label1.Location = new Point(34, 85);
label1.Name = "label1";
label1.Size = new Size(99, 15);
label1.TabIndex = 8;
label1.Text = "Название товара";
//
// textBoxProduct
//
textBoxProduct.Location = new Point(178, 86);
textBoxProduct.Name = "textBoxProduct";
textBoxProduct.Size = new Size(169, 23);
textBoxProduct.TabIndex = 9;
//
// FormProduct // FormProduct
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(414, 246); ClientSize = new Size(414, 278);
Controls.Add(textBoxProduct);
Controls.Add(label1);
Controls.Add(buttonCancel); Controls.Add(buttonCancel);
Controls.Add(buttonSave); Controls.Add(buttonSave);
Controls.Add(comboBoxProduct); Controls.Add(comboBoxProduct);
@ -118,5 +138,7 @@
private ComboBox comboBoxProduct; private ComboBox comboBoxProduct;
private Button buttonSave; private Button buttonSave;
private Button buttonCancel; private Button buttonCancel;
private Label label1;
private TextBox textBoxProduct;
} }
} }

View File

@ -32,6 +32,7 @@ public partial class FormProduct : Form
throw new InvalidDataException(nameof(product)); throw new InvalidDataException(nameof(product));
} }
textBoxProduct.Text = product.ProductName;
comboBoxProduct.SelectedItem = product.ProductType; comboBoxProduct.SelectedItem = product.ProductType;
_productId = value; _productId = value;
} }
@ -71,7 +72,8 @@ public partial class FormProduct : Form
private void ButtonCancel_Click(object sender, EventArgs e) => Close(); private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Product CreateProduct(int id) => private Product CreateProduct(int id) =>
Product.CreateProduct(id, Convert.ToInt32(numericUpDownCost.Value), Product.CreateProduct(id, textBoxProduct.Text, Convert.ToInt32(numericUpDownCost.Value),
(ProductType)comboBoxProduct.SelectedItem!); (ProductType)comboBoxProduct.SelectedItem!);
} }

View File

@ -28,10 +28,8 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
dateTimePickerEnd = new DateTimePicker(); dateTimePicker = new DateTimePicker();
dateTimePickerBegin = new DateTimePicker();
label1 = new Label(); label1 = new Label();
label2 = new Label();
label3 = new Label(); label3 = new Label();
label4 = new Label(); label4 = new Label();
buttonMakeReport = new Button(); buttonMakeReport = new Button();
@ -40,37 +38,21 @@
textBoxFilePath = new TextBox(); textBoxFilePath = new TextBox();
SuspendLayout(); SuspendLayout();
// //
// dateTimePickerEnd // dateTimePicker
// //
dateTimePickerEnd.Location = new Point(176, 221); dateTimePicker.Location = new Point(176, 156);
dateTimePickerEnd.Name = "dateTimePickerEnd"; dateTimePicker.Name = "dateTimePicker";
dateTimePickerEnd.Size = new Size(200, 23); dateTimePicker.Size = new Size(200, 23);
dateTimePickerEnd.TabIndex = 0; dateTimePicker.TabIndex = 1;
//
// dateTimePickerBegin
//
dateTimePickerBegin.Location = new Point(176, 156);
dateTimePickerBegin.Name = "dateTimePickerBegin";
dateTimePickerBegin.Size = new Size(200, 23);
dateTimePickerBegin.TabIndex = 1;
// //
// label1 // label1
// //
label1.AutoSize = true; label1.AutoSize = true;
label1.Location = new Point(51, 156); label1.Location = new Point(51, 156);
label1.Name = "label1"; label1.Name = "label1";
label1.Size = new Size(74, 15); label1.Size = new Size(32, 15);
label1.TabIndex = 2; label1.TabIndex = 2;
label1.Text = "Дата начала"; label1.Text = "Дата";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(51, 221);
label2.Name = "label2";
label2.Size = new Size(68, 15);
label2.TabIndex = 3;
label2.Text = "Дата конца";
// //
// label3 // label3
// //
@ -92,7 +74,7 @@
// //
// buttonMakeReport // buttonMakeReport
// //
buttonMakeReport.Location = new Point(162, 290); buttonMakeReport.Location = new Point(152, 232);
buttonMakeReport.Name = "buttonMakeReport"; buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(114, 23); buttonMakeReport.Size = new Size(114, 23);
buttonMakeReport.TabIndex = 6; buttonMakeReport.TabIndex = 6;
@ -129,17 +111,15 @@
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(484, 370); ClientSize = new Size(484, 310);
Controls.Add(textBoxFilePath); Controls.Add(textBoxFilePath);
Controls.Add(buttonSelectFilePath); Controls.Add(buttonSelectFilePath);
Controls.Add(comboBoxProduct); Controls.Add(comboBoxProduct);
Controls.Add(buttonMakeReport); Controls.Add(buttonMakeReport);
Controls.Add(label4); Controls.Add(label4);
Controls.Add(label3); Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1); Controls.Add(label1);
Controls.Add(dateTimePickerBegin); Controls.Add(dateTimePicker);
Controls.Add(dateTimePickerEnd);
Name = "FormProductReport"; Name = "FormProductReport";
Text = "FormProductReport"; Text = "FormProductReport";
ResumeLayout(false); ResumeLayout(false);
@ -147,11 +127,8 @@
} }
#endregion #endregion
private DateTimePicker dateTimePicker;
private DateTimePicker dateTimePickerEnd;
private DateTimePicker dateTimePickerBegin;
private Label label1; private Label label1;
private Label label2;
private Label label3; private Label label3;
private Label label4; private Label label4;
private Button buttonMakeReport; private Button buttonMakeReport;

View File

@ -14,7 +14,7 @@ namespace GasStation.Forms
_container = container ?? _container = container ??
throw new ArgumentNullException(nameof(container)); throw new ArgumentNullException(nameof(container));
comboBoxProduct.DataSource = productRepository.ReadProduct(); comboBoxProduct.DataSource = productRepository.ReadProduct();
comboBoxProduct.DisplayMember = "ProductType"; comboBoxProduct.DisplayMember = "ProductName";
comboBoxProduct.ValueMember = "Id"; comboBoxProduct.ValueMember = "Id";
} }
@ -43,13 +43,9 @@ namespace GasStation.Forms
{ {
throw new Exception("Не выбран товар"); throw new Exception("Не выбран товар");
} }
if (dateTimePickerEnd.Value <= dateTimePickerBegin.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if if
(_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxProduct.SelectedValue!, (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxProduct.SelectedValue!,
dateTimePickerBegin.Value, dateTimePickerEnd.Value)) dateTimePicker.Value))
{ {
MessageBox.Show("Документ сформирован", MessageBox.Show("Документ сформирован",
"Формирование документа", "Формирование документа",

View File

@ -99,6 +99,11 @@ namespace GasStation.Forms
} }
} }
private void LoadList() => dataGridViewData.DataSource = _productRepository.ReadProduct(); private void LoadList()
{
dataGridViewData.DataSource = _productRepository.ReadProduct();
dataGridViewData.Columns["ID"].Visible = false;
dataGridViewData.Columns["FullName"].Visible = false;
}
} }
} }

View File

@ -19,7 +19,7 @@ namespace GasStation.Forms
comboBoxGasman.ValueMember = "ID"; comboBoxGasman.ValueMember = "ID";
ColumnProduct.DataSource = productRepository.ReadProduct(); ColumnProduct.DataSource = productRepository.ReadProduct();
ColumnProduct.DisplayMember = "ProductType"; ColumnProduct.DisplayMember = "ProductName";
ColumnProduct.ValueMember = "ID"; ColumnProduct.ValueMember = "ID";
} }
@ -60,7 +60,7 @@ namespace GasStation.Forms
Convert.ToInt32(row.Cells["ColumnCount"].Value))); Convert.ToInt32(row.Cells["ColumnCount"].Value)));
} }
return list.GroupBy(x => x.ProductID, x => x.Count, (id, counts) => ProductSelling.CreateSelling(0, id,counts.Sum())).ToList(); return list.GroupBy(x => x.ProductID, x => x.Count, (id, counts) => ProductSelling.CreateSelling(0, id, counts.Sum())).ToList();
; ;
} }

View File

@ -31,7 +31,12 @@ namespace GasStation.Forms
} }
} }
private void LoadList() => dataGridViewData.DataSource = _sellingRepository.ReadSelling(); private void LoadList()
{
dataGridViewData.DataSource = _sellingRepository.ReadSelling();
dataGridViewData.Columns["ID"].Visible = false;
dataGridViewData.Columns["SupplyDate"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm";
}
private void FormSellings_Load(object sender, EventArgs e) private void FormSellings_Load(object sender, EventArgs e)
{ {

View File

@ -86,7 +86,11 @@ namespace GasStation.Forms
} }
} }
private void LoadList() => dataGridViewData.DataSource = _supplierRepository.ReadSupplier(); private void LoadList()
{
dataGridViewData.DataSource = _supplierRepository.ReadSupplier();
dataGridViewData.Columns["ID"].Visible = false;
}
private bool TryGetIDFromSelectedRow(out int id) private bool TryGetIDFromSelectedRow(out int id)
{ {

View File

@ -54,7 +54,12 @@ namespace GasStation.Forms
} }
} }
private void LoadList() => dataGridViewData.DataSource = _supplyRepository.ReadSupply(); private void LoadList()
{
dataGridViewData.DataSource = _supplyRepository.ReadSupply();
dataGridViewData.Columns["ID"].Visible = false;
dataGridViewData.Columns["SupplyDate"].DefaultCellStyle.Format = "dd.MM.yyyy";
}
private void FormSupplies_Load(object sender, EventArgs e) private void FormSupplies_Load(object sender, EventArgs e)
{ {

View File

@ -18,7 +18,7 @@ namespace GasStation.Forms
comboBoxSupplier.ValueMember = "ID"; comboBoxSupplier.ValueMember = "ID";
comboBoxProduct.DataSource = productRepository.ReadProduct(); comboBoxProduct.DataSource = productRepository.ReadProduct();
comboBoxProduct.DisplayMember = "ProductType"; comboBoxProduct.DisplayMember = "FullName";
comboBoxProduct.ValueMember = "ID"; comboBoxProduct.ValueMember = "ID";
} }

View File

@ -21,7 +21,7 @@ internal class ChartReport
{ {
new PdfBuilder(filePath) new PdfBuilder(filePath)
.AddHeader("Поступление продукта") .AddHeader("Поступление продукта")
.AddPieChart("Поступивший товар", GetData(dateTime)) .AddPieChart("Поступивший товар {dateTime:dd MM yyyy}", GetData(dateTime))
.Build(); .Build();
return true; return true;
} }

View File

@ -79,10 +79,10 @@ internal class DocReport
private List<string[]> GetProducts() private List<string[]> GetProducts()
{ {
return [ return [
["Стоимость товара", "Тип товара"], ["Название товара", "Стоимость товара", "Тип товара"],
.. _productRepository .. _productRepository
.ReadProduct() .ReadProduct()
.Select(x => new string[] { x.ProductCost.ToString(), x.ProductType.ToString() }), .Select(x => new string[] { x.ProductName.ToString(), x.ProductCost.ToString(), x.ProductType.ToString() }),
]; ];
} }

View File

@ -17,14 +17,14 @@ internal class TableReport
_logger = logger ?? _logger = logger ??
throw new ArgumentNullException(nameof(logger)); throw new ArgumentNullException(nameof(logger));
} }
public bool CreateTable(string filePath, int productId, DateTime startDate, DateTime endDate) public bool CreateTable(string filePath, int productId, DateTime date)
{ {
try try
{ {
new ExcelBuilder(filePath) new ExcelBuilder(filePath)
.AddHeader("Сводка по движению товара", 0, 3) .AddHeader("Сводка по движению товара", 0, 3)
.AddParagraph("за период", 0) .AddParagraph("за период", 0)
.AddTable([10, 10, 15], GetData(productId, startDate, endDate)) .AddTable([10, 10, 15], GetData(productId, date))
.Build(); .Build();
return true; return true;
} }
@ -35,20 +35,19 @@ internal class TableReport
} }
} }
private List<string[]> GetData(int productId, DateTime startDate, DateTime endDate) private List<string[]> GetData(int productId, DateTime date)
{ {
var data = _sellingRepository var data = _sellingRepository
.ReadSelling() .ReadSelling(date, productId)
.Where(x => x.SellingDateTime >= startDate && x.SellingDateTime <= endDate && x.ProdutcSellings.Any(y => y.ProductID == productId))
.Select(x => new {x.GasmanId, Date = x.SellingDateTime, .Select(x => new {x.GasmanId, Date = x.SellingDateTime,
CountOut = x.ProdutcSellings.FirstOrDefault(y => y.ProductID == productId)?.Count }) CountOut = x.ProdutcSellings.FirstOrDefault(y => y.ProductID == productId)?.Count })
.OrderBy(x => x.Date); .OrderBy(x => x.Date);
return new List<string[]>() { item }.Union(data return new List<string[]>() { item }.Union(data
.Select(x => .Select(x =>
new string[] { x.GasmanId.ToString(), x.Date.ToString(), x.CountOut?.ToString() ?? string.Empty})) new string[] { x.GasmanId.ToString(), x.Date.ToString("dd.MM.yyyy"), x.CountOut?.ToString("N0") ?? string.Empty}))
.Union( .Union(
[["Всего", "", data.Sum(x => x.CountOut ?? 0).ToString()]] [["Всего", "", data.Sum(x => x.CountOut ?? 0).ToString("N0")]]
).ToList(); ).ToList();
} }
} }

View File

@ -28,8 +28,8 @@ public class ProductRepository : IProductRepository
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" var queryInsert = @"
INSERT INTO product (productCost, productType) INSERT INTO product (productName, productCost, productType)
VALUES (@ProductCost, @ProductType)"; VALUES (@ProductName, @ProductCost, @ProductType)";
connection.Execute(queryInsert, product); connection.Execute(queryInsert, product);
} }
catch (Exception ex) catch (Exception ex)
@ -112,6 +112,7 @@ WHERE id=@Id";
var queryUpdate = @" var queryUpdate = @"
UPDATE product UPDATE product
SET SET
productName=@ProductName,
productCost=@ProductCost, productCost=@ProductCost,
productType=@ProductType productType=@ProductType
WHERE id=@Id"; WHERE id=@Id";

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GasStation.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}";
}
}

View File

@ -3,6 +3,7 @@ using GasStation.Entities;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Npgsql; using Npgsql;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace GasStation.Repositories.Implementations; namespace GasStation.Repositories.Implementations;
@ -54,14 +55,55 @@ VALUES (@Id, @ProductID, @Count)";
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
var builder = new QueryBuilder();
if (dateTime.HasValue)
{
builder.AddCondition("s.SellingDateTime = @sellingDateTime");
}
if (count.HasValue)
{
builder.AddCondition("s.Count = @count");
}
if (gasmanID.HasValue)
{
builder.AddCondition("s.GasmanID = @gasmanID");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" var querySelect = @"
SELECT s.*, ps.ProductID, ps.Count FROM selling s SELECT
INNER JOIN Product_Selling ps ON ps.Id = s.Id"; fr.*,
var selling = connection.Query<TempProductSelling>(querySelect); CONCAT(p.ProductType, ' ', p.ProductName) as ProductName,
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(selling)); ps.ProdutId,
return selling.GroupBy(x => x.Id, y => y, (key, value) => ps.Count,
Selling.CreateSelling(value.First(), value.Select(z => ProductSelling.CreateSelling(0, z.ProductID, z.Count)))).ToList(); g.GasmanName as 'GasmanName'
FROM Selling s
LEFT JOIN Gasman g on g.Id = s.GasmanId
INNER JOIN Product_Selling ps ON ps.ProductId = s.Id
LEFT JOIN Product p on p.Id = s.ProductId
{builder.Build()}";
var sellingDict = new Dictionary<int, List<ProductSelling>>();
var selling = connection.Query<Selling, ProductSelling, Selling>(querySelect, (sell, sellings) =>
{
if (!sellingDict.TryGetValue(sell.Id, out var ps))
{
ps = [];
sellingDict.Add(sell.Id, ps);
}
ps.Add(sellings);
return sell;
}, splitOn: "ProdutcId", param: new
{dateTime, count, gasmanID});
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(selling));
return sellingDict.Select(x =>
{
var fr = selling.First(y => y.Id == x.Key);
fr.SetProductSelling(x.Value);
return fr;
}).ToArray();
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -3,6 +3,7 @@ using GasStation.Entities;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Npgsql; using Npgsql;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace GasStation.Repositories.Implementations; namespace GasStation.Repositories.Implementations;
@ -63,9 +64,34 @@ WHERE id=@Id";
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
var builder = new QueryBuilder();
if (supplyDate.HasValue)
{
builder.AddCondition("s.SupplyDate = @supplyDate");
}
if (supplierID.HasValue)
{
builder.AddCondition("s.SupplierID = @supplierID");
}
if (productID.HasValue)
{
builder.AddCondition("s.ProductID = @productID");
}
if (count.HasValue)
{
builder.AddCondition("s.Count = @count");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM supply"; var querySelect = @"SELECT
var supply = connection.Query<Supply>(querySelect); s.*,
CONCAT(p.ProductType, ' ', p.ProductName) as ProductName,
sup.SupplierName as SupplierName
FROM Supply s
LEFT JOIN Product p on p.Id = s.ProductId
LEFT JOIN Supplier sup on sup.Id = s.SupplierId
{builder.Build()}";
var supply = connection.Query<Supply>(querySelect, new { supplyDate, supplierID, productID, count });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supply)); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supply));
return supply; return supply;
} }