lab2 final

This commit is contained in:
2025-12-07 18:25:06 +04:00
parent 3049ea01bc
commit 6cf0f868c0
19 changed files with 1147 additions and 324 deletions

View File

@@ -4,18 +4,18 @@ public class Parts
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int CategoryId { get; set; }
public decimal Price { get; set; }
public int WarrantyMonths { get; set; }
public PartFlags Flags { get; set; } = PartFlags.None;
public static Parts CreateEntity(int id, string name, decimal price, int warranty, PartFlags flags = PartFlags.None)
public static Parts CreateEntity(int id, string name, int categoryId, decimal price, int warranty, PartFlags flags = PartFlags.None)
{
return new Parts
{
Id = id,
Name = name,
CategoryId = categoryId,
Price = price,
WarrantyMonths = warranty,
Flags = flags

View File

@@ -3,18 +3,12 @@
public class Sales
{
public int Id { get; private set; }
public int? AssemblyId { get; private set; }
public int? PartId { get; private set; }
public int? DeviceId { get; private set; }
public DateTime SaleDate { get; private set; }
public decimal TotalAmount { get; private set; }
public string SaleType { get; private set; }
public static Sales CreateEntity(
int id,
int? assemblyId,
int? partId,
int? deviceId,
DateTime saleDate,
decimal totalAmount,
string saleType)
@@ -22,9 +16,6 @@
return new Sales
{
Id = id,
AssemblyId = assemblyId,
PartId = partId,
DeviceId = deviceId,
SaleDate = saleDate,
TotalAmount = totalAmount,
SaleType = saleType

View File

@@ -1,4 +1,6 @@
namespace ProjectComputerShop.Forms
using System.Windows.Forms;
namespace ProjectComputerShop.Forms
{
partial class FormAssembly
{
@@ -6,7 +8,10 @@
protected override void Dispose(bool disposing)
{
if (disposing && components != null) components.Dispose();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
@@ -24,103 +29,81 @@
comboBoxStatus = new ComboBox();
groupBoxParts = new GroupBox();
dataGridViewParts = new DataGridView();
buttonSave = new Button();
buttonCancel = new Button();
partColumn = new DataGridViewComboBoxColumn();
qtyColumn = new DataGridViewTextBoxColumn();
buttonSave = new Button();
buttonCancel = new Button();
((System.ComponentModel.ISupportInitialize)numericCostPrice).BeginInit();
((System.ComponentModel.ISupportInitialize)numericSellingPrice).BeginInit();
groupBoxParts.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewParts).BeginInit();
SuspendLayout();
//
// labelNumber
//
labelNumber.AutoSize = true;
labelNumber.Location = new Point(25, 20);
labelNumber.Name = "labelNumber";
labelNumber.Size = new Size(114, 20);
labelNumber.TabIndex = 0;
labelNumber.Text = "Номер сборки:";
//
// textBoxNumber
//
textBoxNumber.Location = new Point(149, 17);
textBoxNumber.Name = "textBoxNumber";
textBoxNumber.Size = new Size(220, 27);
textBoxNumber.TabIndex = 1;
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(380, 20);
labelDate.Name = "labelDate";
labelDate.Size = new Size(98, 20);
labelDate.TabIndex = 2;
labelDate.Text = "Дата сборки:";
//
// dateTimePickerAssembly
//
dateTimePickerAssembly.Format = DateTimePickerFormat.Short;
dateTimePickerAssembly.Location = new Point(535, 15);
dateTimePickerAssembly.Name = "dateTimePickerAssembly";
dateTimePickerAssembly.Size = new Size(150, 27);
dateTimePickerAssembly.TabIndex = 3;
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Location = new Point(25, 60);
labelCost.Name = "labelCost";
labelCost.Size = new Size(118, 20);
labelCost.TabIndex = 4;
labelCost.Text = "Себестоимость:";
//
// numericCostPrice
//
numericCostPrice.DecimalPlaces = 2;
numericCostPrice.Location = new Point(149, 58);
numericCostPrice.Name = "numericCostPrice";
numericCostPrice.Size = new Size(120, 27);
numericCostPrice.TabIndex = 5;
numericCostPrice.ThousandsSeparator = true;
//
// labelPrice
//
labelPrice.AutoSize = true;
labelPrice.Location = new Point(380, 60);
labelPrice.Name = "labelPrice";
labelPrice.Size = new Size(115, 20);
labelPrice.TabIndex = 6;
labelPrice.Text = "Цена продажи:";
//
// numericSellingPrice
//
numericSellingPrice.DecimalPlaces = 2;
numericSellingPrice.Location = new Point(535, 60);
numericSellingPrice.Name = "numericSellingPrice";
numericSellingPrice.Size = new Size(120, 27);
numericSellingPrice.TabIndex = 7;
numericSellingPrice.ThousandsSeparator = true;
//
// labelStatus
//
labelStatus.AutoSize = true;
labelStatus.Location = new Point(25, 100);
labelStatus.Name = "labelStatus";
labelStatus.Size = new Size(55, 20);
labelStatus.TabIndex = 8;
labelStatus.Text = "Статус:";
//
// comboBoxStatus
//
comboBoxStatus.Location = new Point(149, 97);
comboBoxStatus.Name = "comboBoxStatus";
comboBoxStatus.Size = new Size(220, 28);
comboBoxStatus.TabIndex = 9;
//
// groupBoxParts
//
groupBoxParts.Controls.Add(dataGridViewParts);
groupBoxParts.Location = new Point(229, 156);
groupBoxParts.Name = "groupBoxParts";
@@ -128,9 +111,7 @@
groupBoxParts.TabIndex = 10;
groupBoxParts.TabStop = false;
groupBoxParts.Text = "Комплектующие в сборке";
//
// dataGridViewParts
//
dataGridViewParts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewParts.Columns.AddRange(new DataGridViewColumn[] { partColumn, qtyColumn });
dataGridViewParts.Dock = DockStyle.Fill;
@@ -141,61 +122,50 @@
dataGridViewParts.Size = new Size(313, 199);
dataGridViewParts.TabIndex = 0;
dataGridViewParts.DefaultValuesNeeded += dataGridViewParts_DefaultValuesNeeded;
//
// buttonSave
//
partColumn.HeaderText = "Комплектующее";
partColumn.MinimumWidth = 6;
partColumn.Name = "partColumn";
partColumn.Width = 125;
qtyColumn.HeaderText = "Количество";
qtyColumn.MinimumWidth = 6;
qtyColumn.Name = "qtyColumn";
qtyColumn.Width = 125;
buttonSave.Location = new Point(149, 430);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(100, 35);
buttonSave.TabIndex = 11;
buttonSave.Text = "Сохранить";
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonSave.UseVisualStyleBackColor = true;
buttonCancel.Location = new Point(504, 430);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(100, 35);
buttonCancel.TabIndex = 12;
buttonCancel.Text = "Отмена";
buttonCancel.Click += buttonCancel_Click;
//
// partColumn
//
partColumn.HeaderText = "Комплектующее";
partColumn.MinimumWidth = 6;
partColumn.Name = "partColumn";
partColumn.Width = 125;
//
// qtyColumn
//
qtyColumn.HeaderText = "Количество";
qtyColumn.MinimumWidth = 6;
qtyColumn.Name = "qtyColumn";
qtyColumn.Width = 125;
//
// FormAssembly
//
buttonCancel.UseVisualStyleBackColor = true;
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(776, 505);
Controls.Add(labelNumber);
Controls.Add(textBoxNumber);
Controls.Add(labelDate);
Controls.Add(dateTimePickerAssembly);
Controls.Add(labelCost);
Controls.Add(numericCostPrice);
Controls.Add(labelPrice);
Controls.Add(numericSellingPrice);
Controls.Add(labelStatus);
Controls.Add(comboBoxStatus);
Controls.Add(groupBoxParts);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = false;
Controls.Add(buttonSave);
Controls.Add(groupBoxParts);
Controls.Add(comboBoxStatus);
Controls.Add(labelStatus);
Controls.Add(numericSellingPrice);
Controls.Add(labelPrice);
Controls.Add(numericCostPrice);
Controls.Add(labelCost);
Controls.Add(dateTimePickerAssembly);
Controls.Add(labelDate);
Controls.Add(textBoxNumber);
Controls.Add(labelNumber);
Name = "FormAssembly";
StartPosition = FormStartPosition.CenterParent;
Text = "Редактирование сборки";
Load += FormAssembly_Load;
((System.ComponentModel.ISupportInitialize)numericCostPrice).EndInit();
((System.ComponentModel.ISupportInitialize)numericSellingPrice).EndInit();
groupBoxParts.ResumeLayout(false);

View File

@@ -1,7 +1,6 @@
using System;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using ComputerShop.Entities;
using ComputerShop.Enums;
using ComputerShop.Repositories;
@@ -18,72 +17,96 @@ namespace ProjectComputerShop.Forms
{
set
{
var assembly = _assembliesRepository.ReadAll().FirstOrDefault(a => a.Id == value);
if (assembly == null) return;
try
{
var assembly = _assembliesRepository.ReadById(value);
if (assembly == null)
throw new InvalidDataException(nameof(assembly));
textBoxNumber.Text = assembly.AssemblyNumber;
dateTimePickerAssembly.Value = assembly.AssemblyDate;
numericCostPrice.Value = assembly.CostPrice;
numericSellingPrice.Value = assembly.SellingPrice;
comboBoxStatus.SelectedValue = assembly.Status;
_assemblyId = value;
textBoxNumber.Text = assembly.AssemblyNumber;
dateTimePickerAssembly.Value = assembly.AssemblyDate;
numericCostPrice.Value = assembly.CostPrice;
numericSellingPrice.Value = assembly.SellingPrice;
comboBoxStatus.SelectedValue = assembly.Status;
_assemblyId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при получении данных",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
}
public FormAssembly(IAssembliesRepository assembliesRepository, IPartsRepository partsRepository)
{
InitializeComponent();
_assembliesRepository = assembliesRepository;
_partsRepository = partsRepository;
_assembliesRepository = assembliesRepository ??
throw new ArgumentNullException(nameof(assembliesRepository));
_partsRepository = partsRepository ??
throw new ArgumentNullException(nameof(partsRepository));
comboBoxStatus.DataSource = Enum.GetValues(typeof(AssemblyStatus));
comboBoxStatus.DropDownStyle = ComboBoxStyle.DropDownList;
dateTimePickerAssembly.Value = DateTime.Today;
LoadPartsComboBox();
buttonSave.Click += buttonSave_Click;
buttonCancel.Click += buttonCancel_Click;
}
private void FormAssembly_Load(object sender, EventArgs e)
private void LoadPartsComboBox()
{
var parts = _partsRepository.ReadAll().Select(p => p.Name).ToList();
((DataGridViewComboBoxColumn)dataGridViewParts.Columns["PartColumn"]).DataSource = parts;
partColumn.DataSource = parts;
}
private void dataGridViewParts_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
e.Row.Cells["QuantityColumn"].Value = 1;
e.Row.Cells["qtyColumn"].Value = 1;
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBoxNumber.Text))
try
{
MessageBox.Show("Введите номер сборки.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (string.IsNullOrWhiteSpace(textBoxNumber.Text))
throw new Exception("Имеются незаполненные поля");
var assembly = Assemblies.CreateEntity(
id: _assemblyId ?? 0,
var assembly = CreateAssembly(_assemblyId ?? 0);
if (_assemblyId.HasValue)
_assembliesRepository.Update(assembly);
else
_assembliesRepository.Create(assembly);
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при сохранении",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Assemblies CreateAssembly(int id)
{
return Assemblies.CreateEntity(
id: id,
assemblyNumber: textBoxNumber.Text.Trim(),
assemblyDate: dateTimePickerAssembly.Value.Date,
costPrice: numericCostPrice.Value,
sellingPrice: numericSellingPrice.Value,
status: (AssemblyStatus)comboBoxStatus.SelectedValue
);
if (_assemblyId.HasValue)
_assembliesRepository.Update(assembly);
else
_assembliesRepository.Create(assembly);
DialogResult = DialogResult.OK;
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@@ -1,37 +1,78 @@
using System;
using System.Windows.Forms;
using ComputerShop.Repositories;
using ProjectComputerShop.Entities;
using ProjectComputerShop.Repositories;
namespace ProjectComputerShop.Forms
{
public partial class FormCategory : Form
{
public string CategoryName { get; private set; } = string.Empty;
public int Id { get; internal set; }
private readonly ICategoriesRepository _categoriesRepository;
private int? _categoryId;
public FormCategory()
public int Id
{
set
{
try
{
var category = _categoriesRepository.ReadById(value);
if (category == null)
throw new InvalidDataException(nameof(category));
_categoryId = category.Id;
textBoxCategory.Text = category.CategoryName;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при получении данных",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
}
public FormCategory(ICategoriesRepository repository)
{
InitializeComponent();
_categoriesRepository = repository ??
throw new ArgumentNullException(nameof(repository));
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBoxCategory.Text))
try
{
MessageBox.Show("Введите название категории!", "Внимание",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (string.IsNullOrWhiteSpace(textBoxCategory.Text))
throw new Exception("Имеются незаполненные поля");
CategoryName = textBoxCategory.Text.Trim();
this.DialogResult = DialogResult.OK;
this.Close();
if (_categoryId.HasValue)
_categoriesRepository.Update(CreateCategory(_categoryId.Value));
else
_categoriesRepository.Create(CreateCategory(0));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при сохранении",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Categories CreateCategory(int id)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
return Categories.CreateEntity(
id,
textBoxCategory.Text.Trim()
);
}
}
}

View File

@@ -1,7 +1,8 @@
using ComputerShop.Entities;
using System;
using System.Windows.Forms;
using ComputerShop.Entities;
using ComputerShop.Repositories;
namespace ProjectComputerShop.Forms
{
public partial class FormDevice : Form
@@ -43,11 +44,24 @@ namespace ProjectComputerShop.Forms
_devicesRepository = devicesRepository ?? throw new ArgumentNullException(nameof(devicesRepository));
_categoriesRepository = categoriesRepository ?? throw new ArgumentNullException(nameof(categoriesRepository));
var categories = _categoriesRepository.ReadAll();
comboBoxCategory.DataSource = categories;
comboBoxCategory.DisplayMember = "Name";
comboBoxCategory.ValueMember = "Id";
LoadCategories();
}
private void LoadCategories()
{
try
{
var categories = _categoriesRepository.ReadAll();
comboBoxCategory.DataSource = categories;
comboBoxCategory.DisplayMember = "CategoryName";
comboBoxCategory.ValueMember = "Id";
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при загрузке категорий: {ex.Message}", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
@@ -60,6 +74,22 @@ namespace ProjectComputerShop.Forms
{
throw new Exception("Имеются незаполненные поля");
}
if (numericUpDownRetPrice.Value <= 0)
{
throw new Exception("Розничная цена должна быть больше 0");
}
if (numericUpDownStock.Value < 0)
{
throw new Exception("Остаток не может быть отрицательным");
}
if (comboBoxCategory.SelectedValue == null)
{
throw new Exception("Выберите категорию");
}
if (_deviceId.HasValue)
{
_devicesRepository.Update(CreateDevice(_deviceId.Value));
@@ -81,12 +111,12 @@ namespace ProjectComputerShop.Forms
private Devices CreateDevice(int id) => Devices.CreateEntity(
id,
textBoxModel.Text,
textBoxBrand.Text,
textBoxModel.Text.Trim(),
textBoxBrand.Text.Trim(),
(int)comboBoxCategory.SelectedValue,
numericUpDownRetPrice.Value,
(int)numericUpDownStock.Value,
textBoxSerNum.Text
textBoxSerNum.Text.Trim()
);
}
}
}

View File

@@ -1,4 +1,7 @@
namespace ProjectComputerShop.Forms
using static System.Net.Mime.MediaTypeNames;
using System.Windows.Forms;
namespace ProjectComputerShop.Forms
{
partial class FormDevices
{

View File

@@ -2,23 +2,32 @@
{
partial class FormPart
{
private System.ComponentModel.IContainer _components = null;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && this._components != null) _components.Dispose();
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
InitializeComponent(checkRGB);
}
private void InitializeComponent(CheckBox checkRGB)
{
_components = new System.ComponentModel.Container();
labelName = new Label();
textBoxName = new TextBox();
labelCategory = new Label();
@@ -27,95 +36,302 @@
numericPrice = new NumericUpDown();
labelWarranty = new Label();
numericWarranty = new NumericUpDown();
groupBoxFlags = new GroupBox();
checkRGB = new CheckBox();
checkLiquid = new CheckBox();
checkOC = new CheckBox();
checkModular = new CheckBox();
checkNVMe = new CheckBox();
checkWiFi = new CheckBox();
checkBluetooth = new CheckBox();
checkTouch = new CheckBox();
checkBacklit = new CheckBox();
checkMechanical = new CheckBox();
checkBacklit = new CheckBox();
checkTouch = new CheckBox();
checkBluetooth = new CheckBox();
checkWiFi = new CheckBox();
checkNVMe = new CheckBox();
checkModular = new CheckBox();
checkOC = new CheckBox();
checkLiquid = new CheckBox();
checkRGB = new CheckBox();
buttonSave = new Button();
buttonCancel = new Button();
((System.ComponentModel.ISupportInitialize)numericPrice).BeginInit();
((System.ComponentModel.ISupportInitialize)numericWarranty).BeginInit();
groupBoxFlags.SuspendLayout();
SuspendLayout();
labelName.Location = new Point(20, 20); labelName.Text = "Наименование:"; labelName.AutoSize = true;
textBoxName.Location = new Point(140, 17); textBoxName.Size = new Size(300, 23);
labelCategory.Location = new Point(20, 60); labelCategory.Text = "Категория:"; labelCategory.AutoSize = true;
comboBoxCategory.Location = new Point(140, 57); comboBoxCategory.Size = new Size(300, 23);
labelPrice.Location = new Point(20, 100); labelPrice.Text = "Цена:"; labelPrice.AutoSize = true;
numericPrice.Location = new Point(140, 97); numericPrice.Size = new Size(120, 23);
numericPrice.DecimalPlaces = 2; numericPrice.ThousandsSeparator = true;
labelWarranty.Location = new Point(280, 100); labelWarranty.Text = "Гарантия (мес):"; labelWarranty.AutoSize = true;
numericWarranty.Location = new Point(400, 97); numericWarranty.Size = new Size(80, 23);
numericWarranty.Maximum = 120;
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(23, 27);
labelName.Name = "labelName";
labelName.Size = new Size(119, 20);
labelName.TabIndex = 0;
labelName.Text = "Наименование:";
//
// textBoxName
//
textBoxName.Location = new Point(160, 23);
textBoxName.Margin = new Padding(3, 4, 3, 4);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(342, 27);
textBoxName.TabIndex = 1;
//
// labelCategory
//
labelCategory.AutoSize = true;
labelCategory.Location = new Point(23, 80);
labelCategory.Name = "labelCategory";
labelCategory.Size = new Size(84, 20);
labelCategory.TabIndex = 2;
labelCategory.Text = "Категория:";
//
// comboBoxCategory
//
comboBoxCategory.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxCategory.FormattingEnabled = true;
comboBoxCategory.Location = new Point(160, 76);
comboBoxCategory.Margin = new Padding(3, 4, 3, 4);
comboBoxCategory.Name = "comboBoxCategory";
comboBoxCategory.Size = new Size(342, 28);
comboBoxCategory.TabIndex = 3;
//
// labelPrice
//
labelPrice.AutoSize = true;
labelPrice.Location = new Point(23, 133);
labelPrice.Name = "labelPrice";
labelPrice.Size = new Size(48, 20);
labelPrice.TabIndex = 4;
labelPrice.Text = "Цена:";
//
// numericPrice
//
numericPrice.DecimalPlaces = 2;
numericPrice.Location = new Point(160, 129);
numericPrice.Margin = new Padding(3, 4, 3, 4);
numericPrice.Maximum = new decimal(new int[] { 999999, 0, 0, 0 });
numericPrice.Name = "numericPrice";
numericPrice.Size = new Size(137, 27);
numericPrice.TabIndex = 5;
numericPrice.ThousandsSeparator = true;
//
// labelWarranty
//
labelWarranty.AutoSize = true;
labelWarranty.Location = new Point(320, 133);
labelWarranty.Name = "labelWarranty";
labelWarranty.Size = new Size(116, 20);
labelWarranty.TabIndex = 6;
labelWarranty.Text = "Гарантия (мес):";
//
// numericWarranty
//
numericWarranty.Location = new Point(457, 129);
numericWarranty.Margin = new Padding(3, 4, 3, 4);
numericWarranty.Maximum = new decimal(new int[] { 120, 0, 0, 0 });
numericWarranty.Name = "numericWarranty";
numericWarranty.Size = new Size(91, 27);
numericWarranty.TabIndex = 7;
//
// groupBoxFlags
//
groupBoxFlags.Controls.Add(checkMechanical);
groupBoxFlags.Controls.Add(checkBacklit);
groupBoxFlags.Controls.Add(checkTouch);
groupBoxFlags.Controls.Add(checkBluetooth);
groupBoxFlags.Controls.Add(checkWiFi);
groupBoxFlags.Controls.Add(checkNVMe);
groupBoxFlags.Controls.Add(checkModular);
groupBoxFlags.Controls.Add(checkOC);
groupBoxFlags.Controls.Add(checkLiquid);
groupBoxFlags.Controls.Add(checkRGB);
groupBoxFlags.Location = new Point(23, 187);
groupBoxFlags.Margin = new Padding(3, 4, 3, 4);
groupBoxFlags.Name = "groupBoxFlags";
groupBoxFlags.Padding = new Padding(3, 4, 3, 4);
groupBoxFlags.Size = new Size(526, 240);
groupBoxFlags.TabIndex = 8;
groupBoxFlags.TabStop = false;
groupBoxFlags.Text = "Дополнительные характеристики";
groupBoxFlags.Location = new Point(20, 140);
groupBoxFlags.Size = new Size(460, 180);
groupBoxFlags.Controls.AddRange(new Control[] {
checkRGB, checkLiquid, checkOC, checkModular, checkNVMe,
checkWiFi, checkBluetooth, checkTouch, checkBacklit, checkMechanical
});
int y = 20;
checkRGB.Text = "RGB-подсветка"; checkRGB.Location = new Point(10, y); y += 25;
checkLiquid.Text = "Жидкостное охлаждение"; checkLiquid.Location = new Point(10, y); y += 25;
checkOC.Text = "Поддержка разгона"; checkOC.Location = new Point(10, y); y += 25;
checkModular.Text = "Модульный"; checkModular.Location = new Point(10, y); y += 25;
checkNVMe.Text = "NVMe"; checkNVMe.Location = new Point(10, y); y += 25;
checkWiFi.Text = "Wi-Fi"; checkWiFi.Location = new Point(200, 20);
checkBluetooth.Text = "Bluetooth"; checkBluetooth.Location = new Point(200, 45);
checkTouch.Text = "Сенсорный экран"; checkTouch.Location = new Point(200, 70);
checkBacklit.Text = "Подсветка клавиатуры"; checkBacklit.Location = new Point(200, 95);
checkMechanical.Text = "Механическая клавиатура"; checkMechanical.Location = new Point(200, 120);
buttonSave.Location = new Point(240, 340); buttonSave.Size = new Size(100, 35); buttonSave.Text = "Сохранить";
buttonSave.Click += buttonSave_Click;
buttonCancel.Location = new Point(360, 340); buttonCancel.Size = new Size(100, 35); buttonCancel.Text = "Отмена";
buttonCancel.Click += buttonCancel_Click;
ClientSize = new Size(510, 390);
Controls.AddRange(new Control[] {
labelName, textBoxName, labelCategory, comboBoxCategory,
labelPrice, numericPrice, labelWarranty, numericWarranty,
groupBoxFlags, buttonSave, buttonCancel
});
Text = "Редактирование комплектующего";
StartPosition = FormStartPosition.CenterParent;
//
// checkMechanical
//
checkMechanical.AutoSize = true;
checkMechanical.Location = new Point(229, 160);
checkMechanical.Margin = new Padding(3, 4, 3, 4);
checkMechanical.Name = "checkMechanical";
checkMechanical.Size = new Size(213, 24);
checkMechanical.TabIndex = 9;
checkMechanical.Text = "Механическая клавиатура";
checkMechanical.UseVisualStyleBackColor = true;
//
// checkBacklit
//
checkBacklit.AutoSize = true;
checkBacklit.Location = new Point(229, 127);
checkBacklit.Margin = new Padding(3, 4, 3, 4);
checkBacklit.Name = "checkBacklit";
checkBacklit.Size = new Size(188, 24);
checkBacklit.TabIndex = 8;
checkBacklit.Text = "Подсветка клавиатуры";
checkBacklit.UseVisualStyleBackColor = true;
//
// checkTouch
//
checkTouch.AutoSize = true;
checkTouch.Location = new Point(229, 93);
checkTouch.Margin = new Padding(3, 4, 3, 4);
checkTouch.Name = "checkTouch";
checkTouch.Size = new Size(155, 24);
checkTouch.TabIndex = 7;
checkTouch.Text = "Сенсорный экран";
checkTouch.UseVisualStyleBackColor = true;
//
// checkBluetooth
//
checkBluetooth.AutoSize = true;
checkBluetooth.Location = new Point(229, 60);
checkBluetooth.Margin = new Padding(3, 4, 3, 4);
checkBluetooth.Name = "checkBluetooth";
checkBluetooth.Size = new Size(96, 24);
checkBluetooth.TabIndex = 6;
checkBluetooth.Text = "Bluetooth";
checkBluetooth.UseVisualStyleBackColor = true;
//
// checkWiFi
//
checkWiFi.AutoSize = true;
checkWiFi.Location = new Point(229, 27);
checkWiFi.Margin = new Padding(3, 4, 3, 4);
checkWiFi.Name = "checkWiFi";
checkWiFi.Size = new Size(66, 24);
checkWiFi.TabIndex = 5;
checkWiFi.Text = "Wi-Fi";
checkWiFi.UseVisualStyleBackColor = true;
//
// checkNVMe
//
checkNVMe.AutoSize = true;
checkNVMe.Location = new Point(11, 160);
checkNVMe.Margin = new Padding(3, 4, 3, 4);
checkNVMe.Name = "checkNVMe";
checkNVMe.Size = new Size(72, 24);
checkNVMe.TabIndex = 4;
checkNVMe.Text = "NVMe";
checkNVMe.UseVisualStyleBackColor = true;
//
// checkModular
//
checkModular.AutoSize = true;
checkModular.Location = new Point(11, 127);
checkModular.Margin = new Padding(3, 4, 3, 4);
checkModular.Name = "checkModular";
checkModular.Size = new Size(113, 24);
checkModular.TabIndex = 3;
checkModular.Text = "Модульный";
checkModular.UseVisualStyleBackColor = true;
//
// checkOC
//
checkOC.AutoSize = true;
checkOC.Location = new Point(11, 93);
checkOC.Margin = new Padding(3, 4, 3, 4);
checkOC.Name = "checkOC";
checkOC.Size = new Size(170, 24);
checkOC.TabIndex = 2;
checkOC.Text = "Поддержка разгона";
checkOC.UseVisualStyleBackColor = true;
//
// checkLiquid
//
checkLiquid.AutoSize = true;
checkLiquid.Location = new Point(11, 60);
checkLiquid.Margin = new Padding(3, 4, 3, 4);
checkLiquid.Name = "checkLiquid";
checkLiquid.Size = new Size(205, 24);
checkLiquid.TabIndex = 1;
checkLiquid.Text = "Жидкостное охлаждение";
checkLiquid.UseVisualStyleBackColor = true;
//
// checkRGB
//
checkRGB.AutoSize = true;
checkRGB.Location = new Point(11, 27);
checkRGB.Margin = new Padding(3, 4, 3, 4);
checkRGB.Name = "checkRGB";
checkRGB.Size = new Size(135, 24);
checkRGB.TabIndex = 0;
checkRGB.Text = "RGB-подсветка";
checkRGB.UseVisualStyleBackColor = true;
//
// buttonSave
//
buttonSave.Location = new Point(286, 440);
buttonSave.Margin = new Padding(3, 4, 3, 4);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(114, 40);
buttonSave.TabIndex = 9;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
//
// buttonCancel
//
buttonCancel.Location = new Point(411, 440);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(114, 40);
buttonCancel.TabIndex = 10;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// FormPart
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(591, 508);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(groupBoxFlags);
Controls.Add(numericWarranty);
Controls.Add(labelWarranty);
Controls.Add(numericPrice);
Controls.Add(labelPrice);
Controls.Add(comboBoxCategory);
Controls.Add(labelCategory);
Controls.Add(textBoxName);
Controls.Add(labelName);
FormBorderStyle = FormBorderStyle.FixedDialog;
Margin = new Padding(3, 4, 3, 4);
MaximizeBox = false;
MinimizeBox = false;
Name = "FormPart";
StartPosition = FormStartPosition.CenterParent;
Text = "Редактирование комплектующего";
((System.ComponentModel.ISupportInitialize)numericPrice).EndInit();
((System.ComponentModel.ISupportInitialize)numericWarranty).EndInit();
groupBoxFlags.ResumeLayout(false);
groupBoxFlags.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
private Label labelName, labelCategory, labelPrice, labelWarranty;
private TextBox textBoxName;
private ComboBox comboBoxCategory;
private NumericUpDown numericPrice, numericWarranty;
#endregion
private GroupBox groupBoxFlags;
private CheckBox checkRGB, checkLiquid, checkOC, checkModular, checkNVMe;
private CheckBox checkWiFi, checkBluetooth, checkTouch, checkBacklit, checkMechanical;
private Button buttonSave, buttonCancel;
private System.Windows.Forms.Label labelName;
private System.Windows.Forms.TextBox textBoxName;
private System.Windows.Forms.Label labelCategory;
private System.Windows.Forms.ComboBox comboBoxCategory;
private System.Windows.Forms.Label labelPrice;
private System.Windows.Forms.NumericUpDown numericPrice;
private System.Windows.Forms.Label labelWarranty;
private System.Windows.Forms.NumericUpDown numericWarranty;
private System.Windows.Forms.GroupBox groupBoxFlags;
private System.Windows.Forms.CheckBox checkMechanical;
private System.Windows.Forms.CheckBox checkBacklit;
private System.Windows.Forms.CheckBox checkTouch;
private System.Windows.Forms.CheckBox checkBluetooth;
private System.Windows.Forms.CheckBox checkWiFi;
private System.Windows.Forms.CheckBox checkNVMe;
private System.Windows.Forms.CheckBox checkModular;
private System.Windows.Forms.CheckBox checkOC;
private System.Windows.Forms.CheckBox checkLiquid;
private System.Windows.Forms.CheckBox checkRGB;
private System.Windows.Forms.Button buttonSave;
private System.Windows.Forms.Button buttonCancel;
}
}

View File

@@ -1,4 +1,7 @@
using ComputerShop.Enums;
using System;
using System.Windows.Forms;
using ComputerShop.Entities;
using ComputerShop.Enums;
using ComputerShop.Repositories;
namespace ProjectComputerShop.Forms
@@ -6,53 +9,120 @@ namespace ProjectComputerShop.Forms
public partial class FormPart : Form
{
private readonly IPartsRepository _repository;
private readonly ICategoriesRepository _categoriesRepository; // добавил
private int? _partId;
public int Id
{
set
{
var part = _repository.ReadAll().FirstOrDefault(p => p.Id == value);
if (part == null) return;
try
{
var part = _repository.ReadById(value);
if (part == null)
throw new InvalidDataException(nameof(part));
textBoxName.Text = part.Name;
;
textBoxName.Text = part.Name;
numericPrice.Value = part.Price;
numericWarranty.Value = part.WarrantyMonths;
comboBoxCategory.SelectedValue = part.CategoryId;
numericPrice.Value = part.Price;
numericWarranty.Value = part.WarrantyMonths;
checkRGB.Checked = (part.Flags & PartFlags.RGB) != 0;
checkLiquid.Checked = (part.Flags & PartFlags.LiquidCooling) != 0;
checkOC.Checked = (part.Flags & PartFlags.Overclockable) != 0;
checkModular.Checked = (part.Flags & PartFlags.Modular) != 0;
checkNVMe.Checked = (part.Flags & PartFlags.NVMe) != 0;
checkWiFi.Checked = (part.Flags & PartFlags.WiFi) != 0;
checkBluetooth.Checked = (part.Flags & PartFlags.Bluetooth) != 0;
checkTouch.Checked = (part.Flags & PartFlags.TouchScreen) != 0;
checkBacklit.Checked = (part.Flags & PartFlags.BacklitKeyboard) != 0;
checkMechanical.Checked = (part.Flags & PartFlags.MechanicalKeyboard) != 0;
checkRGB.Checked = (part.Flags & PartFlags.RGB) != 0;
checkLiquid.Checked = (part.Flags & PartFlags.LiquidCooling) != 0;
checkOC.Checked = (part.Flags & PartFlags.Overclockable) != 0;
checkModular.Checked = (part.Flags & PartFlags.Modular) != 0;
checkNVMe.Checked = (part.Flags & PartFlags.NVMe) != 0;
checkWiFi.Checked = (part.Flags & PartFlags.WiFi) != 0;
checkBluetooth.Checked = (part.Flags & PartFlags.Bluetooth) != 0;
checkTouch.Checked = (part.Flags & PartFlags.TouchScreen) != 0;
checkBacklit.Checked = (part.Flags & PartFlags.BacklitKeyboard) != 0;
checkMechanical.Checked = (part.Flags & PartFlags.MechanicalKeyboard) != 0;
_partId = value;
_partId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при получении данных",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
}
public FormPart(IPartsRepository repository)
public FormPart(IPartsRepository repository, ICategoriesRepository categoriesRepository)
{
InitializeComponent();
_repository = repository;
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_categoriesRepository = categoriesRepository ?? throw new ArgumentNullException(nameof(categoriesRepository));
LoadCategories();
buttonSave.Click += buttonSave_Click;
buttonCancel.Click += buttonCancel_Click;
comboBoxCategory.DropDownStyle = ComboBoxStyle.DropDownList;
}
private void LoadCategories()
{
try
{
var categories = _categoriesRepository.ReadAll();
comboBoxCategory.DataSource = categories;
comboBoxCategory.DisplayMember = "CategoryName";
comboBoxCategory.ValueMember = "Id";
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при загрузке категорий: {ex.Message}", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
try
{
MessageBox.Show("Введите наименование!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxCategory.SelectedValue == null)
throw new Exception("Имеются незаполненные поля");
PartFlags flags = PartFlags.None;
if (checkRGB.Checked) flags |= PartFlags.RGB;
if (checkLiquid.Checked) flags |= PartFlags.LiquidCooling;
if (checkOC.Checked) flags |= PartFlags.Overclockable;
if (checkModular.Checked) flags |= PartFlags.Modular;
if (checkNVMe.Checked) flags |= PartFlags.NVMe;
if (checkWiFi.Checked) flags |= PartFlags.WiFi;
if (checkBluetooth.Checked) flags |= PartFlags.Bluetooth;
if (checkTouch.Checked) flags |= PartFlags.TouchScreen;
if (checkBacklit.Checked) flags |= PartFlags.BacklitKeyboard;
if (checkMechanical.Checked) flags |= PartFlags.MechanicalKeyboard;
var part = CreatePart(_partId ?? 0);
if (_partId.HasValue)
_repository.Update(part);
else
_repository.Create(part);
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при сохранении",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Parts CreatePart(int id)
{
PartFlags flags = PartFlags.None;
if (checkRGB.Checked) flags |= PartFlags.RGB;
if (checkLiquid.Checked) flags |= PartFlags.LiquidCooling;
@@ -65,27 +135,14 @@ namespace ProjectComputerShop.Forms
if (checkBacklit.Checked) flags |= PartFlags.BacklitKeyboard;
if (checkMechanical.Checked) flags |= PartFlags.MechanicalKeyboard;
var part = Parts.CreateEntity(
id: _partId ?? 0,
return Parts.CreateEntity(
id: id,
name: textBoxName.Text.Trim(),
categoryId: (int)comboBoxCategory.SelectedValue,
price: numericPrice.Value,
warranty: (int)numericWarranty.Value,
flags: flags
);
if (_partId.HasValue)
_repository.Update(part);
else
_repository.Create(part);
DialogResult = DialogResult.OK;
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@@ -1,5 +1,4 @@
using System;
using System.Linq;
using System.Windows.Forms;
using ComputerShop.Entities;
using ComputerShop.Repositories;
@@ -15,21 +14,36 @@ namespace ProjectComputerShop.Forms
{
set
{
var sale = _salesRepository.ReadAll().FirstOrDefault(s => s.Id == value);
if (sale == null) return;
try
{
var sales = _salesRepository.ReadAll();
var sale = sales.FirstOrDefault(s => s.Id == value);
if (sale == null)
throw new InvalidDataException(nameof(sale));
comboBoxSaleType.Text = sale.SaleType;
numericUpDownTotal.Value = sale.TotalAmount;
dateTimePickerSale.Value = sale.SaleDate;
comboBoxSaleType.Text = sale.SaleType;
numericUpDownTotal.Value = sale.TotalAmount;
dateTimePickerSale.Value = sale.SaleDate;
_saleId = value;
_saleId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при получении данных",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
}
public FormSale(ISalesRepository salesRepository)
{
InitializeComponent();
_salesRepository = salesRepository;
_salesRepository = salesRepository ??
throw new ArgumentNullException(nameof(salesRepository));
comboBoxSaleType.Items.AddRange(new object[] { "Сборка", "Комплектующее", "Готовая техника" });
comboBoxSaleType.SelectedIndex = 0;
@@ -38,29 +52,42 @@ namespace ProjectComputerShop.Forms
private void buttonSave_Click(object sender, EventArgs e)
{
var sale = Sales.CreateEntity(
id: _saleId ?? 0,
assemblyId: null,
partId: null,
deviceId: null,
try
{
if (string.IsNullOrWhiteSpace(comboBoxSaleType.Text))
throw new Exception("Имеются незаполненные поля");
if (numericUpDownTotal.Value <= 0)
throw new Exception("Сумма должна быть больше 0");
var sale = CreateSale(_saleId ?? 0);
if (_saleId.HasValue)
_salesRepository.Update(sale);
else
_salesRepository.Create(sale);
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Ошибка при сохранении",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Sales CreateSale(int id)
{
return Sales.CreateEntity(
id: id,
saleDate: dateTimePickerSale.Value,
totalAmount: numericUpDownTotal.Value,
saleType: comboBoxSaleType.SelectedItem.ToString()
);
if (_saleId.HasValue)
_salesRepository.Update(sale);
else
_salesRepository.Create(sale);
DialogResult = DialogResult.OK;
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@@ -5,12 +5,13 @@ using ProjectComputerShop.Repositories;
using Unity;
using Unity.Extension;
using Unity.Lifetime;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Serilog;
using System.IO;
using ProjectComputerShop.Repositories.Implementation;
using Unity.Microsoft.Logging;
using Microsoft.Extensions.Logging;
internal static class Program
{
@@ -46,7 +47,7 @@ internal static class Program
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
var loggerFactory = new LoggerFactory();
LoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger());

View File

@@ -19,6 +19,7 @@
<PackageReference Include="Serilog" Version="4.3.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="10.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />

View File

@@ -5,7 +5,8 @@ namespace ComputerShop.Repositories;
public interface ISalesRepository
{
IEnumerable<Sales> ReadAll(DateTime? from = null, DateTime? to = null);
Sales ReadById(int id);
void Create(Sales sale);
void Update(Sales sale);
void Delete(int findId);
void Delete(int id);
}

View File

@@ -1,4 +1,8 @@
using ComputerShop.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ComputerShop.Entities;
using ComputerShop.Enums;
using ComputerShop.Repositories;
@@ -6,25 +10,110 @@ namespace ProjectComputerShop.Repositories.Implementation;
public class AssembliesRepository : IAssembliesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<AssembliesRepository> _logger;
public AssembliesRepository(IConnectionString connectionString, ILogger<AssembliesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Assemblies> ReadAll()
{
return [];
_logger.LogInformation("Получение всех сборок");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Assemblies";
var assemblies = connection.Query<Assemblies>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(assemblies));
return assemblies;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении сборок");
throw;
}
}
public Assemblies ReadById(int id)
{
return Assemblies.CreateEntity(0, string.Empty, DateTime.MinValue, 0m, AssemblyStatus.InProgress, 0);
_logger.LogInformation("Получение сборки по идентификатору");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Assemblies WHERE Id=@id";
var assembly = connection.QueryFirstOrDefault<Assemblies>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(assembly));
return assembly;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске сборки");
throw;
}
}
public void Create(Assemblies assembly)
{
_logger.LogInformation("Добавление сборки");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(assembly));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
string queryInsert = @"
INSERT INTO Assemblies (AssemblyNumber, AssemblyDate, CostPrice, SellingPrice, Status)
VALUES (@AssemblyNumber, @AssemblyDate, @CostPrice, @SellingPrice, @Status);";
connection.Execute(queryInsert, assembly);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении сборки");
throw;
}
}
public void Update(Assemblies assembly)
{
_logger.LogInformation("Редактирование сборки");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(assembly));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Assemblies
SET
AssemblyNumber=@AssemblyNumber,
AssemblyDate=@AssemblyDate,
CostPrice=@CostPrice,
SellingPrice=@SellingPrice,
Status=@Status
WHERE Id=@Id";
connection.Execute(queryUpdate, assembly);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании сборки");
throw;
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление сборки");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM Assemblies WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении сборки");
throw;
}
}
}

View File

@@ -1,30 +1,114 @@
using ComputerShop.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ComputerShop.Repositories;
using ProjectComputerShop.Entities;
using ProjectComputerShop.Repositories;
namespace ComputerShop.Implementations;
public class CategoriesRepository : ICategoriesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CategoriesRepository> _logger;
public CategoriesRepository(IConnectionString connectionString, ILogger<CategoriesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Categories> ReadAll()
{
return [];
_logger.LogInformation("Получение всех категорий");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Categories";
var categories = connection.Query<Categories>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(categories));
return categories;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении категорий");
throw;
}
}
public Categories ReadById(int id)
{
return Categories.CreateEntity(0, string.Empty);
_logger.LogInformation("Получение категории по идентификатору");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Categories WHERE Id=@id";
var category = connection.QueryFirstOrDefault<Categories>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(category));
return category;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске категории");
throw;
}
}
public void Create(Categories category)
{
_logger.LogInformation("Добавление категории");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(category));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
string queryInsert = @"
INSERT INTO Categories (CategoryName)
VALUES (@CategoryName);";
connection.Execute(queryInsert, category);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении категории");
throw;
}
}
public void Update(Categories category)
{
_logger.LogInformation("Редактирование категории");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(category));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Categories
SET CategoryName=@CategoryName
WHERE Id=@Id";
connection.Execute(queryUpdate, category);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании категории");
throw;
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление категории");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM Categories WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении категории");
throw;
}
}
}

View File

@@ -8,6 +8,6 @@ namespace ProjectComputerShop.Repositories.Implementation;
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "";
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Database=ComputerShop;Username=postgres;Password=12345678;";
}

View File

@@ -1,29 +1,120 @@
using ComputerShop.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ComputerShop.Entities;
using ComputerShop.Repositories;
using ProjectComputerShop.Repositories;
namespace ComputerShop.Implementations;
public class DevicesRepository : IDevicesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<DevicesRepository> _logger;
public DevicesRepository(IConnectionString connectionString, ILogger<DevicesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Devices> ReadAll()
{
return [];
_logger.LogInformation("Получение всех устройств");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Devices";
var devices = connection.Query<Devices>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(devices));
return devices;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении устройств");
throw;
}
}
public Devices ReadById(int id)
{
return Devices.CreateEntity(0, string.Empty, string.Empty, 0, 0m, 0, string.Empty);
_logger.LogInformation("Получение устройства по идентификатору");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Devices WHERE Id=@id";
var device = connection.QueryFirstOrDefault<Devices>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(device));
return device;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске устройства");
throw;
}
}
public void Create(Devices device)
{
_logger.LogInformation("Добавление устройства");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(device));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
string queryInsert = @"
INSERT INTO Devices (Model, Brand, CategoryId, RetailPrice, StockQuantity, SerialNumber)
VALUES (@Model, @Brand, @CategoryId, @RetailPrice, @StockQuantity, @SerialNumber);";
connection.Execute(queryInsert, device);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении устройства");
throw;
}
}
public void Update(Devices device)
{
_logger.LogInformation("Редактирование устройства");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(device));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Devices
SET
Model=@Model,
Brand=@Brand,
CategoryId=@CategoryId,
RetailPrice=@RetailPrice,
StockQuantity=@StockQuantity,
SerialNumber=@SerialNumber
WHERE Id=@Id";
connection.Execute(queryUpdate, device);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании устройства");
throw;
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление устройства");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM Devices WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении устройства");
throw;
}
}
}

View File

@@ -1,31 +1,119 @@
using ComputerShop.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ComputerShop.Entities;
using ComputerShop.Enums;
using ComputerShop.Repositories;
using ProjectComputerShop.Repositories;
namespace ComputerShop.Implementations
{
public class PartsRepository : IPartsRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PartsRepository> _logger;
public PartsRepository(IConnectionString connectionString, ILogger<PartsRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Parts> ReadAll()
{
return [];
_logger.LogInformation("Получение всех деталей");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Parts";
var parts = connection.Query<Parts>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(parts));
return parts;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении деталей");
throw;
}
}
public Parts? ReadById(int id)
{
return null;
_logger.LogInformation("Получение детали по идентификатору");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Parts WHERE Id=@id";
var part = connection.QueryFirstOrDefault<Parts>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(part));
return part;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске детали");
throw;
}
}
public void Create(Parts part)
{
_logger.LogInformation("Добавление детали");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(part));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
string queryInsert = @"
INSERT INTO Parts (Name, Price, WarrantyMonths, Flags)
VALUES (@Name, @Price, @WarrantyMonths, @Flags);";
connection.Execute(queryInsert, part);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении детали");
throw;
}
}
public void Update(Parts part)
{
_logger.LogInformation("Редактирование детали");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(part));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Parts
SET
Name=@Name,
Price=@Price,
WarrantyMonths=@WarrantyMonths,
Flags=@Flags
WHERE Id=@Id";
connection.Execute(queryUpdate, part);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании детали");
throw;
}
}
public void Delete(int id)
{
_logger.LogInformation("Удаление детали");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM Parts WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении детали");
throw;
}
}
}
}

