МЕГА КОММИТ 2.0. Подписаться

This commit is contained in:
LivelyPuer 2024-12-20 01:12:17 +04:00
parent 78706eac6f
commit c7a8b337e7
21 changed files with 626 additions and 120 deletions

View File

@ -43,18 +43,20 @@
panelButtons.Controls.Add(buttonUpd);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(650, 0);
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(150, 450);
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 1;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(20, 323);
buttonDel.Location = new Point(18, 242);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(113, 100);
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
@ -63,9 +65,10 @@
//
buttonUpd.BackgroundImage = Properties.Resources.Button_Edit;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(20, 174);
buttonUpd.Location = new Point(18, 130);
buttonUpd.Margin = new Padding(3, 2, 3, 2);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(113, 100);
buttonUpd.Size = new Size(99, 75);
buttonUpd.TabIndex = 1;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
@ -74,9 +77,10 @@
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(20, 26);
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(113, 100);
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
@ -89,21 +93,24 @@
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.Margin = new Padding(3, 2, 3, 2);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 51;
dataGridViewData.Size = new Size(650, 450);
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(569, 338);
dataGridViewData.TabIndex = 2;
//
// FormCustomers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewData);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormCustomers";
StartPosition = FormStartPosition.CenterParent;
Text = "Заказчики";

View File

@ -37,8 +37,6 @@
label3 = new Label();
comboBoxStatus = new ComboBox();
dataGridViewProducts = new DataGridView();
ColumnProduct = new DataGridViewComboBoxColumn();
ColumnQuantity = new DataGridViewTextBoxColumn();
groupBox1 = new GroupBox();
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).BeginInit();
groupBox1.SuspendLayout();
@ -120,7 +118,6 @@
// dataGridViewProducts
//
dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewProducts.Columns.AddRange(new DataGridViewColumn[] { ColumnProduct, ColumnQuantity });
dataGridViewProducts.Dock = DockStyle.Fill;
dataGridViewProducts.Location = new Point(3, 23);
dataGridViewProducts.Name = "dataGridViewProducts";
@ -129,20 +126,6 @@
dataGridViewProducts.Size = new Size(392, 236);
dataGridViewProducts.TabIndex = 14;
//
// ColumnProduct
//
ColumnProduct.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnProduct.HeaderText = "Товар";
ColumnProduct.MinimumWidth = 6;
ColumnProduct.Name = "ColumnProduct";
//
// ColumnQuantity
//
ColumnQuantity.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnQuantity.HeaderText = "Количество";
ColumnQuantity.MinimumWidth = 6;
ColumnQuantity.Name = "ColumnQuantity";
//
// groupBox1
//
groupBox1.Controls.Add(dataGridViewProducts);
@ -186,7 +169,5 @@
private ComboBox comboBoxStatus;
private DataGridView dataGridViewProducts;
private GroupBox groupBox1;
private DataGridViewComboBoxColumn ColumnProduct;
private DataGridViewTextBoxColumn ColumnQuantity;
}
}

View File

