лабораторная 2
This commit is contained in:
parent
d1c9cd4ecc
commit
273c081f0e
@ -11,7 +11,7 @@ public class Client
|
||||
public int Id { get; set; }
|
||||
public string Name { get; private set; } = string.Empty;
|
||||
public string Phone { get; private set; } = string.Empty;
|
||||
public Gender Gender { get; private set; } = Gender.None; // Используем flag Gender
|
||||
public Gender Gender { get; private set; } // Используем flag Gender
|
||||
|
||||
public static Client CreateEntity(int id, string name, string phone, Gender gender)
|
||||
{
|
||||
|
@ -8,12 +8,12 @@ namespace ProjectAtelier.Entities;
|
||||
|
||||
public class Product
|
||||
{
|
||||
public int Id { get; private set; }
|
||||
public string Name { get; private set; } = string.Empty;
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public ProductView View{ get; private set; }
|
||||
public int CountMaterial { get; private set; }
|
||||
public IEnumerable<ProductMaterial> ProductMaterial { get; private set; } = [];
|
||||
public ProductView View{ get; set; }
|
||||
public int CountMaterial { get; set; }
|
||||
public IEnumerable<ProductMaterial> ProductMaterial { get; set; } = [];
|
||||
public static Product CreateEntity(int id, string name, ProductView view, int countmaterial, IEnumerable<ProductMaterial> productMaterial)
|
||||
{
|
||||
return new Product
|
||||
|
@ -10,8 +10,8 @@ namespace ProjectAtelier.Entities;
|
||||
{
|
||||
public int Id { get; private set; }
|
||||
public int ProductId { get; private set; }
|
||||
public int MaterialId { get; private set; }
|
||||
public int Count { get; private set; }
|
||||
public int MaterialId { get; set; }
|
||||
public int Count { get; set; }
|
||||
|
||||
public static ProductMaterial CreateOperation(int id, int productId, int materialid, int count)
|
||||
{
|
||||
|
@ -5,13 +5,13 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAtelier.Entities;
|
||||
[Flags]
|
||||
[Flags]
|
||||
public enum Gender
|
||||
|
||||
{
|
||||
None = 0,
|
||||
Male = 1,
|
||||
Female = 2,
|
||||
M = 1,
|
||||
F = 2,
|
||||
Other = 4
|
||||
}
|
||||
|
||||
|
@ -8,8 +8,8 @@ namespace ProjectAtelier.Entities;
|
||||
public enum OrderStatus
|
||||
{
|
||||
None = 0,
|
||||
NotCompleted = 1,
|
||||
Reserv = 2,
|
||||
Completed = 3
|
||||
Обработка = 1,
|
||||
Пошив = 2,
|
||||
Готово = 3
|
||||
}
|
||||
|
||||
|
@ -9,8 +9,11 @@ namespace ProjectAtelier.Entities;
|
||||
public enum ProductView
|
||||
{
|
||||
None = 0,
|
||||
Shirt = 1,
|
||||
Trousers = 2,
|
||||
Jacket = 3
|
||||
Рубашка = 1,
|
||||
Брюки = 2,
|
||||
Пиджак = 3,
|
||||
Халат= 4,
|
||||
Футболка= 5
|
||||
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Microsoft.VisualBasic.FileIO;
|
||||
using ProjectAtelier.Entities;
|
||||
using ProjectAtelier.Repositories;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -28,10 +29,23 @@ namespace ProjectAtelier.Forms
|
||||
{
|
||||
throw new InvalidDataException(nameof(client));
|
||||
}
|
||||
//textBoxName.Text = client.Name;
|
||||
//textBoxPhone.Text = client.Phone;
|
||||
//SetCheckedListBoxGender(client.Gender); // Устанавливаем выбранные элементы
|
||||
//_clientId = value;///////////////////////////////
|
||||
foreach (Gender elem in Enum.GetValues(typeof(Gender)))
|
||||
{
|
||||
if ((elem & client.Gender) != 0)
|
||||
{
|
||||
checkedListBoxGender.SetItemChecked(checkedListBoxGender.Items.IndexOf(
|
||||
elem), true);
|
||||
}
|
||||
}
|
||||
textBoxName.Text = client.Name;
|
||||
textBoxPhone.Text = client.Phone;
|
||||
SetCheckedListBoxGender(client.Gender); // Устанавливаем выбранные элементы
|
||||
_clientId = value;
|
||||
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -44,21 +58,25 @@ namespace ProjectAtelier.Forms
|
||||
public FormClient(IClientRepository clientRepository)
|
||||
{
|
||||
InitializeComponent();
|
||||
_clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository));
|
||||
_clientRepository = clientRepository ??
|
||||
throw new ArgumentNullException(nameof(clientRepository));
|
||||
foreach (var elem in Enum.GetValues(typeof(Gender)))
|
||||
{
|
||||
checkedListBoxGender.Items.Add(elem);
|
||||
}
|
||||
|
||||
// Инициализация CheckedListBox с элементами перечисления Gender
|
||||
checkedListBoxGender.Items.AddRange(Enum.GetValues(typeof(Gender)).Cast<object>().ToArray());
|
||||
}
|
||||
|
||||
private void ButtonAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(textBoxName.Text) || string.IsNullOrWhiteSpace(textBoxPhone.Text))
|
||||
if (string.IsNullOrWhiteSpace(textBoxName.Text) ||
|
||||
string.IsNullOrWhiteSpace(textBoxPhone.Text) ||
|
||||
checkedListBoxGender.CheckedItems.Count == 0)
|
||||
{
|
||||
throw new Exception("Имеются незаполненные поля");
|
||||
}
|
||||
|
||||
if (_clientId.HasValue)
|
||||
{
|
||||
_clientRepository.UpdateClient(CreateClient(_clientId.Value));
|
||||
@ -71,34 +89,22 @@ namespace ProjectAtelier.Forms
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Ошибка при сохранении",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
|
||||
|
||||
private void ButtonCancel_Click(object sender, EventArgs e) =>Close();
|
||||
private Client CreateClient(int id)
|
||||
{
|
||||
// Получаем выбранные значения из CheckedListBox
|
||||
Gender gender = Gender.None;
|
||||
foreach (var item in checkedListBoxGender.CheckedItems)
|
||||
foreach (var elem in checkedListBoxGender.CheckedItems)
|
||||
{
|
||||
gender |= (Gender)item;
|
||||
gender |= (Gender)elem;
|
||||
}
|
||||
|
||||
return Client.CreateEntity(id, textBoxName.Text, textBoxPhone.Text, gender);
|
||||
}
|
||||
|
||||
private void SetCheckedListBoxGender(Gender gender)
|
||||
{
|
||||
checkedListBoxGender.ClearSelected();
|
||||
foreach (var item in checkedListBoxGender.Items)
|
||||
{
|
||||
if (gender.HasFlag((Gender)item))
|
||||
{
|
||||
checkedListBoxGender.SetItemChecked(checkedListBoxGender.Items.IndexOf(item), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -66,7 +66,7 @@ namespace ProjectAtelier.Forms
|
||||
}
|
||||
try
|
||||
{
|
||||
var form = _container.Resolve<FormMaterial>();
|
||||
var form = _container.Resolve<FormClient>();
|
||||
form.Id = findId;
|
||||
form.ShowDialog();
|
||||
LoadList();
|
||||
@ -76,7 +76,7 @@ namespace ProjectAtelier.Forms
|
||||
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
private void LoadList() => dataGridView.DataSource = _clientRepository.ReadClient();
|
||||
private void LoadList() => dataGridView.DataSource = _clientRepository.ReadClients();
|
||||
private bool TryGetIdentifierFromSelectedRow(out int id)
|
||||
{
|
||||
id = 0;
|
||||
|
32
ProjectAtelier/Forms/FormProductMaterial.Designer.cs
generated
32
ProjectAtelier/Forms/FormProductMaterial.Designer.cs
generated
@ -30,8 +30,9 @@
|
||||
{
|
||||
groupBox = new GroupBox();
|
||||
dataGridView = new DataGridView();
|
||||
ColumnMaterials = new DataGridViewComboBoxColumn();
|
||||
ColumnMaterial = new DataGridViewComboBoxColumn();
|
||||
ColumnCount = new DataGridViewTextBoxColumn();
|
||||
ColumProduct = new DataGridViewTextBoxColumn();
|
||||
buttonAdd = new Button();
|
||||
buttonCancel = new Button();
|
||||
labelName = new Label();
|
||||
@ -60,7 +61,7 @@
|
||||
//
|
||||
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
|
||||
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
|
||||
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterials, ColumnCount });
|
||||
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterial, ColumnCount, ColumProduct });
|
||||
dataGridView.Dock = DockStyle.Fill;
|
||||
dataGridView.Location = new Point(3, 24);
|
||||
dataGridView.Margin = new Padding(3, 4, 3, 4);
|
||||
@ -71,13 +72,13 @@
|
||||
dataGridView.Size = new Size(642, 328);
|
||||
dataGridView.TabIndex = 0;
|
||||
//
|
||||
// ColumnMaterials
|
||||
// ColumnMaterial
|
||||
//
|
||||
ColumnMaterials.HeaderText = "Materials";
|
||||
ColumnMaterials.MinimumWidth = 6;
|
||||
ColumnMaterials.Name = "ColumnMaterials";
|
||||
ColumnMaterials.Resizable = DataGridViewTriState.True;
|
||||
ColumnMaterials.SortMode = DataGridViewColumnSortMode.Automatic;
|
||||
ColumnMaterial.HeaderText = "Materials";
|
||||
ColumnMaterial.MinimumWidth = 6;
|
||||
ColumnMaterial.Name = "ColumnMaterial";
|
||||
ColumnMaterial.Resizable = DataGridViewTriState.True;
|
||||
ColumnMaterial.SortMode = DataGridViewColumnSortMode.Automatic;
|
||||
//
|
||||
// ColumnCount
|
||||
//
|
||||
@ -85,6 +86,12 @@
|
||||
ColumnCount.MinimumWidth = 6;
|
||||
ColumnCount.Name = "ColumnCount";
|
||||
//
|
||||
// ColumProduct
|
||||
//
|
||||
ColumProduct.HeaderText = "ColumnName";
|
||||
ColumProduct.MinimumWidth = 6;
|
||||
ColumProduct.Name = "ColumProduct";
|
||||
//
|
||||
// buttonAdd
|
||||
//
|
||||
buttonAdd.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
|
||||
@ -121,7 +128,7 @@
|
||||
// labelType
|
||||
//
|
||||
labelType.AutoSize = true;
|
||||
labelType.Location = new Point(35, 104);
|
||||
labelType.Location = new Point(35, 109);
|
||||
labelType.Name = "labelType";
|
||||
labelType.Size = new Size(96, 20);
|
||||
labelType.TabIndex = 4;
|
||||
@ -148,7 +155,7 @@
|
||||
//
|
||||
comboBoxProduct.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
comboBoxProduct.FormattingEnabled = true;
|
||||
comboBoxProduct.Location = new Point(215, 104);
|
||||
comboBoxProduct.Location = new Point(215, 101);
|
||||
comboBoxProduct.Margin = new Padding(3, 4, 3, 4);
|
||||
comboBoxProduct.Name = "comboBoxProduct";
|
||||
comboBoxProduct.Size = new Size(161, 28);
|
||||
@ -192,13 +199,14 @@
|
||||
private DataGridView dataGridView;
|
||||
private Button buttonAdd;
|
||||
private Button buttonCancel;
|
||||
private DataGridViewComboBoxColumn ColumnMaterials;
|
||||
private DataGridViewTextBoxColumn ColumnCount;
|
||||
private Label labelName;
|
||||
private Label labelType;
|
||||
private Label labelCountInWarehouse;
|
||||
private TextBox textBoxName;
|
||||
private ComboBox comboBoxProduct;
|
||||
private NumericUpDown numericUpDownCount;
|
||||
private DataGridViewComboBoxColumn ColumnMaterial;
|
||||
private DataGridViewTextBoxColumn ColumnCount;
|
||||
private DataGridViewTextBoxColumn ColumProduct;
|
||||
}
|
||||
}
|
@ -1,5 +1,15 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using ProjectAtelier.Repositories;
|
||||
using ProjectAtelier.Repositories.Implementations;
|
||||
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 ProjectAtelier.Forms
|
||||
{
|
||||
@ -23,10 +33,17 @@ namespace ProjectAtelier.Forms
|
||||
comboBoxProduct.SelectedItem = product.View;
|
||||
numericUpDownCount.Value = product.CountMaterial;
|
||||
_productId = value;
|
||||
|
||||
// Заполняем DataGridView данными из product.ProductMaterial
|
||||
dataGridView.Rows.Clear();
|
||||
foreach (var material in product.ProductMaterial)
|
||||
{
|
||||
dataGridView.Rows.Add(material.MaterialId, material.Count);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка при полученииданных", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -39,19 +56,17 @@ namespace ProjectAtelier.Forms
|
||||
|
||||
comboBoxProduct.DataSource = Enum.GetValues(typeof(ProductView));
|
||||
|
||||
ColumnMaterials.DataSource = materialRepository.ReadMaterials();
|
||||
ColumnMaterials.DisplayMember = "Name";
|
||||
ColumnMaterials.ValueMember = "Id";
|
||||
}
|
||||
private void buttonAdd_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (dataGridView.RowCount < 1)
|
||||
{
|
||||
throw new Exception("Имеются незаполненны поля");
|
||||
MessageBox.Show("Имеются незаполненные поля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 1)
|
||||
if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 0)
|
||||
{
|
||||
throw new Exception("Имеются незаполненные поля");
|
||||
}
|
||||
@ -76,17 +91,25 @@ namespace ProjectAtelier.Forms
|
||||
var list = new List<ProductMaterial>();
|
||||
foreach (DataGridViewRow row in dataGridView.Rows)
|
||||
{
|
||||
if (row.Cells["ColumProduct"].Value == null || row.Cells["ColumMaterials"].Value == null || row.Cells["ColumnCount"].Value == null)
|
||||
if (row.Cells["ColumnMaterial"].Value == null || row.Cells["ColumnCount"].Value == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
list.Add(ProductMaterial.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnMaterial"].Value),
|
||||
Convert.ToInt32(row.Cells["ColumnProduct"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value)));
|
||||
list.Add(new ProductMaterial
|
||||
{
|
||||
MaterialId = Convert.ToInt32(row.Cells["ColumnMaterial"].Value),
|
||||
Count = Convert.ToInt32(row.Cells["ColumnCount"].Value)
|
||||
});
|
||||
}
|
||||
return list;
|
||||
}
|
||||
private Product CreateProduct(int id) => Product.CreateEntity(id, textBoxName.Text, (ProductView)comboBoxProduct.SelectedItem!, Convert.ToInt32(numericUpDownCount.Value), CreateListMaterialFromDataGrid());
|
||||
|
||||
|
||||
private Product CreateProduct(int id) => new Product
|
||||
{
|
||||
Id = id,
|
||||
Name = textBoxName.Text,
|
||||
View = (ProductView)comboBoxProduct.SelectedItem,
|
||||
CountMaterial = Convert.ToInt32(numericUpDownCount.Value),
|
||||
ProductMaterial = CreateListMaterialFromDataGrid()
|
||||
};
|
||||
}
|
||||
}
|
@ -117,4 +117,7 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="ColumProduct.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<value>True</value>
|
||||
</metadata>
|
||||
</root>
|
36
ProjectAtelier/Forms/FormProductOrder.Designer.cs
generated
36
ProjectAtelier/Forms/FormProductOrder.Designer.cs
generated
@ -36,12 +36,12 @@
|
||||
comboBoxStatus = new ComboBox();
|
||||
groupBox = new GroupBox();
|
||||
dataGridView = new DataGridView();
|
||||
ColumnProducts = new DataGridViewComboBoxColumn();
|
||||
ColumnCount = new DataGridViewTextBoxColumn();
|
||||
comboBoxClient = new ComboBox();
|
||||
labelClient = new Label();
|
||||
dateTimePicker = new DateTimePicker();
|
||||
label1 = new Label();
|
||||
ColumProduct = new DataGridViewComboBoxColumn();
|
||||
ColumnCount = new DataGridViewTextBoxColumn();
|
||||
groupBox.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
|
||||
SuspendLayout();
|
||||
@ -120,7 +120,7 @@
|
||||
//
|
||||
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
|
||||
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
|
||||
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnProducts, ColumnCount });
|
||||
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumProduct, ColumnCount });
|
||||
dataGridView.Dock = DockStyle.Fill;
|
||||
dataGridView.Location = new Point(3, 24);
|
||||
dataGridView.Margin = new Padding(3, 4, 3, 4);
|
||||
@ -131,19 +131,6 @@
|
||||
dataGridView.Size = new Size(499, 408);
|
||||
dataGridView.TabIndex = 0;
|
||||
//
|
||||
// ColumnProducts
|
||||
//
|
||||
ColumnProducts.HeaderText = "Изделие";
|
||||
ColumnProducts.MinimumWidth = 6;
|
||||
ColumnProducts.Name = "ColumnProducts";
|
||||
ColumnProducts.ReadOnly = true;
|
||||
//
|
||||
// ColumnCount
|
||||
//
|
||||
ColumnCount.HeaderText = "Количество";
|
||||
ColumnCount.MinimumWidth = 6;
|
||||
ColumnCount.Name = "ColumnCount";
|
||||
//
|
||||
// comboBoxClient
|
||||
//
|
||||
comboBoxClient.DropDownStyle = ComboBoxStyle.DropDownList;
|
||||
@ -179,6 +166,19 @@
|
||||
label1.TabIndex = 11;
|
||||
label1.Text = "Дата";
|
||||
//
|
||||
// ColumProduct
|
||||
//
|
||||
ColumProduct.HeaderText = "Изделие";
|
||||
ColumProduct.MinimumWidth = 6;
|
||||
ColumProduct.Name = "ColumProduct";
|
||||
ColumProduct.ReadOnly = true;
|
||||
//
|
||||
// ColumnCount
|
||||
//
|
||||
ColumnCount.HeaderText = "Количество";
|
||||
ColumnCount.MinimumWidth = 6;
|
||||
ColumnCount.Name = "ColumnCount";
|
||||
//
|
||||
// FormProductOrder
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
@ -216,9 +216,9 @@
|
||||
private DataGridView dataGridView;
|
||||
private ComboBox comboBoxClient;
|
||||
private Label labelClient;
|
||||
private DataGridViewComboBoxColumn ColumnProducts;
|
||||
private DataGridViewTextBoxColumn ColumnCount;
|
||||
private DateTimePicker dateTimePicker;
|
||||
private Label label1;
|
||||
private DataGridViewComboBoxColumn ColumProduct;
|
||||
private DataGridViewTextBoxColumn ColumnCount;
|
||||
}
|
||||
}
|
@ -21,12 +21,12 @@ namespace ProjectAtelier.Forms
|
||||
|
||||
comboBoxStatus.DataSource = Enum.GetValues(typeof(OrderStatus));
|
||||
|
||||
ColumnProducts.DataSource = productRepository.ReadProducts();
|
||||
ColumnProducts.DisplayMember = "Name";
|
||||
ColumnProducts.ValueMember = "Id";
|
||||
ColumProduct.DataSource = productRepository.ReadProducts();
|
||||
ColumProduct.DisplayMember = "Name";
|
||||
ColumProduct.ValueMember = "Id";
|
||||
|
||||
// Заполняем ComboBox для выбора клиента
|
||||
comboBoxClient.DataSource = clientRepository.ReadClient();
|
||||
comboBoxClient.DataSource = clientRepository.ReadClients();
|
||||
comboBoxClient.DisplayMember = "Name";
|
||||
comboBoxClient.ValueMember = "Id";
|
||||
|
||||
|
1
ProjectAtelier/Forms/FormProducts.Designer.cs
generated
1
ProjectAtelier/Forms/FormProducts.Designer.cs
generated
@ -88,6 +88,7 @@
|
||||
buttonRemove.Size = new Size(94, 92);
|
||||
buttonRemove.TabIndex = 1;
|
||||
buttonRemove.UseVisualStyleBackColor = true;
|
||||
buttonRemove.Click += buttonRemove_Click;
|
||||
//
|
||||
// buttonAdd
|
||||
//
|
||||
|
@ -3,6 +3,10 @@ using ProjectAtelier.Repositories;
|
||||
using ProjectAtelier.REPOSITORY.Implementations;
|
||||
using ProjectAtelier.REPOSITORY;
|
||||
using Unity;
|
||||
using Unity.Microsoft.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAtelier
|
||||
{
|
||||
@ -22,6 +26,8 @@ namespace ProjectAtelier
|
||||
private static IUnityContainer CreateContainer()
|
||||
{
|
||||
var container = new UnityContainer();
|
||||
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
|
||||
|
||||
container.RegisterType<IOrderRepository, OrderRepository>();
|
||||
container.RegisterType<IMaterialRepository, MaterialRepository>();
|
||||
container.RegisterType<IProductRepository, ProductRepository>();
|
||||
@ -29,7 +35,19 @@ namespace ProjectAtelier
|
||||
container.RegisterType<IProductMaterialRepository, ProductMaterialRepository>();
|
||||
container.RegisterType<IMaterialReplenishmentRepository, MaterialReplenishmentRepository>();
|
||||
|
||||
container.RegisterType<IConnectionString, ConnectionString>();
|
||||
return container;
|
||||
}
|
||||
private static LoggerFactory CreateLoggerFactory()
|
||||
{
|
||||
var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
return loggerFactory;
|
||||
}
|
||||
}
|
||||
}
|
@ -9,7 +9,18 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.1.35" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Npgsql" Version="8.0.5" />
|
||||
<PackageReference Include="Serilog" Version="4.0.2" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="Unity" Version="5.11.10" />
|
||||
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@ -27,4 +38,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -1,4 +1,9 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
using ProjectAtelier.Repositories;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -9,21 +14,93 @@ namespace ProjectAtelier.REPOSITORY.Implementations;
|
||||
|
||||
public class MaterialReplenishmentRepository : IMaterialReplenishmentRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
private readonly ILogger<Material> _logger;
|
||||
public MaterialReplenishmentRepository(IConnectionString connectionString, ILogger<Material> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
public void CreateMaterialSpent(MaterialReplenishment material)
|
||||
{
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryInsert = @"
|
||||
INSERT INTO MaterialReplenishment (Count, DataTime, IDMaterial)
|
||||
VALUES (@Count, @DataTime, @IDMaterial)";
|
||||
connection.Execute(queryInsert, material);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public MaterialReplenishment ReadMaterialSpentById(int id)
|
||||
{
|
||||
return MaterialReplenishment.CreateOperation(0, 0, DateTime.Now, 0);
|
||||
_logger.LogInformation("Получение объекта по идентификатору");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT * FROM MaterialReplenishment
|
||||
WHERE Id=@id";
|
||||
var material = connection.QueryFirst<MaterialReplenishment>(querySelect, new
|
||||
{
|
||||
id
|
||||
});
|
||||
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(material));
|
||||
return material;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при поиске объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<MaterialReplenishment> ReadMaterialsSpent()
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = "SELECT * FROM MaterialReplenishment";
|
||||
var materials = connection.Query<MaterialReplenishment>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials));
|
||||
return materials;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateMaterialSpent(MaterialReplenishment material)
|
||||
{
|
||||
_logger.LogInformation("Редактирование объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryUpdate = @"
|
||||
UPDATE MaterialReplenishment
|
||||
SET
|
||||
Count=@Count,
|
||||
DataTime=@DataTime,
|
||||
IDMaterial=@IDMaterial
|
||||
WHERE Id=@Id";
|
||||
connection.Execute(queryUpdate, material);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при редактировании объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
@ -9,7 +9,7 @@ namespace ProjectAtelier.Repositories;
|
||||
|
||||
public interface IClientRepository
|
||||
{
|
||||
IEnumerable<Client> ReadClient();
|
||||
IEnumerable<Client> ReadClients();
|
||||
Client ReadClientById(int id);
|
||||
void CreateClient(Client client);
|
||||
void UpdateClient(Client client);
|
||||
|
5
ProjectAtelier/Repositories/IConnectionString.cs
Normal file
5
ProjectAtelier/Repositories/IConnectionString.cs
Normal file
@ -0,0 +1,5 @@
|
||||
namespace ProjectAtelier.Repositories;
|
||||
public interface IConnectionString
|
||||
{
|
||||
public string ConnectionString { get; }
|
||||
}
|
@ -10,7 +10,6 @@ namespace ProjectAtelier.Repositories;
|
||||
public interface IOrderRepository
|
||||
{
|
||||
IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderStatus = null, int? orderId = null);
|
||||
Order ReadOrderById(int orderId);
|
||||
void CreateOrder(Order order);
|
||||
void DeleteOrder(int id);
|
||||
}
|
||||
|
@ -1,33 +1,126 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
|
||||
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
public class ClientRepository : IClientRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
private readonly ILogger<Client> _logger;
|
||||
public ClientRepository(IConnectionString connectionString, ILogger<Client> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public void CreateClient(Client client)
|
||||
{
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}",
|
||||
JsonConvert.SerializeObject(client));
|
||||
try
|
||||
{
|
||||
using var connection = new
|
||||
NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryInsert = @"
|
||||
INSERT INTO Clients (Name, Phone, Gender)
|
||||
VALUES (@Name, @Phone, @Gender)";
|
||||
connection.Execute(queryInsert, client);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteClient(int id)
|
||||
{
|
||||
}
|
||||
|
||||
public IEnumerable<Client> ReadClient()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public Client ReadClientById(int id)
|
||||
{
|
||||
return Client.CreateEntity(id, string.Empty, string.Empty, Gender.None);
|
||||
}
|
||||
|
||||
public void UpdateClient(Client client)
|
||||
{
|
||||
_logger.LogInformation("Редактирование объекта");
|
||||
_logger.LogDebug("Объект: {json}",
|
||||
JsonConvert.SerializeObject(client));
|
||||
try
|
||||
{
|
||||
using var connection = new
|
||||
NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryUpdate = @"
|
||||
UPDATE Clients
|
||||
SET
|
||||
Name=@Name,
|
||||
Phone=@Phone,
|
||||
Gender=@Gender
|
||||
WHERE Id=@Id";
|
||||
connection.Execute(queryUpdate, client);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при редактировании объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void DeleteClient(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new
|
||||
NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Clients
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public Client ReadClientById(int id)
|
||||
{
|
||||
_logger.LogInformation("Получение объекта по идентификатору");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT * FROM Clients
|
||||
WHERE Id=@id";
|
||||
var client = connection.QueryFirst<Client>(querySelect, new
|
||||
{
|
||||
id
|
||||
});
|
||||
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client));
|
||||
return client;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при поиске объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<Client> ReadClients()
|
||||
{
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new
|
||||
NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = "SELECT * FROM Clients";
|
||||
var Client = connection.Query<Client>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}",
|
||||
JsonConvert.SerializeObject(Client));
|
||||
return Client;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
public class ConnectionString : IConnectionString
|
||||
{
|
||||
string IConnectionString.ConnectionString => "Server=localhost; Port=5432;Database=atelier;User Id=postgres; Password=postgres";
|
||||
}
|
@ -1,4 +1,8 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -9,25 +13,113 @@ namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
public class MaterialRepository : IMaterialRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
private readonly ILogger<Material> _logger;
|
||||
public MaterialRepository(IConnectionString connectionString, ILogger<Material> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public void CreateMaterial(Material material)
|
||||
{
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryInsert = @"
|
||||
INSERT INTO Materials (Name, UseCount, CountInWareHouse)
|
||||
VALUES (@Name, @UseCount, @CountInWareHouse)";
|
||||
connection.Execute(queryInsert, material);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void UpdateMaterial(Material material)
|
||||
{
|
||||
_logger.LogInformation("Редактирование объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryUpdate = @"
|
||||
UPDATE Materials
|
||||
SET
|
||||
Name=@Name,
|
||||
UseCount=@UseCount,
|
||||
CountInWareHouse=@CountInWareHouse
|
||||
WHERE Id=@Id";
|
||||
connection.Execute(queryUpdate, material);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при редактировании объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteMaterial(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Materials
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<Material> ReadMaterials()
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = "SELECT * FROM Materials";
|
||||
var materials = connection.Query<Material>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials));
|
||||
return materials;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public Material ReadMaterialById(int id)
|
||||
{
|
||||
return Material.CreateEntity(id, string.Empty, 0, 0);
|
||||
}
|
||||
|
||||
public void UpdateMaterial(Material material)
|
||||
{
|
||||
_logger.LogInformation("Получение объекта по идентификатору");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT * FROM Materials
|
||||
WHERE Id=@id";
|
||||
var material = connection.QueryFirst<Material>(querySelect, new
|
||||
{
|
||||
id
|
||||
});
|
||||
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(material));
|
||||
return material;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при поиске объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,8 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -9,20 +13,82 @@ namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
public class OrderRepository : IOrderRepository
|
||||
{
|
||||
public void CreateOrder(Order feedReplenishment)
|
||||
private readonly IConnectionString _connectionString;
|
||||
private readonly ILogger<ProductRepository> _logger;
|
||||
public OrderRepository(IConnectionString connectionString, ILogger<ProductRepository> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
public void CreateOrder(Order order)
|
||||
{
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var queryInsert = @"
|
||||
INSERT INTO Orders (DataTime, Status, Characteristic, IdClient)
|
||||
VALUES (@DataTime, @Status, @Characteristic, @IdClient);
|
||||
SELECT MAX(Id) FROM Orders";
|
||||
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
|
||||
var querySubInsert = @"
|
||||
INSERT INTO Orders_Products (OrderId, ProductId, Count)
|
||||
VALUES (@OrderId, @ProductId, @Count)";
|
||||
foreach (var elem in order.OrderProduct)
|
||||
{
|
||||
connection.Execute(querySubInsert, new
|
||||
{
|
||||
orderId,
|
||||
elem.ProductId,
|
||||
elem.Count
|
||||
}, transaction);
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteOrder(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Orders
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderStatus = null, int? orderId = null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
public Order ReadOrderById(int id)
|
||||
{
|
||||
return Order.CreateOperation(id, 0, string.Empty, [], 0, DateTime.Now);
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"SELECT * FROM Orders";
|
||||
var order = connection.Query<Order>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(order));
|
||||
return order;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,8 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -9,25 +13,157 @@ namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
public class ProductRepository : IProductRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
private readonly ILogger<ProductRepository> _logger;
|
||||
public ProductRepository(IConnectionString connectionString, ILogger<ProductRepository> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
public void CreateProduct(Product product)
|
||||
{
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var queryInsert = @"
|
||||
INSERT INTO Products (Name, View, CountMaterial)
|
||||
VALUES (@Name, @View, @CountMaterial);
|
||||
SELECT MAX(Id) FROM Products";
|
||||
var productId = connection.QueryFirst<int>(queryInsert, product, transaction);
|
||||
var querySubInsert = @"
|
||||
INSERT INTO Product_Materials (ProductId, MaterialId, Count)
|
||||
VALUES (@ProductId, @MaterialId, @Count)";
|
||||
foreach (var elem in product.ProductMaterial)
|
||||
{
|
||||
connection.Execute(querySubInsert, new
|
||||
{
|
||||
productId,
|
||||
elem.MaterialId,
|
||||
elem.Count
|
||||
}, transaction);
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteProduct(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Products
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<Product> ReadProducts()
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"SELECT * FROM Products";
|
||||
var product = connection.Query<Product>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(product));
|
||||
return product;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public Product ReadProductById(int id)
|
||||
{
|
||||
return Product.CreateEntity(id, string.Empty, 0, 0, []);
|
||||
_logger.LogInformation("Получение объекта по ID: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT * FROM Products WHERE Id = @Id;
|
||||
SELECT m.*, pm.Count FROM Materials m
|
||||
JOIN Product_Materials pm ON m.Id = pm.MaterialId
|
||||
WHERE pm.ProductId = @Id";
|
||||
using var multi = connection.QueryMultiple(querySelect, new { Id = id });
|
||||
var product = multi.Read<Product>().FirstOrDefault();
|
||||
if (product != null)
|
||||
{
|
||||
var materials = multi.Read<Material>().ToList();
|
||||
product.ProductMaterial = materials.Select(m => new ProductMaterial
|
||||
{
|
||||
MaterialId = m.Id,
|
||||
Count = m.UseCount // Исправлено здесь
|
||||
}).ToList();
|
||||
}
|
||||
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product));
|
||||
return product;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объекта по ID: {id}", id);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateProduct(Product product)
|
||||
{
|
||||
_logger.LogInformation("Редактирование объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
|
||||
var queryUpdate = @"
|
||||
UPDATE Products
|
||||
SET Name = @Name, View = @View, CountMaterial = @CountMaterial
|
||||
WHERE Id = @Id";
|
||||
connection.Execute(queryUpdate, product, transaction);
|
||||
|
||||
var queryDelete = @"
|
||||
DELETE FROM Product_Materials
|
||||
WHERE ProductId = @ProductId";
|
||||
connection.Execute(queryDelete, new { ProductId = product.Id }, transaction);
|
||||
|
||||
var querySubInsert = @"
|
||||
INSERT INTO Product_Materials (ProductId, MaterialId, Count)
|
||||
VALUES (@ProductId, @MaterialId, @Count)";
|
||||
foreach (var elem in product.ProductMaterial)
|
||||
{
|
||||
connection.Execute(querySubInsert, new
|
||||
{
|
||||
ProductId = product.Id,
|
||||
elem.MaterialId,
|
||||
elem.Count
|
||||
}, transaction);
|
||||
}
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при редактировании объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
15
ProjectAtelier/appsettings.json
Normal file
15
ProjectAtelier/appsettings.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs.txt",
|
||||
"rollingInterval": "Day"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user