View File

@@ -1,26 +1,136 @@
using ComputerShop.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ComputerShop.Entities;
using ComputerShop.Repositories;
using ProjectComputerShop.Repositories;
using System.Text;
namespace ComputerShop.Implementations;
public class SalesRepository : ISalesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SalesRepository> _logger;
public SalesRepository(IConnectionString connectionString, ILogger<SalesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Sales> ReadAll(DateTime? from = null, DateTime? to = null)
{
return [];
_logger.LogInformation("Получение всех продаж");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryBuilder = new StringBuilder("SELECT * FROM Sales WHERE 1=1");
var parameters = new DynamicParameters();
if (from.HasValue)
{
queryBuilder.Append(" AND SaleDate >= @From");
parameters.Add("From", from.Value);
}
if (to.HasValue)
{
queryBuilder.Append(" AND SaleDate <= @To");
parameters.Add("To", to.Value);
}
var sales = connection.Query<Sales>(queryBuilder.ToString(), parameters);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(sales));
return sales;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении продаж");
throw;
}
}
public Sales ReadById(int id)
{
_logger.LogInformation("Получение продажи по идентификатору");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Sales WHERE Id=@id";
var sale = connection.QueryFirstOrDefault<Sales>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(sale));
return sale;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске продажи");
throw;
}
}
public void Create(Sales sale)
{
_logger.LogInformation("Добавление продажи");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(sale));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
string queryInsert = @"
INSERT INTO Sales (SaleDate, TotalAmount, SaleType)
VALUES ( @SaleDate, @TotalAmount, @SaleType);";
connection.Execute(queryInsert, sale);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении продажи");
throw;
}
}
public void Update(Sales sale)
{
throw new NotImplementedException();
_logger.LogInformation("Редактирование продажи");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(sale));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Sales
SET
AssemblyId=@AssemblyId,
PartId=@PartId,
DeviceId=@DeviceId,
SaleDate=@SaleDate,
TotalAmount=@TotalAmount,
SaleType=@SaleType
WHERE Id=@Id";
connection.Execute(queryUpdate, sale);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании продажи");
throw;
}
}
public void Delete(int findId)
public void Delete(int id)
{
throw new NotImplementedException();
_logger.LogInformation("Удаление продажи");
_logger.LogDebug("Идентификатор: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM Sales WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении продажи");
throw;
}
}
}