@ -33,11 +33,49 @@ public partial class FormOrder : Form
dataGridViewProducts.AllowUserToAddRows = true;
dataGridViewProducts.AllowUserToDeleteRows = true;
// Настройка таблицы товаров
InitializeDataGridViewProducts();
// Настройка DateTimePicker для даты заказа
dateTimePickerOrderDate.Value = DateTime.Now;
dateTimePickerOrderDate.Enabled = false;
}
private void InitializeDataGridViewProducts()
{
// Отключаем авто-генерацию столбцов
dataGridViewProducts.AutoGenerateColumns = false;
// Устанавливаем режим авторазмера столбцов
dataGridViewProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
// Столбец "Товар"
var productColumn = new DataGridViewComboBoxColumn
{
Name = "ColumnProduct",
HeaderText = "Товар",
DataSource = _productRepository.ReadProducts()
.Select(p => new { p.Id, p.Type }) // Пример данных: Id и Name
.ToList(),
DisplayMember = "Type",
ValueMember = "Id",
FlatStyle = FlatStyle.Flat
};
dataGridViewProducts.Columns.Add(productColumn);
// Столбец "Количество"
var quantityColumn = new DataGridViewTextBoxColumn
{
Name = "ColumnQuantity",
HeaderText = "Количество",
ValueType = typeof(int)
};
dataGridViewProducts.Columns.Add(quantityColumn);
productColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
quantityColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
private void ButtonSave_Click(object sender, EventArgs e)
{

View File

@ -117,10 +117,4 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ColumnProduct.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnQuantity.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -41,18 +41,20 @@
panelButtons.Controls.Add(buttonDel);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(650, 0);
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(150, 450);
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 2;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(20, 323);
buttonDel.Location = new Point(18, 242);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(113, 100);
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
@ -61,9 +63,10 @@
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(20, 26);
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(113, 100);
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
@ -76,21 +79,24 @@
dataGridViewOrders.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewOrders.Dock = DockStyle.Fill;
dataGridViewOrders.Location = new Point(0, 0);
dataGridViewOrders.Margin = new Padding(3, 2, 3, 2);
dataGridViewOrders.MultiSelect = false;
dataGridViewOrders.Name = "dataGridViewOrders";
dataGridViewOrders.ReadOnly = true;
dataGridViewOrders.RowHeadersVisible = false;
dataGridViewOrders.RowHeadersWidth = 51;
dataGridViewOrders.Size = new Size(650, 450);
dataGridViewOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewOrders.Size = new Size(569, 338);
dataGridViewOrders.TabIndex = 3;
//
// FormOrders
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewOrders);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormOrders";
Text = "Заказать товары";
Load += FormOrders_Load;

View File

@ -73,6 +73,11 @@ public partial class FormOrders : Form
private void LoadList()
{
dataGridViewOrders.DataSource = _orderRepository.ReadOrders();
if (dataGridViewOrders.Columns.Contains("OrderProducts"))
{
dataGridViewOrders.Columns["OrderProducts"].Visible = false;
}
}
// Метод для получения идентификатора заказа из выбранной строки в DataGridView

View File

@ -104,9 +104,9 @@
label4.AutoSize = true;
label4.Location = new Point(32, 287);
label4.Name = "label4";
label4.Size = new Size(97, 20);
label4.Size = new Size(72, 20);
label4.TabIndex = 8;
label4.Text = "ID магазина:";
label4.Text = "Магазин:";
//
// label5
//

View File

@ -1,11 +1,12 @@
using ProjectOpticsStore.Entities;
using ProjectOpticsStore.Entities.Enums;
using ProjectOpticsStore.Entities.Enums;
using ProjectOpticsStore.Repositories;
namespace ProjectOpticsStore.Forms;
public partial class FormProduct : Form
{
private readonly IProductRepository _productRepository;
private readonly IStoreRepository _storeRepository;
private int? _productId;
public int Id
@ -34,7 +35,7 @@ public partial class FormProduct : Form
// Заполнение текстовых полей
textBoxPower.Text = product.Power.ToString();
textBoxPrice.Text = product.Price.ToString();
comboBoxStore.Text = product.Store.ToString();
comboBoxStore.SelectedValue = product.Store;
textBoxThickness.Text = product.Thickness.ToString("F2");
textBoxDisease.Text = product.Disease;
@ -48,16 +49,22 @@ public partial class FormProduct : Form
}
}
public FormProduct(IProductRepository productRepository)
public FormProduct(IProductRepository productRepository, IStoreRepository storeRepository)
{
InitializeComponent();
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
_storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository));
// Заполнение CheckedListBox значениями перечисления
// Инициализация CheckedListBox значениями перечисления
foreach (var elem in Enum.GetValues(typeof(ProductTypeEnum)))
{
checkedListBoxProductType.Items.Add(elem);
}
// Инициализация ComboBox для магазинов
comboBoxStore.DataSource = _storeRepository.ReadStores().ToList();
comboBoxStore.DisplayMember = "Address"; // Отображаем адрес магазина
comboBoxStore.ValueMember = "Id"; // Значение это идентификатор магазина
}
private void ButtonSave_Click(object sender, EventArgs e)
@ -68,7 +75,7 @@ public partial class FormProduct : Form
if (checkedListBoxProductType.CheckedItems.Count == 0 ||
string.IsNullOrWhiteSpace(textBoxPower.Text) ||
string.IsNullOrWhiteSpace(textBoxPrice.Text) ||
string.IsNullOrWhiteSpace(comboBoxStore.Text) ||
comboBoxStore.SelectedValue == null ||
string.IsNullOrWhiteSpace(textBoxThickness.Text))
{
throw new Exception("Имеются незаполненные поля.");
@ -103,13 +110,16 @@ public partial class FormProduct : Form
productType |= (ProductTypeEnum)elem;
}
// Получение идентификатора магазина из ComboBox (это целое число)
int storeId = (int)comboBoxStore.SelectedValue!;
// Создание сущности Product
return Product.CreateEntity(
id,
productType,
double.Parse(textBoxPower.Text),
int.Parse(textBoxPrice.Text),
int.Parse(comboBoxStore.Text),
storeId, // Передаем идентификатор магазина, а не адрес
float.Parse(textBoxThickness.Text),
textBoxDisease.Text
);

