1 Commits

Author SHA1 Message Date
f6966a2f78 Лабораторная 2 2024-12-22 17:03:53 +04:00
34 changed files with 1054 additions and 148 deletions

View File

@@ -5,6 +5,9 @@
public int Id { get; set; }
public List<ProductInCheque> Products { get; set; }
public Client Client { get; set; }
[System.ComponentModel.Browsable(false)]
public int ClientId { get; set; }
public DateTime PurchaseDate { get; set; }
public static Cheque CreateEntity(int id, List<ProductInCheque> products, Client client, DateTime purchaseDate)

View File

@@ -1,4 +1,10 @@
using ProjectSellPC.Entites.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSellPC.Entites
{
public class Client
@@ -18,5 +24,10 @@ namespace ProjectSellPC.Entites
ClientType = clientType
};
}
public override string ToString()
{
return Name;
}
}
}

View File

@@ -18,5 +18,9 @@ namespace ProjectSellPC.Entites
Price = price,
ProductType = productType };
}
public override string ToString()
{
return Name;
}
}
}

View File

@@ -1,12 +1,21 @@
namespace ProjectSellPC.Entites
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSellPC.Entites
{
public class ProductInCheque
{
public int ID { get; set; }
//отредактировать базу данных!!!!!!!
public int ProductID { get; set; }
public int ChequeID { get; set; }
public int Count { get; set; }
public static ProductInCheque CreateElement(int id, int count)
{
return new ProductInCheque { ID = id, Count = count};
return new ProductInCheque { ProductID = id, Count = count };
}
}
}

View File