View File

@ -43,18 +43,20 @@
panelButtons.Controls.Add(buttonUpd);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(650, 0);
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(150, 450);
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 3;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(20, 323);
buttonDel.Location = new Point(18, 242);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(113, 100);
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
@ -63,9 +65,10 @@
//
buttonUpd.BackgroundImage = Properties.Resources.Button_Edit;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(20, 174);
buttonUpd.Location = new Point(18, 130);
buttonUpd.Margin = new Padding(3, 2, 3, 2);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(113, 100);
buttonUpd.Size = new Size(99, 75);
buttonUpd.TabIndex = 1;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
@ -74,9 +77,10 @@
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(20, 26);
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(113, 100);
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
@ -89,21 +93,24 @@
dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewProducts.Dock = DockStyle.Fill;
dataGridViewProducts.Location = new Point(0, 0);
dataGridViewProducts.Margin = new Padding(3, 2, 3, 2);
dataGridViewProducts.MultiSelect = false;
dataGridViewProducts.Name = "dataGridViewProducts";
dataGridViewProducts.ReadOnly = true;
dataGridViewProducts.RowHeadersVisible = false;
dataGridViewProducts.RowHeadersWidth = 51;
dataGridViewProducts.Size = new Size(650, 450);
dataGridViewProducts.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewProducts.Size = new Size(569, 338);
dataGridViewProducts.TabIndex = 4;
//
// FormProducts
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewProducts);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormProducts";
Text = "Работа с товарами";
Load += FormProducts_Load;

View File

@ -43,18 +43,20 @@
panelButtons.Controls.Add(buttonUpd);
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(650, 0);
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(150, 450);
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 4;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.Button_Delete;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(20, 323);
buttonDel.Location = new Point(18, 242);
buttonDel.Margin = new Padding(3, 2, 3, 2);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(113, 100);
buttonDel.Size = new Size(99, 75);
buttonDel.TabIndex = 2;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
@ -63,9 +65,10 @@
//
buttonUpd.BackgroundImage = Properties.Resources.Button_Edit;
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpd.Location = new Point(20, 174);
buttonUpd.Location = new Point(18, 130);
buttonUpd.Margin = new Padding(3, 2, 3, 2);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(113, 100);
buttonUpd.Size = new Size(99, 75);
buttonUpd.TabIndex = 1;
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
@ -74,9 +77,10 @@
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(20, 26);
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(113, 100);
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
@ -89,21 +93,24 @@
dataGridViewStores.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewStores.Dock = DockStyle.Fill;
dataGridViewStores.Location = new Point(0, 0);
dataGridViewStores.Margin = new Padding(3, 2, 3, 2);
dataGridViewStores.MultiSelect = false;
dataGridViewStores.Name = "dataGridViewStores";
dataGridViewStores.ReadOnly = true;
dataGridViewStores.RowHeadersVisible = false;
dataGridViewStores.RowHeadersWidth = 51;
dataGridViewStores.Size = new Size(650, 450);
dataGridViewStores.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewStores.Size = new Size(569, 338);
dataGridViewStores.TabIndex = 5;
//
// FormStores
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewStores);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormStores";
Text = "Так сказать магазины";
Load += FormStores_Load;

View File

@ -39,18 +39,20 @@
//
panelButtons.Controls.Add(buttonAdd);
panelButtons.Dock = DockStyle.Right;
panelButtons.Location = new Point(650, 0);
panelButtons.Location = new Point(569, 0);
panelButtons.Margin = new Padding(3, 2, 3, 2);
panelButtons.Name = "panelButtons";
panelButtons.Size = new Size(150, 450);
panelButtons.Size = new Size(131, 338);
panelButtons.TabIndex = 5;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Button_Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(20, 26);
buttonAdd.Location = new Point(18, 20);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(113, 100);
buttonAdd.Size = new Size(99, 75);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
@ -63,21 +65,24 @@
dataGridViewSupplies.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewSupplies.Dock = DockStyle.Fill;
dataGridViewSupplies.Location = new Point(0, 0);
dataGridViewSupplies.Margin = new Padding(3, 2, 3, 2);
dataGridViewSupplies.MultiSelect = false;
dataGridViewSupplies.Name = "dataGridViewSupplies";
dataGridViewSupplies.ReadOnly = true;
dataGridViewSupplies.RowHeadersVisible = false;
dataGridViewSupplies.RowHeadersWidth = 51;
dataGridViewSupplies.Size = new Size(650, 450);
dataGridViewSupplies.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewSupplies.Size = new Size(569, 338);
dataGridViewSupplies.TabIndex = 6;
//
// FormSupplies
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(700, 338);
Controls.Add(dataGridViewSupplies);
Controls.Add(panelButtons);
Margin = new Padding(3, 2, 3, 2);
Name = "FormSupplies";
Text = "Определенным образом поставка";
Load += FormSupplies_Load;

View File

@ -1,7 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectOpticsStore.Repositories;
using ProjectOpticsStore.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace ProjectOpticsStore
{
@ -18,15 +22,33 @@ namespace ProjectOpticsStore
ApplicationConfiguration.Initialize();
Application.Run(CreateContainer().Resolve<FormOpticsStore>());
}
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<ICustomerRepository, CustomerRepository>(new TransientLifetimeManager());
container.RegisterType<IOrderRepository, OrderRepository>(new TransientLifetimeManager());
container.RegisterType<IProductRepository, ProductRepository>(new TransientLifetimeManager());
container.RegisterType<IStoreRepository, StoreRepository>(new TransientLifetimeManager());
container.RegisterType<ISupplyRepository, SupplyRepository>(new TransientLifetimeManager());
container.RegisterType<IConnectionString, ConnectionString>(new TransientLifetimeManager());
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;
}
}
}

View File

@ -13,7 +13,20 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Container" Version="5.11.11" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -31,4 +44,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
namespace ProjectOpticsStore.Repositories;
public interface IConnectionString
{
public string ConnectionString { get; }
}

View File

@ -0,0 +1,6 @@
namespace ProjectOpticsStore.Repositories.Implementations;
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=127.0.0.1;Database=opticsstore;Username=postgres;Password=postgres";
}

View File