@@ -1,9 +1,18 @@
namespace ProjectSellPC.Entites
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSellPC.Entites
{
public class ProductsOnWarehouse
{
public int Id { get; set; }
[System.ComponentModel.Browsable(false)]
public int ProductId { get; set; }
public Product Product { get; set; }
[System.ComponentModel.Browsable(false)]
public int WarehouseId { get; set; }
public Warehouse Warehouse { get; set; }
public int Count { get; set; }

View File

@@ -1,4 +1,10 @@
namespace ProjectSellPC.Entites
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ProjectSellPC.Entites
{
public class Warehouse
{
@@ -10,5 +16,10 @@
{
return new Warehouse { Id = id, Size = size, Adress = adress };
}
public override string ToString()
{
return Adress;
}
}
}

View File

@@ -1,5 +1,14 @@
using ProjectSellPC.Repos;
using Unity;
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 ProjectSellPC.Forms.Receipt
{

View File

@@ -1,6 +1,15 @@
using ProjectSellPC.Entites;
using ProjectSellPC.Repos;
using ProjectSellPC.Entites.Enums;
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 ProjectSellPC.Forms.Receipt
{
public partial class ChequeSettingsForm : Form
@@ -59,7 +68,7 @@ namespace ProjectSellPC.Forms.Receipt
var list = new List<ProductInCheque>();
foreach (DataGridViewRow row in productsDataGridView.Rows)
{
if (row.Cells["ProductColoumn"].Value == null || row.Cells["ColumnCount"].Value == null)
if (row.Cells["ProductColoumn"].Value == null || row.Cells["ProductCount"].Value == null)
{
continue;
}

View File

@@ -1,6 +1,15 @@
using ProjectSellPC.Forms.Clients;
using ProjectSellPC.Repos;
using Unity;
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 ProjectSellPC.Forms
{

View File

@@ -1,6 +1,15 @@
using ProjectSellPC.Entites.Enums;
using ProjectSellPC.Entites;
using ProjectSellPC.Repos;
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 ProjectSellPC.Forms.Clients
{
@@ -17,7 +26,7 @@ namespace ProjectSellPC.Forms.Clients
try
{
var client = _repository.Read(value);
if (client != null)
if (client == null)
{
throw new InvalidDataException(nameof(client));
}
@@ -67,7 +76,7 @@ namespace ProjectSellPC.Forms.Clients
else
{
_repository.Update(CreateClient(0));
_repository.Create(CreateClient(0));
}
Close();

View File

@@ -1,5 +1,14 @@
using ProjectSellPC.Repos;
using Unity;
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 ProjectSellPC
{

View File

@@ -36,7 +36,7 @@
priceNumeric = new NumericUpDown();
label3 = new Label();
label4 = new Label();
typeCheckedListBox = new CheckedListBox();
typeChequeedListBox = new CheckedListBox();
((System.ComponentModel.ISupportInitialize)priceNumeric).BeginInit();
SuspendLayout();
//
@@ -111,20 +111,20 @@
label4.TabIndex = 7;
label4.Text = "Вид:";
//
// typeCheckedListBox
// typeChequeedListBox
//
typeCheckedListBox.FormattingEnabled = true;
typeCheckedListBox.Location = new Point(152, 285);
typeCheckedListBox.Name = "typeCheckedListBox";
typeCheckedListBox.Size = new Size(150, 114);
typeCheckedListBox.TabIndex = 8;
typeChequeedListBox.FormattingEnabled = true;
typeChequeedListBox.Location = new Point(152, 285);
typeChequeedListBox.Name = "typeChequeedListBox";
typeChequeedListBox.Size = new Size(150, 114);
typeChequeedListBox.TabIndex = 8;
//
// ProductSettingsForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(409, 477);
Controls.Add(typeCheckedListBox);
Controls.Add(typeChequeedListBox);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(priceNumeric);
@@ -152,6 +152,6 @@
private NumericUpDown priceNumeric;
private Label label3;
private Label label4;
private CheckedListBox typeCheckedListBox;
private CheckedListBox typeChequeedListBox;
}
}

View File

@@ -1,6 +1,9 @@
using ProjectSellPC.Entites;
using ProjectSellPC.Entites.Enums;
using ProjectSellPC.Repos;
using Microsoft.VisualBasic.FileIO;
using System;
using System.Windows.Forms;
namespace ProjectSellPC
{
@@ -17,7 +20,7 @@ namespace ProjectSellPC
try
{
var product = _productRepository.Read(value);
if (product != null)
if (product == null)
{
throw new InvalidDataException(nameof(product));
}
@@ -28,7 +31,7 @@ namespace ProjectSellPC
if ((elem & product.ProductType) != 0)
{
typeCheckedListBox.SetItemChecked(typeCheckedListBox.Items.IndexOf(elem), true);
typeChequeedListBox.SetItemChecked(typeChequeedListBox.Items.IndexOf(elem), true);
}
}
priceNumeric.Value = product.Price;
@@ -50,7 +53,7 @@ namespace ProjectSellPC
foreach (var elem in Enum.GetValues(typeof(ProductType)))
{
typeCheckedListBox.Items.Add(elem);
typeChequeedListBox.Items.Add(elem);
}
}
@@ -65,7 +68,7 @@ namespace ProjectSellPC
try
{
if (string.IsNullOrWhiteSpace(productNameTextbox.Text) ||
string.IsNullOrWhiteSpace(descriptionTextbox.Text) || typeCheckedListBox.CheckedItems.Count == 0)
string.IsNullOrWhiteSpace(descriptionTextbox.Text) || typeChequeedListBox.CheckedItems.Count == 0)
{
throw new Exception("Имеются незаполненные поля");
}
@@ -92,7 +95,7 @@ namespace ProjectSellPC
private Product CreateProduct(int id)
{
ProductType type = ProductType.None;
foreach (var elem in typeCheckedListBox.CheckedItems)
foreach (var elem in typeChequeedListBox.CheckedItems)
{
type |= (ProductType)elem;
}

View File

@@ -54,16 +54,7 @@
productsDataGridView.RowHeadersWidth = 51;
productsDataGridView.Size = new Size(851, 400);
productsDataGridView.TabIndex = 8;
//
// editButton
//
editButton.Location = new Point(881, 78);
editButton.Name = "editButton";
editButton.Size = new Size(161, 60);
editButton.TabIndex = 10;
editButton.Text = "Редактировать";
editButton.UseVisualStyleBackColor = true;
editButton.Click += editButton_Click;
//
// ProductsOnWarehouseForm
//

View File

@@ -1,6 +1,24 @@
using ProjectSellPC.Repos;
using Unity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 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 ProjectSellPC.Forms.ProductsOnWarehouse
{
public partial class ProductsOnWarehouseForm : Form
@@ -56,18 +74,19 @@ namespace ProjectSellPC.Forms.ProductsOnWarehouse
}
}
private void editButton_Click(object sender, EventArgs e)
private void deleteButton_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
var form = _container.Resolve<ProductsOnWarehouseSettingsForm>();
form.Id = findId;
form.ShowDialog();
_productOnWarehouseRepository.Delete(findId);
LoadList();
}
catch (Exception ex)

View File

@@ -1,5 +1,14 @@
using ProjectSellPC.Entites;
using ProjectSellPC.Repos;
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 ProjectSellPC.Forms.ProductsOnWarehouse
{
@@ -22,9 +31,22 @@ namespace ProjectSellPC.Forms.ProductsOnWarehouse
{
throw new InvalidDataException("Record not found");
}
productCombobox.SelectedItem = record.Product;
WarehouseCombobox.SelectedItem = record.Warehouse;
//ProductComboBox
foreach (var item in _productRepository.ReadAll())
{
if (item.ID == record.ProductId)
{
productCombobox.SelectedItem = item;
}
}
//WarehouseCombobox
foreach (var item in _WarehouseRepository.ReadAll())
{
if (item.Id == record.WarehouseId)
{
WarehouseCombobox.SelectedItem = item;
}
}
countNumeric.Value = record.Count;
_recordId = value;
}
@@ -59,7 +81,7 @@ namespace ProjectSellPC.Forms.ProductsOnWarehouse
productCombobox.ValueMember = "Id";
WarehouseCombobox.DataSource = _WarehouseRepository.ReadAll().ToList();
WarehouseCombobox.DisplayMember = "Name";
WarehouseCombobox.DisplayMember = "Adress";
WarehouseCombobox.ValueMember = "Id";
}
@@ -67,7 +89,7 @@ namespace ProjectSellPC.Forms.ProductsOnWarehouse
{
try
{
if (productCombobox.SelectedItem == null || WarehouseCombobox.SelectedItem == null || countNumeric.Value < 1)
if (productCombobox.SelectedItem == null || WarehouseCombobox.SelectedItem == null)
{
throw new Exception("Заполните все поля");
}
@@ -75,16 +97,7 @@ namespace ProjectSellPC.Forms.ProductsOnWarehouse
var selectedProduct = (Product)productCombobox.SelectedItem;
var selectedWarehouse = (Entites.Warehouse)WarehouseCombobox.SelectedItem;
var count = (int)countNumeric.Value;
if (_recordId.HasValue)
{
_productOnWarehouseRepository.Update(CreateProductOnWarehouse(_recordId.Value, selectedProduct, selectedWarehouse, count));
}
else
{
_productOnWarehouseRepository.Create(CreateProductOnWarehouse(0, selectedProduct, selectedWarehouse, count));
}
_productOnWarehouseRepository.Create(CreateProductOnWarehouse(0, selectedProduct, selectedWarehouse, count));
Close();
}
catch (Exception ex)

View File

@@ -1,4 +1,13 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectSellPC.Forms.Clients;
using ProjectSellPC.Repos;
using Unity;

View File

@@ -1,4 +1,16 @@
using ProjectSellPC.Repos;
using ProjectSellPC.Entites.Enums;
using ProjectSellPC.Entites;
using ProjectSellPC.Repos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProjectSellPC.Repos;
namespace ProjectSellPC.Forms.Warehouse
@@ -16,7 +28,7 @@ namespace ProjectSellPC.Forms.Warehouse
try
{
var Warehouse = _repository.Read(value);
if (Warehouse != null)
if (Warehouse == null)
{
throw new InvalidDataException(nameof(Warehouse));
}
@@ -61,7 +73,7 @@ namespace ProjectSellPC.Forms.Warehouse
else
{
_repository.Update(CreateWarehouse(0));
_repository.Create(CreateWarehouse(0));
}
Close();

View File

@@ -1,7 +1,10 @@
using ProjectSellPC.Repos;
using ProjectSellPC.Repos.Impements;
using Microsoft.Extensions.Logging;
using Unity;
using Unity.Lifetime;
using Serilog;
using Microsoft.Extensions.Configuration;
namespace ProjectSellPC
{
@@ -20,13 +23,29 @@ namespace ProjectSellPC
{
var container = new UnityContainer();
container.RegisterInstance<ILoggerFactory>(CreateLoggerFactory());
container.RegisterType<IConnectionString, ConnectionString>(new SingletonLifetimeManager());
container.RegisterType<IProductRepository, ProductRepo>(new TransientLifetimeManager());
container.RegisterType<IClientRepository, ClientRepo>(new TransientLifetimeManager());
container.RegisterType<IWarehouseRepository, WarehouseRepo>(new TransientLifetimeManager());
container.RegisterType<IProductOnWarehouseRepository, ProductsOnWarehouseRepo>(new TransientLifetimeManager());
container.RegisterType<IProductInChequeRepository, ProductInChequeRepo>(new TransientLifetimeManager());
container.RegisterType<IChequeRepository, ChequeRepo>(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

@@ -9,7 +9,22 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" 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.AspNetCore" Version="9.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSellPC.Repos
{
public interface IConnectionString
{
string ConnectionString { get; }
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectSellPC.Entites;
namespace ProjectSellPC.Repos
{
public interface IProductInChequeRepository
{
IEnumerable<ProductInCheque> ReadAll();
ProductInCheque Read(int id);
void Create(ProductInCheque ps);
}
}

View File

@@ -6,6 +6,6 @@ namespace ProjectSellPC.Repos
IEnumerable<ProductsOnWarehouse> ReadAll();
ProductsOnWarehouse Read(int id);
void Create(ProductsOnWarehouse ps);
ProductsOnWarehouse Update(ProductsOnWarehouse Warehouse);
void Delete(int id);
}
}

View File

@@ -1,23 +0,0 @@
using ProjectSellPC.Entites;
namespace ProjectSellPC.Repos.Impements
{
public class ChequeRepo : IChequeRepository
{
public void Create(Cheque Cheque)
{
}
public Cheque Read(int id)
{
return Cheque.CreateEntity(0, new List<ProductInCheque>(), new Client(), DateTime.Now);
}
public IEnumerable<Cheque> ReadAll()
{
return new List<Cheque>();
}
}
}

View File

@@ -0,0 +1,121 @@
using ProjectSellPC.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace ProjectSellPC.Repos.Impements
{
public class ChequeRepo : IChequeRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ChequeRepo> _logger;
private readonly IClientRepository _clientRepository;
public ChequeRepo(IConnectionString connectionString, ILoggerFactory loggerFactory, IClientRepository clientRepository)
{
_connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
_logger = loggerFactory.CreateLogger<ChequeRepo>();
_clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository));
}
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
public void Create(Cheque Cheque)
{
_logger.LogInformation("Создание чека");
using (var connection = CreateConnection())
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
try
{
var chequeSql = "INSERT INTO \"cheque\" (\"clientid\", \"purchasedate\") VALUES (@ClientId, @PurchaseDate) RETURNING \"id\"";
Cheque.Id = connection.ExecuteScalar<int>(chequeSql, new
{
ClientId = Cheque.Client.Id,
PurchaseDate = Cheque.PurchaseDate
}, transaction);
var productSql = "INSERT INTO \"productsincheque\" (\"chequeid\", \"productid\", \"count\") VALUES (@ChequeId, @ProductID, @Count)";
foreach (var productInCheque in Cheque.Products)
{
connection.Execute(productSql, new
{
ChequeId = Cheque.Id,
ProductID = productInCheque.ProductID,
Count = productInCheque.Count
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
_logger.LogError(ex, "Ошибка при создании чека");
throw;
}
}
}
}
public Cheque Read(int id)
{
_logger.LogInformation("Чтение чека по ID: {id}", id);
using (var connection = CreateConnection())
{
try
{
var ChequeSql = "SELECT * FROM \"cheque\" WHERE \"id\" = @Id";
var Cheque = connection.QuerySingleOrDefault<Cheque>(ChequeSql, new { Id = id });
if (Cheque == null) return null;
Cheque.Client = _clientRepository.Read(Cheque.Client.Id);
var productSql = "SELECT * FROM \"productsincheque\" WHERE \"chequeid\" = @ChequeId";
Cheque.Products = connection.Query<ProductInCheque>(productSql, new { ChequeId = Cheque.Id }).ToList();
return Cheque;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении чека");
throw;
}
}
}
public IEnumerable<Cheque> ReadAll()
{
_logger.LogInformation("Чтение всех чеков");
using (var connection = CreateConnection())
{
try
{
var ChequeSql = "SELECT * FROM \"cheque\"";
var Cheques = connection.Query<Cheque>(ChequeSql).ToList();
foreach (var Cheque in Cheques)
{
Cheque.Client = _clientRepository.Read(Cheque.ClientId);
var productSql = "SELECT * FROM \"productsincheque\" WHERE \"chequeeid\" = @ChequeId";
Cheque.Products = connection.Query<ProductInCheque>(productSql, new { ChequeId = Cheque.Id }).ToList();
}
return Cheques;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении всех чеков");
throw;
}
}
}
}
}

View File

@@ -1,33 +1,141 @@
using ProjectSellPC.Entites;
using ProjectSellPC.Entites.Enums;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
namespace ProjectSellPC.Repos.Impements
{
public class ClientRepo : IClientRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepo> _logger;
public ClientRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<ClientRepo>();
}
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
public void Create(Client client)
{
_logger.LogInformation("Добавление клиента");
_logger.LogDebug("Клиент: {json}", JsonConvert.SerializeObject(client));
try
{
using (var connection = CreateConnection())
{
var sql = "INSERT INTO \"client\" (\"name\", \"phonenumber\", \"clienttype\") " +
"VALUES (@Name, @PhoneNumber, @ClientType)";
connection.Execute(sql, new
{
Name = client.Name,
PhoneNumber = client.PhoneNumber,
ClientType = (int)client.ClientType
});
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении клиента");
throw;
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление клиента");
_logger.LogDebug("Клиент ID: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = "DELETE FROM \"client\" WHERE \"id\" = @Id";
connection.Execute(sql, new { Id = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении клиента");
throw;
}
}
public Client Read(int id)
{
return Client.CreateEntity(0, string.Empty, string.Empty, ClientType.Individual);
_logger.LogInformation("Получение клиента по ID");
_logger.LogDebug("Клиент ID: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"client\" WHERE \"id\" = @Id";
return connection.QuerySingleOrDefault<Client>(sql, new { Id = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении клиента");
throw;
}
}
public IEnumerable<Client> ReadAll()
{
return new List<Client>();
_logger.LogInformation("Получение всех клиентов");
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"client\"";
return connection.Query<Client>(sql);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении списка клиентов");
throw;
}
}
public Client Update(Client client)
{
return Client.CreateEntity(0, string.Empty, string.Empty, ClientType.Individual);
_logger.LogInformation("Обновление информации о клиенте");
_logger.LogDebug("Клиент: {json}", JsonConvert.SerializeObject(client));
try
{
using (var connection = CreateConnection())
{
var sql = "UPDATE \"client\" SET \"name\" = @Name, \"phonenumber\" = @PhoneNumber, \"clienttype\" = @ClientType " +
"WHERE \"id\" = @Id";
connection.Execute(sql, new
{
Id = client.Id,
Name = client.Name,
PhoneNumber = client.PhoneNumber,
ClientType = (int)client.ClientType
});
return client;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при обновлении информации о клиенте");
throw;
}
}
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectSellPC.Repos;
namespace ProjectSellPC.Repos.Impements
{
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Username=postgres;Password=78oripop;Database=otp2";
}
}

View File

@@ -0,0 +1,136 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectSellPC.Entites;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSellPC.Repos.Impements
{
public class ProductInChequeRepo : IProductInChequeRepository
{
private readonly IProductRepository _productRepository;
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductInChequeRepo> _logger;
public ProductInChequeRepo(IConnectionString connectionString, ILoggerFactory loggerFactory, IProductRepository productRepository)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<ProductInChequeRepo>();
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
}
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
public void Create(ProductInCheque productInCheque)
{
_logger.LogInformation("Добавление товара в чек");
_logger.LogDebug("Товар в чеке: {json}", Newtonsoft.Json.JsonConvert.SerializeObject(productInCheque));
using (var connection = CreateConnection())
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
try
{
var sql = "INSERT INTO \"productsincheque\" (\"productid\", \"count\") " +
"VALUES (@ProductID, @Count) RETURNING \"ID\"";
productInCheque.ID = connection.ExecuteScalar<int>(sql, new
{
ProductID = productInCheque.ProductID,
Count = productInCheque.Count
}, transaction);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
_logger.LogError(ex, "Ошибка при добавлении товара в чек");
throw;
}
}
}
}
public ProductInCheque Read(int id)
{
_logger.LogInformation("Получение товара в чеке по ID");
_logger.LogDebug("ID товара в чеке: {id}", id);
using (var connection = CreateConnection())
{
try
{
var sql = "SELECT * FROM \"productincheque\" WHERE \"id\" = @ID";
var productInCheque = connection.QuerySingleOrDefault<ProductInCheque>(sql, new { ID = id });
if (productInCheque != null)
{
// Загрузка дополнительной информации о продукте при необходимости
var product = _productRepository.Read(productInCheque.ProductID);
productInCheque.ProductID = product?.ID ?? 0;
}
return productInCheque;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении товара в чеке");
throw;
}
}
}
public IEnumerable<ProductInCheque> ReadAll()
{
_logger.LogInformation("Получение всех товаров в чеках");
using (var connection = CreateConnection())
{
try
{
var sql = "SELECT * FROM \"productincheque\"";
var productsInCheque = connection.Query<ProductInCheque>(sql).ToList();
foreach (var productInCheque in productsInCheque)
{
var product = _productRepository.Read(productInCheque.ProductID);
productInCheque.ProductID = product?.ID ?? 0;
}
return productsInCheque;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении списка товаров в чеках");
throw;
}
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление товара из чека");
_logger.LogDebug("ID товара в чеке: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = "DELETE FROM \"productincheque\" WHERE \"id\" = @ID";
connection.Execute(sql, new { ID = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении товара из чека");
throw;
}
}
}
}

View File

@@ -1,33 +1,150 @@
using ProjectSellPC.Entites;
using ProjectSellPC.Entites.Enums;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System.Data;
using System.Linq.Expressions;
namespace ProjectSellPC.Repos.Impements
{
public class ProductRepo : IProductRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductRepo> _logger;
public ProductRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
{
_connectionString = connectionString;
//_logger = logger;
_logger = loggerFactory.CreateLogger<ProductRepo>();
}
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
public void Create(Product product)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using (var connection = CreateConnection())
{
var sql = "INSERT INTO \"product\" (\"name\", \"description\", \"price\", \"producttype\") " +
"VALUES (@Name, @Description, @Price, @ProductType)";
connection.Execute(sql, new
{
Name = product.Name,
Description = product.Description,
Price = product.Price,
ProductType = (int)product.ProductType
});
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = "DELETE FROM \"product\" WHERE \"id\" = @Id";
connection.Execute(sql, new { Id = id });
}
}
catch (Exception e)
{
_logger.LogError(e, "Ошибка при удалении объекта");
throw;
}
}
public Product Read(int id)
{
return Product.CreateEntity(0, string.Empty, string.Empty, 0, ProductType.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = $"SELECT * FROM \"product\" WHERE \"id\" = {id}";
return connection.QuerySingleOrDefault<Product>(sql);
}
}
catch (Exception e)
{
_logger.LogError(e, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Product> ReadAll()
{
return new List<Product>();
_logger.LogInformation("Получение всех объектов");
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"product\"";
return connection.Query<Product>(sql).ToList();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Product Update(Product product)
{
return Product.CreateEntity(0, string.Empty, string.Empty, 0, ProductType.None);
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using (var connection = CreateConnection())
{
var sql = "UPDATE \"product\" " +
"SET \"name\" = @Name, " +
"\"description\" = @Description, " +
"\"price\" = @Price," +
"\"producttype\" = @ProductType" +
" WHERE \"id\" = @Id";
connection.Execute(sql, new
{
Id = product.ID,
Name = product.Name,
Description = product.Description,
Price = product.Price,
ProductType = (int)product.ProductType
});
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при изменении объекта");
throw;
}
return product;
}
}
}

View File

@@ -1,27 +0,0 @@
using ProjectSellPC.Entites;
namespace ProjectSellPC.Repos.Impements
{
public class ProductsOnWarehouseRepo : IProductOnWarehouseRepository
{
public void Create(ProductsOnWarehouse ps)
{
}
public ProductsOnWarehouse Read(int id)
{
return ProductsOnWarehouse.CreateEntity(0, new Product(), new Warehouse(), 0);
}
public IEnumerable<ProductsOnWarehouse> ReadAll()
{
return new List<ProductsOnWarehouse>();
}
public ProductsOnWarehouse Update(ProductsOnWarehouse Warehouse)
{
return ProductsOnWarehouse.CreateEntity(0, new Product(), new Warehouse(), 0);
}
}
}

View File

@@ -0,0 +1,135 @@
using ProjectSellPC.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace ProjectSellPC.Repos.Impements
{
public class ProductsOnWarehouseRepo : IProductOnWarehouseRepository
{
private readonly IProductRepository _productRepository;
private readonly IWarehouseRepository _warehouseRepository;
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductsOnWarehouseRepo> _logger;
public ProductsOnWarehouseRepo(IConnectionString connectionString, ILoggerFactory loggerFactory,
IProductRepository productRepository,
IWarehouseRepository warehouseRepository)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<ProductsOnWarehouseRepo>();
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
_warehouseRepository = warehouseRepository ?? throw new ArgumentNullException(nameof(warehouseRepository));
}
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
public void Create(ProductsOnWarehouse productsOnWarehouse)
{
_logger.LogInformation("Добавление продукта на склад");
_logger.LogDebug("Продукт на складе: {json}", JsonConvert.SerializeObject(productsOnWarehouse));
using (var connection = CreateConnection())
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
try
{
var sql = "INSERT INTO \"productsonwarehouse\" (\"productid\", \"warehouseid\", \"count\") " +
"VALUES (@ProductId, @WarehouseId, @Count) RETURNING \"id\"";
productsOnWarehouse.Id = connection.ExecuteScalar<int>(sql, new
{
ProductId = productsOnWarehouse.Product.ID,
WarehouseId = productsOnWarehouse.Warehouse.Id,
Count = productsOnWarehouse.Count
}, transaction);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
_logger.LogError(ex, "Ошибка при добавлении продукта на склад");
throw;
}
}
}
}
public ProductsOnWarehouse Read(int id)
{
_logger.LogInformation("Получение продукта на складе по ID");
_logger.LogDebug("ID продукта на складе: {id}", id);
using (var connection = CreateConnection())
{
try
{
var sql = "SELECT * FROM \"productsonwarehouse\" WHERE \"id\" = @Id";
var productOnWarehouse = connection.QuerySingleOrDefault<ProductsOnWarehouse>(sql, new { Id = id });
productOnWarehouse.Warehouse = _warehouseRepository.Read(productOnWarehouse.WarehouseId);
productOnWarehouse.Product = _productRepository.Read(productOnWarehouse.ProductId);
return productOnWarehouse;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении продукта на складе");
throw;
}
}
}
public IEnumerable<ProductsOnWarehouse> ReadAll()
{
_logger.LogInformation("Получение всех продуктов на складе");
using (var connection = CreateConnection())
{
try
{
var sql = "SELECT * FROM \"productsonwarehouse\"";
var answer = connection.Query<ProductsOnWarehouse>(sql).ToList();
foreach (var productOnWarehouse in answer)
{
productOnWarehouse.Product = _productRepository.Read(productOnWarehouse.ProductId);
productOnWarehouse.Warehouse = _warehouseRepository.Read(productOnWarehouse.WarehouseId);
}
return answer;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении списка продуктов на складе");
throw;
}
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление товара со склада");
_logger.LogDebug("Склад ID: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = "DELETE FROM \"productsonwarehouse\" WHERE \"id\" = @Id";
connection.Execute(sql, new { Id = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении");
throw;
}
}
}
}

View File

@@ -1,32 +0,0 @@
using ProjectSellPC.Entites;
namespace ProjectSellPC.Repos.Impements
{
public class WarehouseRepo: IWarehouseRepository
{
public void Create(Warehouse Warehouse)
{
}
public void Delete(int id)
{
}
public Warehouse Read(int id)
{
return Warehouse.CreateEntity(0, 0, string.Empty);
}
public IEnumerable<Warehouse> ReadAll()
{
return new List<Warehouse>();
}
public Warehouse Update(Warehouse Warehouse)
{
return Warehouse.CreateEntity(0, 0, string.Empty);
}
}
}

View File

@@ -0,0 +1,140 @@
using ProjectSellPC.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace ProjectSellPC.Repos.Impements
{
public class WarehouseRepo: IWarehouseRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<WarehouseRepo> _logger;
public WarehouseRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<WarehouseRepo>();
}
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
public void Create(Warehouse warehouse)
{
_logger.LogInformation("Добавление склада");
_logger.LogDebug("Склад: {json}", JsonConvert.SerializeObject(warehouse));
try
{
using (var connection = CreateConnection())
{
var sql = "INSERT INTO \"warehouse\" (\"size\", \"adress\") " +
"VALUES (@Size, @Adress)";
connection.Execute(sql, new
{
Size = warehouse.Size,
Adress = warehouse.Adress
});
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении склада");
throw;
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление склада");
_logger.LogDebug("Склад ID: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = "DELETE FROM \"warehouse\" WHERE \"id\" = @Id";
connection.Execute(sql, new { Id = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении склада");
throw;
}
}
public Warehouse Read(int id)
{
_logger.LogInformation("Получение склада по ID");
_logger.LogDebug("Склад ID: {id}", id);
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"warehouse\" WHERE \"id\" = @Id";
return connection.QuerySingleOrDefault<Warehouse>(sql, new { Id = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении склада");
throw;
}
}
public IEnumerable<Warehouse> ReadAll()
{
_logger.LogInformation("Получение всех складов");
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"warehouse\"";
return connection.Query<Warehouse>(sql).ToList();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении списка складов");
throw;
}
}
public Warehouse Update(Warehouse warehouse)
{
_logger.LogInformation("Обновление информации о складе");
_logger.LogDebug("Склад: {json}", JsonConvert.SerializeObject(warehouse));
try
{
using (var connection = CreateConnection())
{
var sql = "UPDATE \"warehouse\" SET \"size\" = @Size, \"adress\" = @Adress " +
"WHERE \"id\" = @Id";
connection.Execute(sql, new
{
Id = warehouse.Id,
Size = warehouse.Size,
Adress = warehouse.Adress
});
return warehouse;
}
}
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/log.txt",
"rollingInterval": "Day"
}
}
]
}
}