@ -1,28 +1,116 @@
using ProjectOpticsStore.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class CustomerRepository : ICustomerRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CustomerRepository> _logger;
public CustomerRepository(IConnectionString connectionString, ILogger<CustomerRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateCustomer(Customer customer)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Customers (FullName)
VALUES (@FullName)";
connection.Execute(queryInsert, customer);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateCustomer(Customer customer)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Customers
SET
FullName=@Fullname
WHERE Id=@Id";
connection.Execute(queryUpdate, customer);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteCustomer(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Customers
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Customer ReadCustomerById(int id)
{
return Customer.CreateEntity(0, string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Customers
WHERE Id=@id";
var customer = connection.QueryFirst<Customer>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(customer));
return customer;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Customer> ReadCustomers()
{
return [];
}
public void UpdateCustomer(Customer customer)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Customers";
var customers = connection.Query<Customer>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(customers));
return customers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,17 +1,92 @@
namespace ProjectOpticsStore.Repositories.Implementations;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class OrderRepository : IOrderRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> 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 (CustomerId, DateCreated, Status)
VALUES (@CustomerId, @DateCreated, @Status);
SELECT MAX(Id) FROM Orders";
var OrderId = connection.QueryFirst<int>(queryInsert, order, transaction);
var querySubInsert = @"
INSERT INTO Orders_Products (OrderId, ProductId, Quantity)
VALUES (@OrderId, @ProductId, @Quantity)";
foreach (var elem in order.OrderProducts)
{
connection.Execute(querySubInsert, new { OrderId, elem.ProductId, elem.Quantity }, 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? dateFrom = null, DateTime? dateTo = null, int? customerId = null)
{
return [];
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Orders";
var orders = connection.Query<Order>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orders;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}
}

View File

@ -1,33 +1,124 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectOpticsStore.Entities.Enums;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace ProjectOpticsStore.Repositories.Implementations;
internal 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);
var queryInsert = @"
INSERT INTO Products (Type, Power, Price, Store, Thickness, Disease)
VALUES (@Type, @Power, @Price, @Store, @Thickness, @Disease)";
connection.Execute(queryInsert, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateProduct(Product product)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Products
SET
Type=@Type,
Power=@Power,
Price=@Price,
Store=@Store,
Thickness=@Thickness,
Disease=@Disease
WHERE Id=@Id";
connection.Execute(queryUpdate, product);
}
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 Product ReadProductById(int id)
{
return Product.CreateEntity(0, ProductTypeEnum.None, 0, 0, 0, 0, string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Products
WHERE Id=@id";
var product = connection.QueryFirst<Product>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product));
return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Product> ReadProducts()
{
return [];
}
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
public void UpdateProduct(Product product)
{
// SQL-запрос для получения всех продуктов
var querySelect = "SELECT * FROM Products";
var products = connection.Query<Product>(querySelect);
return products;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}

View File

@ -1,33 +1,115 @@
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 ProjectOpticsStore.Entities;
using ProjectOpticsStore.Entities.Enums;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class StoreRepository : IStoreRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StoreRepository> _logger;
public StoreRepository(IConnectionString connectionString, ILogger<StoreRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateStore(Store store)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(store));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Stores (Address)
VALUES (@Address)";
connection.Execute(queryInsert, store);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateStore(Store store)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(store));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Stores
SET
Address=@Address
WHERE Id=@Id";
connection.Execute(queryUpdate, store);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteStore(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Stores
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Store ReadStoreById(int id)
{
return Store.CreateEntity(0, string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Stores
WHERE Id=@id";
var store = connection.QueryFirst<Store>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(store));
return store;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Store> ReadStores()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Stores";
var stores = connection.Query<Store>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(stores));
return stores;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateStore(Store store)
{
}
}
}

View File

@ -1,15 +1,57 @@
using ProjectOpticsStore.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsStore.Entities;
namespace ProjectOpticsStore.Repositories.Implementations;
internal class SupplyRepository : ISupplyRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SupplyRepository> _logger;
public SupplyRepository(IConnectionString connectionString, ILogger<SupplyRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSupply(Supply supply)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supply));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Supplies (StoreId, OperationDate, ProductId, Quantity)
VALUES (@StoreId, @OperationDate, @ProductId, @Quantity)";
connection.Execute(queryInsert, supply);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Supply> ReadSupplies(DateTime? dateFrom = null, DateTime? dateTo = null, int? storeId = null, int? productId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Supplies";
var supplies = connection.Query<Supply>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supplies));
return supplies;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/schedule_log.txt",
"rollingInterval": "Day"
}
}
]
}
}