Compare commits

...

5 Commits
main ... laba3

81 changed files with 6780 additions and 77 deletions

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities.Enums;
namespace TradeAndProcurementEnterprice.Entities;
public class Agent
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public Qualification Qualification { get; private set; }
public Category Category { get; private set; }
public static Agent CreateEntity(int id, string name, Qualification qualification, Category category)
{
return new Agent
{
Id = id,
Name = name ?? string.Empty,
Qualification = qualification,
Category = category
};
}
}

View File

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities;
public class Contract
{
public int ID { get; private set; }
public DateTime SaleDate { get; private set; }
public int PurchasingCompanyID { get; private set; }
public int AgentsID { get; private set; }
public IEnumerable<ProductSales> ProductSales { get; private set; } = [];
public static Contract CreateOperation(int contractID, int purchasingCompanyID, int agentsID, IEnumerable<ProductSales> productSales)
{
return new Contract
{
ID = contractID,
SaleDate = DateTime.Now,
PurchasingCompanyID = purchasingCompanyID,
AgentsID = agentsID,
ProductSales = productSales
};
}
public static Contract CreateOperation(TempProductSales tempProductSales,
IEnumerable<ProductSales> productSales)
{
return new Contract
{
ID = tempProductSales.ID,
AgentsID = tempProductSales.AgentsId,
SaleDate = tempProductSales.SaleDate,
PurchasingCompanyID = tempProductSales.PurchasingCompanyId,
ProductSales = productSales
};
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities;
public class DelegateToAgents
{
public int Id { get; private set; }
public int ProductArticle { get; private set; }
public int AgentsID { get; private set; }
public int Quantity { get; private set; }
public DateTime Date { get; private set; }
public static DelegateToAgents CreateOperation(int id, int productArticle, int agentsID, int quantity)
{
return new DelegateToAgents
{
Id = id,
ProductArticle = productArticle,
AgentsID = agentsID,
Date = DateTime.Now,
Quantity = quantity
};
}
}

View File

@ -0,0 +1,18 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities.Enums;
[Flags]
public enum Category
{
None = 0,
Dairy = 1,
Groceries = 2,
Frozen = 4,
Other = 8
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities.Enums;
public enum Qualification
{
None = 0,
Junior = 1,
Middle = 2,
Senior = 3
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities.Enums;
public enum Units
{
None = 0,
Kilogram = 1,
Piece = 2,
Liter = 3
}

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities.Enums;
namespace TradeAndProcurementEnterprice.Entities;
public class Product
{
public int Article { get; private set; }
public string Name { get; private set; } = string.Empty;
public decimal SellingPrice { get; private set; }
public Units Unit { get; private set; }
public Category Category { get; private set; }
public int InventoryQuantity { get; private set; }
public static Product CreateEntity(int article, string name, decimal sellingPrice, Units unit,
Category category, int inventoryQuantity)
{
return new Product
{
Article = article,
Name = name ?? string.Empty,
SellingPrice = sellingPrice,
Unit = unit,
Category = category,
InventoryQuantity = inventoryQuantity
};
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities;
public class ProductSales
{
public int Id { get; private set; }
public int ProductArticle { get; private set; }
public int ProductQuantity { get; private set; }
public static ProductSales CreateElement(int id, int prodictArticle, int productQuantity)
{
return new ProductSales
{
Id = id,
ProductArticle = prodictArticle,
ProductQuantity = productQuantity
};
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities;
public class PurchasingCompany
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public static PurchasingCompany CreateEntity(int id, string name)
{
return new PurchasingCompany
{
Id = id,
Name = name
};
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Entities;
public class TempProductSales
{
public int ID { get; private set; }
public int AgentsId { get; private set; }
public DateTime SaleDate { get; private set; }
public int PurchasingCompanyId { get; private set; }
public int ProductArticle { get; private set; }
public int ProductQuantity { get; private set; }
}

View File

@ -1,39 +0,0 @@
namespace TradeAndProcurementEnterprice
{
partial class Form1
{
/// <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 && (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()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace TradeAndProcurementEnterprice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,171 @@
namespace TradeAndProcurementEnterprice
{
partial class FormEnterprice
{
/// <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 && (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()
{
menuStrip1 = new MenuStrip();
catalogToolStripMenuItem = new ToolStripMenuItem();
agentsToolStripMenuItem = new ToolStripMenuItem();
nomenclatureToolStripMenuItem = new ToolStripMenuItem();
purchasingCompanyToolStripMenuItem = new ToolStripMenuItem();
operationToolStripMenuItem = new ToolStripMenuItem();
contractsToolStripMenuItem1 = new ToolStripMenuItem();
delegateToAgentsToolStripMenuItem = new ToolStripMenuItem();
reportToolStripMenuItem = new ToolStripMenuItem();
directoryReportToolStripMenuItem = new ToolStripMenuItem();
productReportToolStripMenuItem = new ToolStripMenuItem();
productAgentsToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(32, 32);
menuStrip1.Items.AddRange(new ToolStripItem[] { catalogToolStripMenuItem, operationToolStripMenuItem, reportToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(3, 1, 0, 1);
menuStrip1.Size = new Size(650, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// catalogToolStripMenuItem
//
catalogToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { agentsToolStripMenuItem, nomenclatureToolStripMenuItem, purchasingCompanyToolStripMenuItem });
catalogToolStripMenuItem.Name = "catalogToolStripMenuItem";
catalogToolStripMenuItem.Size = new Size(94, 22);
catalogToolStripMenuItem.Text = "Справочники";
//
// agentsToolStripMenuItem
//
agentsToolStripMenuItem.Name = "agentsToolStripMenuItem";
agentsToolStripMenuItem.Size = new Size(195, 22);
agentsToolStripMenuItem.Text = "Агенты-реализаторы";
agentsToolStripMenuItem.Click += AgentsToolStripMenuItem_Click;
//
// nomenclatureToolStripMenuItem
//
nomenclatureToolStripMenuItem.Name = "nomenclatureToolStripMenuItem";
nomenclatureToolStripMenuItem.Size = new Size(195, 22);
nomenclatureToolStripMenuItem.Text = "Номенклатура";
nomenclatureToolStripMenuItem.Click += NomenclatureToolStripMenuItem_Click;
//
// purchasingCompanyToolStripMenuItem
//
purchasingCompanyToolStripMenuItem.Name = "purchasingCompanyToolStripMenuItem";
purchasingCompanyToolStripMenuItem.Size = new Size(195, 22);
purchasingCompanyToolStripMenuItem.Text = "Компании закупщики";
purchasingCompanyToolStripMenuItem.Click += PurchasingCompanyToolStripMenuItem_Click;
//
// operationToolStripMenuItem
//
operationToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { contractsToolStripMenuItem1, delegateToAgentsToolStripMenuItem });
operationToolStripMenuItem.Name = "operationToolStripMenuItem";
operationToolStripMenuItem.Size = new Size(75, 22);
operationToolStripMenuItem.Text = "Операции";
//
// contractsToolStripMenuItem1
//
contractsToolStripMenuItem1.Name = "contractsToolStripMenuItem1";
contractsToolStripMenuItem1.Size = new Size(174, 22);
contractsToolStripMenuItem1.Text = "Продажи";
contractsToolStripMenuItem1.Click += ContractsToolStripMenuItem1_Click;
//
// delegateToAgentsToolStripMenuItem
//
delegateToAgentsToolStripMenuItem.Name = "delegateToAgentsToolStripMenuItem";
delegateToAgentsToolStripMenuItem.Size = new Size(174, 22);
delegateToAgentsToolStripMenuItem.Text = "Передача агентам";
delegateToAgentsToolStripMenuItem.Click += DelegateToAgentsToolStripMenuItem_Click;
//
// reportToolStripMenuItem
//
reportToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, productReportToolStripMenuItem, productAgentsToolStripMenuItem });
reportToolStripMenuItem.Name = "reportToolStripMenuItem";
reportToolStripMenuItem.Size = new Size(60, 22);
reportToolStripMenuItem.Text = "Отчёты";
//
// directoryReportToolStripMenuItem
//
directoryReportToolStripMenuItem.Name = "directoryReportToolStripMenuItem";
directoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
directoryReportToolStripMenuItem.Size = new Size(280, 22);
directoryReportToolStripMenuItem.Text = "Документ со справочниками";
directoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// productReportToolStripMenuItem
//
productReportToolStripMenuItem.Name = "productReportToolStripMenuItem";
productReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
productReportToolStripMenuItem.Size = new Size(280, 22);
productReportToolStripMenuItem.Text = "Движение номенклатуры";
productReportToolStripMenuItem.Click += ProductReportToolStripMenuItem_Click;
//
// productAgentsToolStripMenuItem
//
productAgentsToolStripMenuItem.Name = "productAgentsToolStripMenuItem";
productAgentsToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
productAgentsToolStripMenuItem.Size = new Size(280, 22);
productAgentsToolStripMenuItem.Text = "Распределение товара";
productAgentsToolStripMenuItem.Click += ProductAgentsToolStripMenuItem_Click;
//
// FormEnterprice
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackgroundImage = Properties.Resources.photo_2024_12_03_21_34_38;
BackgroundImageLayout = ImageLayout.Stretch;
ClientSize = new Size(650, 339);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Margin = new Padding(2, 1, 2, 1);
Name = "FormEnterprice";
StartPosition = FormStartPosition.CenterScreen;
Text = "Торгово закупочное предприятие";
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem catalogToolStripMenuItem;
private ToolStripMenuItem agentsToolStripMenuItem;
private ToolStripMenuItem nomenclatureToolStripMenuItem;
private ToolStripMenuItem operationToolStripMenuItem;
private ToolStripMenuItem reportToolStripMenuItem;
private ToolStripMenuItem purchasingCompanyToolStripMenuItem;
private ToolStripMenuItem contractsToolStripMenuItem1;
private ToolStripMenuItem delegateToAgentsToolStripMenuItem;
private ToolStripMenuItem directoryReportToolStripMenuItem;
private ToolStripMenuItem productReportToolStripMenuItem;
private ToolStripMenuItem productAgentsToolStripMenuItem;
}
}

View File

@ -0,0 +1,113 @@
using TradeAndProcurementEnterprice.Forms;
using Unity;
namespace TradeAndProcurementEnterprice
{
public partial class FormEnterprice : Form
{
private readonly IUnityContainer _container;
public FormEnterprice(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void AgentsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormAgents>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void NomenclatureToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormProducts>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void PurchasingCompanyToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormPurchasingCompanies>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ContractsToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormContracts>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DelegateToAgentsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDelegatesToAgents>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ProductReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormProductReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ProductAgentsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormProductAgentReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,158 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormAgent
{
/// <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 && (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()
{
buttonCancel = new Button();
buttonSave = new Button();
comboBoxQualification = new ComboBox();
textBoxName = new TextBox();
labelCategory = new Label();
labelQualification = new Label();
labelName = new Label();
checkedListBoxCategory = new CheckedListBox();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(280, 412);
buttonCancel.Margin = new Padding(6, 6, 6, 6);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(156, 49);
buttonCancel.TabIndex = 16;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(80, 412);
buttonSave.Margin = new Padding(6, 6, 6, 6);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(156, 49);
buttonSave.TabIndex = 17;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// comboBoxQualification
//
comboBoxQualification.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxQualification.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxQualification.FormattingEnabled = true;
comboBoxQualification.Location = new Point(217, 124);
comboBoxQualification.Margin = new Padding(6, 6, 6, 6);
comboBoxQualification.Name = "comboBoxQualification";
comboBoxQualification.Size = new Size(273, 40);
comboBoxQualification.TabIndex = 14;
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxName.Location = new Point(217, 38);
textBoxName.Margin = new Padding(6, 6, 6, 6);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(273, 39);
textBoxName.TabIndex = 11;
//
// labelCategory
//
labelCategory.AutoSize = true;
labelCategory.Location = new Point(39, 220);
labelCategory.Margin = new Padding(6, 0, 6, 0);
labelCategory.Name = "labelCategory";
labelCategory.Size = new Size(126, 32);
labelCategory.TabIndex = 7;
labelCategory.Text = "Категория";
//
// labelQualification
//
labelQualification.AutoSize = true;
labelQualification.Location = new Point(43, 130);
labelQualification.Margin = new Padding(6, 0, 6, 0);
labelQualification.Name = "labelQualification";
labelQualification.Size = new Size(174, 32);
labelQualification.TabIndex = 8;
labelQualification.Text = "Квалификация";
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(39, 53);
labelName.Margin = new Padding(6, 0, 6, 0);
labelName.Name = "labelName";
labelName.Size = new Size(67, 32);
labelName.TabIndex = 10;
labelName.Text = "ФИО";
//
// checkedListBoxCategory
//
checkedListBoxCategory.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
checkedListBoxCategory.FormattingEnabled = true;
checkedListBoxCategory.Location = new Point(217, 211);
checkedListBoxCategory.Margin = new Padding(6, 6, 6, 6);
checkedListBoxCategory.Name = "checkedListBoxCategory";
checkedListBoxCategory.Size = new Size(273, 148);
checkedListBoxCategory.TabIndex = 18;
//
// FormAgent
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(549, 504);
Controls.Add(checkedListBoxCategory);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(comboBoxQualification);
Controls.Add(textBoxName);
Controls.Add(labelCategory);
Controls.Add(labelQualification);
Controls.Add(labelName);
Margin = new Padding(6, 6, 6, 6);
MinimumSize = new Size(575, 575);
Name = "FormAgent";
StartPosition = FormStartPosition.CenterParent;
Text = "Агент-реализатор";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private ComboBox comboBoxQualification;
private TextBox textBoxName;
private Label labelCategory;
private Label labelQualification;
private Label labelName;
private CheckedListBox checkedListBoxCategory;
}
}

View File

@ -0,0 +1,108 @@
using Microsoft.VisualBasic.FileIO;
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 TradeAndProcurementEnterprice.Entities;
using TradeAndProcurementEnterprice.Entities.Enums;
using TradeAndProcurementEnterprice.Repositories;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormAgent : Form
{
private readonly IAgentsRepository _agentsRepository;
private int? _agentsId;
public int Id
{
set
{
try
{
var agent = _agentsRepository.ReadAgentByID(value);
if (agent == null)
{
throw new InvalidDataException(nameof(agent));
}
textBoxName.Text = agent.Name;
comboBoxQualification.SelectedItem = agent.Qualification; foreach (Category elem in Enum.GetValues(typeof(Category)))
{
if ((elem & agent.Category) != 0)
{
checkedListBoxCategory.SetItemChecked(checkedListBoxCategory.Items.IndexOf(elem), true);
}
}
_agentsId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormAgent(IAgentsRepository agentsRepository)
{
InitializeComponent();
_agentsRepository = agentsRepository ??
throw new ArgumentNullException(nameof(agentsRepository));
comboBoxQualification.DataSource = Enum.GetValues(typeof(Qualification));
foreach (var elem in Enum.GetValues(typeof(Category)))
{
checkedListBoxCategory.Items.Add(elem);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text) || checkedListBoxCategory.CheckedItems.Count == 0 || comboBoxQualification.SelectedIndex < 1)
{
throw new Exception("Имеются незаполненные поля!");
}
if (_agentsId.HasValue)
{
_agentsRepository.UpdateAgent(CreateAgent(_agentsId.Value));
}
else
{
_agentsRepository.CreateAgent(CreateAgent(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Agent CreateAgent(int id)
{
Category category = Category.None;
foreach (var elem in checkedListBoxCategory.CheckedItems)
{
category |= (Category)elem;
}
return Agent.CreateEntity(id, textBoxName.Text, (Qualification)comboBoxQualification.SelectedItem,
category);
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->

View File

@ -0,0 +1,129 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormAgents
{
/// <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 && (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()
{
panel1 = new Panel();
buttonDel = new Button();
buttonEdit = new Button();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonEdit);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(644, 0);
panel1.Name = "panel1";
panel1.Size = new Size(96, 435);
panel1.TabIndex = 0;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.remove;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(17, 183);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(65, 65);
buttonDel.TabIndex = 3;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonEdit
//
buttonEdit.BackgroundImage = Properties.Resources.edit;
buttonEdit.BackgroundImageLayout = ImageLayout.Stretch;
buttonEdit.Location = new Point(17, 95);
buttonEdit.Name = "buttonEdit";
buttonEdit.Size = new Size(65, 65);
buttonEdit.TabIndex = 2;
buttonEdit.UseVisualStyleBackColor = true;
buttonEdit.Click += ButtonEdit_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(17, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(65, 65);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 82;
dataGridViewData.RowTemplate.Height = 25;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(644, 435);
dataGridViewData.TabIndex = 1;
//
// FormAgents
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(740, 435);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
MinimumSize = new Size(546, 316);
Name = "FormAgents";
StartPosition = FormStartPosition.CenterParent;
Text = "Агенты-реализаторы";
Load += FormAgents_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button buttonAdd;
private Button buttonDel;
private Button buttonEdit;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,115 @@
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.Xml.Linq;
using TradeAndProcurementEnterprice.Repositories;
using TradeAndProcurementEnterprice.Repositories.Implementations;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormAgents : Form
{
private readonly IUnityContainer _container;
private readonly IAgentsRepository _agentsRepository;
public FormAgents(IUnityContainer container, IAgentsRepository agentsRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_agentsRepository = agentsRepository ??
throw new ArgumentNullException(nameof(agentsRepository));
}
private void FormAgents_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormAgent>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonEdit_Click(object sender, EventArgs e)
{
if (!TryGetIdFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormAgent>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_agentsRepository.DeleteAgent(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _agentsRepository.ReadAgents();
private bool TryGetIdFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,189 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormContract
{
/// <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 && (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()
{
buttonCancel = new Button();
buttonSave = new Button();
comboBoxPurchasingCompany = new ComboBox();
comboBoxAgent = new ComboBox();
labelAgent = new Label();
labelPurchatingCompany = new Label();
groupBox1 = new GroupBox();
dataGridViewProduct = new DataGridView();
ColumnProduct = new DataGridViewComboBoxColumn();
ColumnQuantity = new DataGridViewTextBoxColumn();
groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewProduct).BeginInit();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(290, 653);
buttonCancel.Margin = new Padding(6, 6, 6, 6);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(156, 49);
buttonCancel.TabIndex = 32;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(50, 653);
buttonSave.Margin = new Padding(6, 6, 6, 6);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(156, 49);
buttonSave.TabIndex = 33;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// comboBoxPurchasingCompany
//
comboBoxPurchasingCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxPurchasingCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxPurchasingCompany.FormattingEnabled = true;
comboBoxPurchasingCompany.Location = new Point(221, 34);
comboBoxPurchasingCompany.Margin = new Padding(6, 6, 6, 6);
comboBoxPurchasingCompany.Name = "comboBoxPurchasingCompany";
comboBoxPurchasingCompany.Size = new Size(240, 40);
comboBoxPurchasingCompany.TabIndex = 29;
//
// comboBoxAgent
//
comboBoxAgent.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxAgent.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxAgent.FormattingEnabled = true;
comboBoxAgent.Location = new Point(221, 126);
comboBoxAgent.Margin = new Padding(6, 6, 6, 6);
comboBoxAgent.Name = "comboBoxAgent";
comboBoxAgent.Size = new Size(240, 40);
comboBoxAgent.TabIndex = 30;
//
// labelAgent
//
labelAgent.Location = new Point(39, 111);
labelAgent.Margin = new Padding(6, 0, 6, 0);
labelAgent.Name = "labelAgent";
labelAgent.Size = new Size(167, 77);
labelAgent.TabIndex = 27;
labelAgent.Text = "Агент-\r\nреализатор";
//
// labelPurchatingCompany
//
labelPurchatingCompany.Location = new Point(43, 23);
labelPurchatingCompany.Margin = new Padding(6, 0, 6, 0);
labelPurchatingCompany.Name = "labelPurchatingCompany";
labelPurchatingCompany.Size = new Size(163, 68);
labelPurchatingCompany.TabIndex = 28;
labelPurchatingCompany.Text = "Компания закупщик";
//
// groupBox1
//
groupBox1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
groupBox1.Controls.Add(dataGridViewProduct);
groupBox1.Location = new Point(43, 218);
groupBox1.Margin = new Padding(6, 6, 6, 6);
groupBox1.Name = "groupBox1";
groupBox1.Padding = new Padding(6, 6, 6, 6);
groupBox1.Size = new Size(420, 422);
groupBox1.TabIndex = 34;
groupBox1.TabStop = false;
groupBox1.Text = "Продукт";
//
// dataGridViewProduct
//
dataGridViewProduct.AllowUserToResizeColumns = false;
dataGridViewProduct.AllowUserToResizeRows = false;
dataGridViewProduct.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridViewProduct.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewProduct.Columns.AddRange(new DataGridViewColumn[] { ColumnProduct, ColumnQuantity });
dataGridViewProduct.Location = new Point(6, 41);
dataGridViewProduct.Margin = new Padding(6, 6, 6, 6);
dataGridViewProduct.MultiSelect = false;
dataGridViewProduct.Name = "dataGridViewProduct";
dataGridViewProduct.RowHeadersVisible = false;
dataGridViewProduct.RowHeadersWidth = 82;
dataGridViewProduct.RowTemplate.Height = 25;
dataGridViewProduct.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewProduct.Size = new Size(403, 375);
dataGridViewProduct.TabIndex = 0;
//
// ColumnProduct
//
ColumnProduct.HeaderText = "Наименование";
ColumnProduct.MinimumWidth = 10;
ColumnProduct.Name = "ColumnProduct";
ColumnProduct.Width = 200;
//
// ColumnQuantity
//
ColumnQuantity.HeaderText = "Количесво";
ColumnQuantity.MinimumWidth = 10;
ColumnQuantity.Name = "ColumnQuantity";
ColumnQuantity.Width = 200;
//
// FormContract
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(496, 727);
Controls.Add(groupBox1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(comboBoxPurchasingCompany);
Controls.Add(comboBoxAgent);
Controls.Add(labelAgent);
Controls.Add(labelPurchatingCompany);
Margin = new Padding(6, 6, 6, 6);
MinimumSize = new Size(472, 694);
Name = "FormContract";
StartPosition = FormStartPosition.CenterParent;
Text = "Контракт";
groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewProduct).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private ComboBox comboBoxPurchasingCompany;
private ComboBox comboBoxAgent;
private Label labelAgent;
private Label labelPurchatingCompany;
private GroupBox groupBox1;
private DataGridView dataGridViewProduct;
private DataGridViewComboBoxColumn ColumnProduct;
private DataGridViewTextBoxColumn ColumnQuantity;
}
}

View File

@ -0,0 +1,77 @@
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 TradeAndProcurementEnterprice.Entities;
using TradeAndProcurementEnterprice.Repositories;
using TradeAndProcurementEnterprice.Repositories.Implementations;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormContract : Form
{
private readonly IContractRepository _contractRepository;
public FormContract(IContractRepository contractRepository, IAgentsRepository agentsRepository,
IPurchasingCompanyRepository purchasingCompanyRepository, IProductRepository productRepository)
{
InitializeComponent();
_contractRepository = contractRepository ??
throw new ArgumentNullException(nameof(contractRepository));
comboBoxPurchasingCompany.DataSource = purchasingCompanyRepository.ReadCompanies();
comboBoxPurchasingCompany.DisplayMember = "Name";
comboBoxPurchasingCompany.ValueMember = "Id";
comboBoxAgent.DataSource = agentsRepository.ReadAgents();
comboBoxAgent.DisplayMember = "Name";
comboBoxAgent.ValueMember = "Id";
ColumnProduct.DataSource = productRepository.ReadProducts();
ColumnProduct.DisplayMember = "Name";
ColumnProduct.ValueMember = "Article";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (comboBoxAgent.SelectedIndex < 0 || comboBoxPurchasingCompany.SelectedIndex < 0 || dataGridViewProduct.RowCount < 1)
{
throw new Exception("Имеются незаполненные поля!");
}
_contractRepository.CreateContract(Contract.CreateOperation(0,
(int)comboBoxPurchasingCompany.SelectedValue!, (int)comboBoxAgent.SelectedValue!, CreateListProductSalesFromDataGrid()));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<ProductSales> CreateListProductSalesFromDataGrid()
{
var list = new List<ProductSales>();
foreach (DataGridViewRow row in dataGridViewProduct.Rows)
{
if (row.Cells["ColumnProduct"].Value == null || row.Cells["ColumnQuantity"].Value == null)
{
continue;
}
list.Add(ProductSales.CreateElement(0, Convert.ToInt32(row.Cells["ColumnProduct"].Value), Convert.ToInt32(row.Cells["ColumnQuantity"].Value)));
}
return list.GroupBy(x => x.ProductArticle, x => x.ProductQuantity, (id, quantity) =>
ProductSales.CreateElement(0, id, quantity.Sum())).ToList();
}
}
}

View File

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ColumnProduct.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnQuantity.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,101 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormContracts
{
/// <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 && (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()
{
panel1 = new Panel();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(644, 0);
panel1.Name = "panel1";
panel1.Size = new Size(96, 435);
panel1.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(17, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(65, 65);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 82;
dataGridViewData.RowTemplate.Height = 25;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(644, 435);
dataGridViewData.TabIndex = 1;
//
// FormContracts
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(740, 435);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
MinimumSize = new Size(546, 316);
Name = "FormContracts";
StartPosition = FormStartPosition.CenterParent;
Text = "Продажи";
Load += FormContracts_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button buttonAdd;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,58 @@
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 TradeAndProcurementEnterprice.Repositories;
using TradeAndProcurementEnterprice.Repositories.Implementations;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormContracts : Form
{
private readonly IUnityContainer _container;
private readonly IContractRepository _contractRepository;
public FormContracts(IUnityContainer container, IContractRepository contractRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_contractRepository = contractRepository ??
throw new ArgumentNullException(nameof(contractRepository));
}
private void FormContracts_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormContract>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _contractRepository.ReadContracts();
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,160 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormDelegateToAgent
{
/// <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 && (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()
{
buttonCancel = new Button();
buttonSave = new Button();
numericUpDownQuantity = new NumericUpDown();
comboBoxAgent = new ComboBox();
labelQuantity = new Label();
labelAgent = new Label();
labelProduct = new Label();
comboBoxProduct = new ComboBox();
((System.ComponentModel.ISupportInitialize)numericUpDownQuantity).BeginInit();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(282, 309);
buttonCancel.Margin = new Padding(6, 6, 6, 6);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(156, 49);
buttonCancel.TabIndex = 24;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(82, 309);
buttonSave.Margin = new Padding(6, 6, 6, 6);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(156, 49);
buttonSave.TabIndex = 25;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// numericUpDownQuantity
//
numericUpDownQuantity.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
numericUpDownQuantity.Location = new Point(219, 128);
numericUpDownQuantity.Margin = new Padding(6, 6, 6, 6);
numericUpDownQuantity.Maximum = new decimal(new int[] { 1000000, 0, 0, 0 });
numericUpDownQuantity.Name = "numericUpDownQuantity";
numericUpDownQuantity.Size = new Size(277, 39);
numericUpDownQuantity.TabIndex = 23;
//
// comboBoxAgent
//
comboBoxAgent.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxAgent.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxAgent.FormattingEnabled = true;
comboBoxAgent.Location = new Point(219, 220);
comboBoxAgent.Margin = new Padding(6, 6, 6, 6);
comboBoxAgent.Name = "comboBoxAgent";
comboBoxAgent.Size = new Size(273, 40);
comboBoxAgent.TabIndex = 22;
//
// labelQuantity
//
labelQuantity.AutoSize = true;
labelQuantity.Location = new Point(41, 132);
labelQuantity.Margin = new Padding(6, 0, 6, 0);
labelQuantity.Name = "labelQuantity";
labelQuantity.Size = new Size(144, 32);
labelQuantity.TabIndex = 15;
labelQuantity.Text = "Количество";
//
// labelAgent
//
labelAgent.Location = new Point(41, 208);
labelAgent.Margin = new Padding(6, 0, 6, 0);
labelAgent.Name = "labelAgent";
labelAgent.Size = new Size(150, 75);
labelAgent.TabIndex = 17;
labelAgent.Text = "Агент-\r\nреализатор";
//
// labelProduct
//
labelProduct.AutoSize = true;
labelProduct.Location = new Point(41, 45);
labelProduct.Margin = new Padding(6, 0, 6, 0);
labelProduct.Name = "labelProduct";
labelProduct.Size = new Size(181, 32);
labelProduct.TabIndex = 19;
labelProduct.Text = "Наименование";
//
// comboBoxProduct
//
comboBoxProduct.Anchor = AnchorStyles.Top | AnchorStyles.Right;
comboBoxProduct.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxProduct.FormattingEnabled = true;
comboBoxProduct.Location = new Point(219, 38);
comboBoxProduct.Margin = new Padding(6, 6, 6, 6);
comboBoxProduct.Name = "comboBoxProduct";
comboBoxProduct.Size = new Size(273, 40);
comboBoxProduct.TabIndex = 22;
//
// FormDelegateToAgent
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(554, 409);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(numericUpDownQuantity);
Controls.Add(comboBoxProduct);
Controls.Add(comboBoxAgent);
Controls.Add(labelQuantity);
Controls.Add(labelAgent);
Controls.Add(labelProduct);
Margin = new Padding(6, 6, 6, 6);
MinimumSize = new Size(580, 480);
Name = "FormDelegateToAgent";
StartPosition = FormStartPosition.CenterParent;
Text = "Передача агентам";
((System.ComponentModel.ISupportInitialize)numericUpDownQuantity).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private NumericUpDown numericUpDownQuantity;
private ComboBox comboBoxAgent;
private Label labelQuantity;
private Label labelAgent;
private Label labelProduct;
private ComboBox comboBoxProduct;
}
}

View File

@ -0,0 +1,57 @@
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 TradeAndProcurementEnterprice.Entities;
using TradeAndProcurementEnterprice.Repositories;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormDelegateToAgent : Form
{
private readonly IDelegateToAgentRepository _delegateToAgentRepository;
public FormDelegateToAgent(IDelegateToAgentRepository delegateToAgentRepository, IProductRepository productRepository,
IAgentsRepository agentsRepository)
{
InitializeComponent();
_delegateToAgentRepository = delegateToAgentRepository ??
throw new ArgumentNullException(nameof(delegateToAgentRepository));
comboBoxProduct.DataSource = productRepository.ReadProducts();
comboBoxProduct.DisplayMember = "Name";
comboBoxProduct.ValueMember = "Article";
comboBoxAgent.DataSource = agentsRepository.ReadAgents();
comboBoxAgent.DisplayMember = "Name";
comboBoxAgent.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (comboBoxProduct.SelectedIndex < 0 || comboBoxAgent.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля!");
}
_delegateToAgentRepository.CreateDelegatesToAgent(DelegateToAgents.CreateOperation(0,
(int)comboBoxProduct.SelectedValue!,
(int)comboBoxAgent.SelectedValue!, Convert.ToInt32(numericUpDownQuantity.Value)));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,101 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormDelegatesToAgents
{
/// <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 && (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()
{
panel1 = new Panel();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(644, 0);
panel1.Name = "panel1";
panel1.Size = new Size(96, 435);
panel1.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(17, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(65, 65);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 82;
dataGridViewData.RowTemplate.Height = 25;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(644, 435);
dataGridViewData.TabIndex = 1;
//
// FormDelegatesToAgents
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(740, 435);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
MinimumSize = new Size(546, 316);
Name = "FormDelegatesToAgents";
StartPosition = FormStartPosition.CenterParent;
Text = "Передача товара агентам-реализаторам";
Load += FormDelegatesToAgents_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button buttonAdd;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,56 @@
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 TradeAndProcurementEnterprice.Repositories;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormDelegatesToAgents : Form
{
private readonly IUnityContainer _container;
private readonly IDelegateToAgentRepository _delegateToAgentRepository;
public FormDelegatesToAgents(IUnityContainer container, IDelegateToAgentRepository delegateToAgentRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_delegateToAgentRepository = delegateToAgentRepository ??
throw new ArgumentNullException(nameof(delegateToAgentRepository));
}
private void FormDelegatesToAgents_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDelegateToAgent>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _delegateToAgentRepository.ReadDelegatesToAgent();
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,101 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormDirectoryReport
{
/// <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 && (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()
{
checkBoxProducts = new CheckBox();
checkBoxAgents = new CheckBox();
checkBoxCompanies = new CheckBox();
buttonCreate = new Button();
SuspendLayout();
//
// checkBoxProducts
//
checkBoxProducts.AutoSize = true;
checkBoxProducts.Location = new Point(35, 52);
checkBoxProducts.Name = "checkBoxProducts";
checkBoxProducts.Size = new Size(206, 36);
checkBoxProducts.TabIndex = 0;
checkBoxProducts.Text = "Номенклатура";
checkBoxProducts.UseVisualStyleBackColor = true;
//
// checkBoxAgents
//
checkBoxAgents.AutoSize = true;
checkBoxAgents.Location = new Point(35, 121);
checkBoxAgents.Name = "checkBoxAgents";
checkBoxAgents.Size = new Size(278, 36);
checkBoxAgents.TabIndex = 0;
checkBoxAgents.Text = "Агенты-реализаторы";
checkBoxAgents.UseVisualStyleBackColor = true;
//
// checkBoxCompanies
//
checkBoxCompanies.AutoSize = true;
checkBoxCompanies.Location = new Point(35, 191);
checkBoxCompanies.Name = "checkBoxCompanies";
checkBoxCompanies.Size = new Size(290, 36);
checkBoxCompanies.TabIndex = 0;
checkBoxCompanies.Text = "Компании-закупщики";
checkBoxCompanies.UseVisualStyleBackColor = true;
//
// buttonCreate
//
buttonCreate.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
buttonCreate.Location = new Point(35, 261);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(458, 46);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Сформировать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(529, 339);
Controls.Add(buttonCreate);
Controls.Add(checkBoxCompanies);
Controls.Add(checkBoxAgents);
Controls.Add(checkBoxProducts);
MinimumSize = new Size(555, 410);
Name = "FormDirectoryReport";
Text = "Выгрузка справочников";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxProducts;
private CheckBox checkBoxAgents;
private CheckBox checkBoxCompanies;
private Button buttonCreate;
}
}

View File

@ -0,0 +1,63 @@
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 TradeAndProcurementEnterprice.Reports;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxProducts.Checked && !checkBoxProducts.Checked && !checkBoxCompanies.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки!");
}
var saveFileDialog = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (saveFileDialog.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файл для отчёта!");
}
if (_container.Resolve<DocReport>().CreateDoc(saveFileDialog.FileName, checkBoxProducts.Checked,
checkBoxAgents.Checked, checkBoxCompanies.Checked))
{
MessageBox.Show("Документ сформирован.", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа! Подробности в логах.", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании отчёта", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,201 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormProduct
{
/// <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 && (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()
{
labelName = new Label();
labelPrice = new Label();
labelUnit = new Label();
labelCategory = new Label();
labelInventoryQuantity = new Label();
textBoxName = new TextBox();
numericUpDownPrice = new NumericUpDown();
comboBoxUnit = new ComboBox();
numericUpDownQuantity = new NumericUpDown();
buttonSave = new Button();
buttonCancel = new Button();
comboBoxCategory = new ComboBox();
((System.ComponentModel.ISupportInitialize)numericUpDownPrice).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownQuantity).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(26, 27);
labelName.Name = "labelName";
labelName.Size = new Size(180, 33);
labelName.TabIndex = 0;
labelName.Text = "Номенклатура";
//
// labelPrice
//
labelPrice.Location = new Point(26, 84);
labelPrice.Name = "labelPrice";
labelPrice.Size = new Size(158, 73);
labelPrice.TabIndex = 0;
labelPrice.Text = "Цена за единицу";
//
// labelUnit
//
labelUnit.Location = new Point(26, 163);
labelUnit.Name = "labelUnit";
labelUnit.Size = new Size(158, 73);
labelUnit.TabIndex = 0;
labelUnit.Text = "Единица измерения";
//
// labelCategory
//
labelCategory.AutoSize = true;
labelCategory.Location = new Point(26, 270);
labelCategory.Name = "labelCategory";
labelCategory.Size = new Size(131, 33);
labelCategory.TabIndex = 0;
labelCategory.Text = "Категория";
//
// labelInventoryQuantity
//
labelInventoryQuantity.Location = new Point(26, 331);
labelInventoryQuantity.Name = "labelInventoryQuantity";
labelInventoryQuantity.Size = new Size(158, 72);
labelInventoryQuantity.TabIndex = 0;
labelInventoryQuantity.Text = "Количество на складе";
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxName.Location = new Point(248, 24);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(237, 41);
textBoxName.TabIndex = 1;
//
// numericUpDownPrice
//
numericUpDownPrice.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
numericUpDownPrice.DecimalPlaces = 2;
numericUpDownPrice.Location = new Point(248, 100);
numericUpDownPrice.Maximum = new decimal(new int[] { 1000000, 0, 0, 0 });
numericUpDownPrice.Name = "numericUpDownPrice";
numericUpDownPrice.Size = new Size(237, 41);
numericUpDownPrice.TabIndex = 2;
//
// comboBoxUnit
//
comboBoxUnit.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxUnit.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxUnit.FormattingEnabled = true;
comboBoxUnit.Location = new Point(248, 179);
comboBoxUnit.Name = "comboBoxUnit";
comboBoxUnit.Size = new Size(237, 41);
comboBoxUnit.TabIndex = 3;
//
// numericUpDownQuantity
//
numericUpDownQuantity.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
numericUpDownQuantity.Location = new Point(248, 343);
numericUpDownQuantity.Maximum = new decimal(new int[] { 1000000, 0, 0, 0 });
numericUpDownQuantity.Name = "numericUpDownQuantity";
numericUpDownQuantity.Size = new Size(237, 41);
numericUpDownQuantity.TabIndex = 4;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(44, 424);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(201, 46);
buttonSave.TabIndex = 5;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(274, 424);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(201, 46);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// comboBoxCategory
//
comboBoxCategory.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxCategory.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxCategory.FormattingEnabled = true;
comboBoxCategory.Location = new Point(248, 262);
comboBoxCategory.Name = "comboBoxCategory";
comboBoxCategory.Size = new Size(237, 41);
comboBoxCategory.TabIndex = 14;
//
// FormProduct
//
AutoScaleDimensions = new SizeF(15F, 33F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(559, 514);
Controls.Add(comboBoxCategory);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(numericUpDownQuantity);
Controls.Add(comboBoxUnit);
Controls.Add(numericUpDownPrice);
Controls.Add(textBoxName);
Controls.Add(labelInventoryQuantity);
Controls.Add(labelCategory);
Controls.Add(labelUnit);
Controls.Add(labelPrice);
Controls.Add(labelName);
Font = new Font("Comic Sans MS", 9F, FontStyle.Regular, GraphicsUnit.Point);
MinimumSize = new Size(585, 585);
Name = "FormProduct";
StartPosition = FormStartPosition.CenterParent;
Text = "Номенклатура";
((System.ComponentModel.ISupportInitialize)numericUpDownPrice).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownQuantity).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelPrice;
private Label labelUnit;
private Label labelCategory;
private Label labelInventoryQuantity;
private TextBox textBoxName;
private NumericUpDown numericUpDownPrice;
private ComboBox comboBoxUnit;
private NumericUpDown numericUpDownQuantity;
private Button buttonSave;
private Button buttonCancel;
private ComboBox comboBoxCategory;
}
}

View File

@ -0,0 +1,92 @@
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 TradeAndProcurementEnterprice.Repositories;
using TradeAndProcurementEnterprice.Entities;
using TradeAndProcurementEnterprice.Entities.Enums;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormProduct : Form
{
private readonly IProductRepository _productRepository;
private int? _productArticle;
public int Article
{
set
{
try
{
var product = _productRepository.ReadProductByArticle(value);
if (product == null)
{
throw new InvalidDataException(nameof(product));
}
textBoxName.Text = product.Name;
numericUpDownPrice.Value = product.SellingPrice;
comboBoxUnit.SelectedItem = product.Unit;
comboBoxCategory.SelectedItem = product.Category;
numericUpDownQuantity.Value = product.InventoryQuantity;
_productArticle = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormProduct(IProductRepository productRepository)
{
InitializeComponent();
_productRepository = productRepository ??
throw new ArgumentNullException(nameof(productRepository));
comboBoxUnit.DataSource = Enum.GetValues(typeof(Units));
comboBoxCategory.DataSource = Enum.GetValues(typeof(Category));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(textBoxName.Text) || comboBoxUnit.SelectedIndex < 1
|| comboBoxCategory.SelectedIndex < 1)
{
throw new Exception("Имеются незаполненные поля!");
}
if (_productArticle.HasValue)
{
_productRepository.UpdateProduct(CreateProduct(_productArticle.Value));
}
else
{
_productRepository.CreateProduct(CreateProduct(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Product CreateProduct(int article) => Product.CreateEntity(article, textBoxName.Text,
numericUpDownPrice.Value, (Units)comboBoxUnit.SelectedItem, (Category)comboBoxCategory.SelectedItem,
Convert.ToInt32(numericUpDownQuantity.Value));
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,111 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormProductAgentReport
{
/// <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 && (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()
{
buttonChoose = new Button();
labelFile = new Label();
labelDate = new Label();
dateTimePickerData = new DateTimePicker();
buttonBuild = new Button();
SuspendLayout();
//
// buttonChoose
//
buttonChoose.Location = new Point(12, 12);
buttonChoose.Name = "buttonChoose";
buttonChoose.Size = new Size(81, 23);
buttonChoose.TabIndex = 0;
buttonChoose.Text = "Выбрать";
buttonChoose.UseVisualStyleBackColor = true;
buttonChoose.Click += ButtonChoose_Click;
//
// labelFile
//
labelFile.Anchor = AnchorStyles.Top | AnchorStyles.Right;
labelFile.AutoSize = true;
labelFile.Location = new Point(108, 16);
labelFile.Name = "labelFile";
labelFile.Size = new Size(36, 15);
labelFile.TabIndex = 1;
labelFile.Text = "Файл";
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(12, 50);
labelDate.Name = "labelDate";
labelDate.Size = new Size(32, 15);
labelDate.TabIndex = 1;
labelDate.Text = "Дата";
//
// dateTimePickerData
//
dateTimePickerData.Anchor = AnchorStyles.Top | AnchorStyles.Right;
dateTimePickerData.Location = new Point(57, 44);
dateTimePickerData.Name = "dateTimePickerData";
dateTimePickerData.Size = new Size(200, 23);
dateTimePickerData.TabIndex = 2;
//
// buttonBuild
//
buttonBuild.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
buttonBuild.Location = new Point(66, 86);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(154, 23);
buttonBuild.TabIndex = 3;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += ButtonBuild_Click;
//
// FormProductAgentReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(284, 121);
Controls.Add(buttonBuild);
Controls.Add(dateTimePickerData);
Controls.Add(labelDate);
Controls.Add(labelFile);
Controls.Add(buttonChoose);
MinimumSize = new Size(300, 160);
Name = "FormProductAgentReport";
Text = "Распределение товара";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonChoose;
private Label labelFile;
private Label labelDate;
private DateTimePicker dateTimePickerData;
private Button buttonBuild;
}
}

View File

@ -0,0 +1,67 @@
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 TradeAndProcurementEnterprice.Reports;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormProductAgentReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormProductAgentReport(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void ButtonChoose_Click(object sender, EventArgs e)
{
var saveFileDialog = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
_fileName = saveFileDialog.FileName;
labelFile.Text = Path.GetFileName(_fileName);
}
}
private void ButtonBuild_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла для отчета!");
}
if (_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePickerData.Value))
{
MessageBox.Show("Документ сформирован.", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа! Подробности в логах.",
"Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,181 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormProductReport
{
/// <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 && (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()
{
dateTimePickerStart = new DateTimePicker();
labelPath = new Label();
buttonSelectFilePath = new Button();
textBoxFilePath = new TextBox();
comboBoxProduct = new ComboBox();
labelProduct = new Label();
dateTimePickerEnd = new DateTimePicker();
labelDateStart = new Label();
labelDateEnd = new Label();
buttonBuild = new Button();
SuspendLayout();
//
// dateTimePickerStart
//
dateTimePickerStart.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
dateTimePickerStart.Location = new Point(130, 89);
dateTimePickerStart.Margin = new Padding(2, 1, 2, 1);
dateTimePickerStart.Name = "dateTimePickerStart";
dateTimePickerStart.Size = new Size(269, 23);
dateTimePickerStart.TabIndex = 0;
//
// labelPath
//
labelPath.AutoSize = true;
labelPath.Location = new Point(22, 19);
labelPath.Margin = new Padding(2, 0, 2, 0);
labelPath.Name = "labelPath";
labelPath.Size = new Size(87, 15);
labelPath.TabIndex = 1;
labelPath.Text = "Путь до файла";
//
// buttonSelectFilePath
//
buttonSelectFilePath.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSelectFilePath.Location = new Point(373, 19);
buttonSelectFilePath.Margin = new Padding(2, 1, 2, 1);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(24, 18);
buttonSelectFilePath.TabIndex = 2;
buttonSelectFilePath.Text = "..";
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// textBoxFilePath
//
textBoxFilePath.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxFilePath.Location = new Point(130, 19);
textBoxFilePath.Margin = new Padding(2, 1, 2, 1);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(241, 23);
textBoxFilePath.TabIndex = 3;
//
// comboBoxProduct
//
comboBoxProduct.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
comboBoxProduct.FormattingEnabled = true;
comboBoxProduct.Location = new Point(130, 53);
comboBoxProduct.Margin = new Padding(2, 1, 2, 1);
comboBoxProduct.Name = "comboBoxProduct";
comboBoxProduct.Size = new Size(269, 23);
comboBoxProduct.TabIndex = 4;
//
// labelProduct
//
labelProduct.AutoSize = true;
labelProduct.Location = new Point(22, 54);
labelProduct.Margin = new Padding(2, 0, 2, 0);
labelProduct.Name = "labelProduct";
labelProduct.Size = new Size(88, 15);
labelProduct.TabIndex = 1;
labelProduct.Text = "Номенклатура";
//
// dateTimePickerEnd
//
dateTimePickerEnd.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
dateTimePickerEnd.Location = new Point(130, 123);
dateTimePickerEnd.Margin = new Padding(2, 1, 2, 1);
dateTimePickerEnd.Name = "dateTimePickerEnd";
dateTimePickerEnd.Size = new Size(269, 23);
dateTimePickerEnd.TabIndex = 0;
//
// labelDateStart
//
labelDateStart.AutoSize = true;
labelDateStart.Location = new Point(22, 91);
labelDateStart.Margin = new Padding(2, 0, 2, 0);
labelDateStart.Name = "labelDateStart";
labelDateStart.Size = new Size(74, 15);
labelDateStart.TabIndex = 1;
labelDateStart.Text = "Дата начала";
//
// labelDateEnd
//
labelDateEnd.AutoSize = true;
labelDateEnd.Location = new Point(22, 125);
labelDateEnd.Margin = new Padding(2, 0, 2, 0);
labelDateEnd.Name = "labelDateEnd";
labelDateEnd.Size = new Size(98, 15);
labelDateEnd.TabIndex = 1;
labelDateEnd.Text = "Дата окончания ";
//
// buttonBuild
//
buttonBuild.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
buttonBuild.Location = new Point(123, 161);
buttonBuild.Margin = new Padding(2, 1, 2, 1);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(165, 22);
buttonBuild.TabIndex = 5;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += ButtonBuild_Click;
//
// FormProductReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(419, 209);
Controls.Add(buttonBuild);
Controls.Add(comboBoxProduct);
Controls.Add(textBoxFilePath);
Controls.Add(buttonSelectFilePath);
Controls.Add(labelDateEnd);
Controls.Add(labelDateStart);
Controls.Add(labelProduct);
Controls.Add(labelPath);
Controls.Add(dateTimePickerEnd);
Controls.Add(dateTimePickerStart);
Margin = new Padding(2, 1, 2, 1);
MinimumSize = new Size(435, 248);
Name = "FormProductReport";
Text = "Движение номенклатуры";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerStart;
private Label labelPath;
private Button buttonSelectFilePath;
private TextBox textBoxFilePath;
private ComboBox comboBoxProduct;
private Label labelProduct;
private DateTimePicker dateTimePickerEnd;
private Label labelDateStart;
private Label labelDateEnd;
private Button buttonBuild;
}
}

View File

@ -0,0 +1,83 @@
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 TradeAndProcurementEnterprice.Reports;
using TradeAndProcurementEnterprice.Repositories;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormProductReport : Form
{
private readonly IUnityContainer _container;
public FormProductReport(IUnityContainer container, IProductRepository productRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
comboBoxProduct.DataSource = productRepository.ReadProducts();
comboBoxProduct.DisplayMember = "Name";
comboBoxProduct.ValueMember = "Article";
}
private void ButtonSelectFilePath_Click(object sender, EventArgs e)
{
var saveFileDialog = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (saveFileDialog.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxFilePath.Text = saveFileDialog.FileName;
}
private void ButtonBuild_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета!");
}
if (comboBoxProduct.SelectedIndex < 0)
{
throw new Exception("Не выбранф номенклатура!");
}
if (dateTimePickerEnd.Value <= dateTimePickerStart.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания!");
}
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text,
(int)comboBoxProduct.SelectedValue!, dateTimePickerStart.Value, dateTimePickerEnd.Value))
{
MessageBox.Show("Документ сформирован.", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа! Подробности в логах.", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,129 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormProducts
{
/// <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 && (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()
{
panel1 = new Panel();
buttonDel = new Button();
buttonEdit = new Button();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonEdit);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(644, 0);
panel1.Name = "panel1";
panel1.Size = new Size(96, 435);
panel1.TabIndex = 0;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.remove;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(17, 183);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(65, 65);
buttonDel.TabIndex = 3;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonEdit
//
buttonEdit.BackgroundImage = Properties.Resources.edit;
buttonEdit.BackgroundImageLayout = ImageLayout.Stretch;
buttonEdit.Location = new Point(17, 95);
buttonEdit.Name = "buttonEdit";
buttonEdit.Size = new Size(65, 65);
buttonEdit.TabIndex = 2;
buttonEdit.UseVisualStyleBackColor = true;
buttonEdit.Click += ButtonEdit_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(17, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(65, 65);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 82;
dataGridViewData.RowTemplate.Height = 25;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(644, 435);
dataGridViewData.TabIndex = 1;
//
// FormProducts
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(740, 435);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
MinimumSize = new Size(546, 316);
Name = "FormProducts";
StartPosition = FormStartPosition.CenterParent;
Text = "Номенклатура";
Load += FormProducts_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button buttonAdd;
private Button buttonDel;
private Button buttonEdit;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,113 @@
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 TradeAndProcurementEnterprice.Repositories;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormProducts : Form
{
private readonly IUnityContainer _container;
private readonly IProductRepository _productRepository;
public FormProducts(IUnityContainer container, IProductRepository productRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_productRepository = productRepository ??
throw new ArgumentNullException(nameof(productRepository));
}
private void FormProducts_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormProduct>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonEdit_Click(object sender, EventArgs e)
{
if (!TryGetIdFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormProduct>();
form.Article = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_productRepository.DeleteProduct(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _productRepository.ReadProducts();
private bool TryGetIdFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Article"].Value);
return true;
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,129 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormPurchasingCompanies
{
/// <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 && (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()
{
panel1 = new Panel();
buttonDel = new Button();
buttonEdit = new Button();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonEdit);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(644, 0);
panel1.Name = "panel1";
panel1.Size = new Size(96, 435);
panel1.TabIndex = 0;
//
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.remove;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(17, 183);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(65, 65);
buttonDel.TabIndex = 3;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonEdit
//
buttonEdit.BackgroundImage = Properties.Resources.edit;
buttonEdit.BackgroundImageLayout = ImageLayout.Stretch;
buttonEdit.Location = new Point(17, 95);
buttonEdit.Name = "buttonEdit";
buttonEdit.Size = new Size(65, 65);
buttonEdit.TabIndex = 2;
buttonEdit.UseVisualStyleBackColor = true;
buttonEdit.Click += ButtonEdit_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(17, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(65, 65);
buttonAdd.TabIndex = 1;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.RowHeadersWidth = 82;
dataGridViewData.RowTemplate.Height = 25;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(644, 435);
dataGridViewData.TabIndex = 1;
//
// FormPurchasingCompanies
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(740, 435);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
MinimumSize = new Size(546, 316);
Name = "FormPurchasingCompanies";
StartPosition = FormStartPosition.CenterParent;
Text = "Компании закупщики";
Load += FormPurchasingCompanies_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button buttonAdd;
private Button buttonDel;
private Button buttonEdit;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,115 @@
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.Xml.Linq;
using TradeAndProcurementEnterprice.Repositories;
using TradeAndProcurementEnterprice.Repositories.Implementations;
using Unity;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormPurchasingCompanies : Form
{
private readonly IUnityContainer _container;
private readonly IPurchasingCompanyRepository _companyRepository;
public FormPurchasingCompanies(IUnityContainer container, IPurchasingCompanyRepository companyRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_companyRepository = companyRepository ??
throw new ArgumentNullException(nameof(companyRepository));
}
private void FormPurchasingCompanies_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormPurchasingCompany>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonEdit_Click(object sender, EventArgs e)
{
if (!TryGetIdFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormPurchasingCompany>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_companyRepository.DeleteCompany(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _companyRepository.ReadCompanies();
private bool TryGetIdFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,104 @@
namespace TradeAndProcurementEnterprice.Forms
{
partial class FormPurchasingCompany
{
/// <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 && (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()
{
textBoxName = new TextBox();
labelName = new Label();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxName.Location = new Point(243, 46);
textBoxName.Margin = new Padding(6, 6, 6, 6);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(271, 39);
textBoxName.TabIndex = 19;
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(50, 49);
labelName.Margin = new Padding(6, 0, 6, 0);
labelName.Name = "labelName";
labelName.Size = new Size(181, 32);
labelName.TabIndex = 18;
labelName.Text = "Наименование";
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(91, 121);
buttonSave.Margin = new Padding(6, 6, 6, 6);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(156, 49);
buttonSave.TabIndex = 21;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(290, 121);
buttonCancel.Margin = new Padding(6, 6, 6, 6);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(156, 49);
buttonCancel.TabIndex = 20;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormPurchasingCompany
//
AutoScaleDimensions = new SizeF(13F, 32F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(564, 219);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxName);
Controls.Add(labelName);
Margin = new Padding(6, 6, 6, 6);
MinimumSize = new Size(590, 290);
Name = "FormPurchasingCompany";
StartPosition = FormStartPosition.CenterParent;
Text = "Компания закупщик";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxName;
private Label labelName;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,84 @@
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 TradeAndProcurementEnterprice.Entities;
using TradeAndProcurementEnterprice.Entities.Enums;
using TradeAndProcurementEnterprice.Repositories;
using TradeAndProcurementEnterprice.Repositories.Implementations;
namespace TradeAndProcurementEnterprice.Forms
{
public partial class FormPurchasingCompany : Form
{
private readonly IPurchasingCompanyRepository _purchasingCompanyRepository;
private int? _companyId;
public int Id
{
set
{
try
{
var company = _purchasingCompanyRepository.ReadCompaniesByID(value);
if (company == null)
{
throw new InvalidDataException(nameof(company));
}
textBoxName.Text = company.Name;
_companyId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormPurchasingCompany(IPurchasingCompanyRepository purchasingCompanyRepository)
{
InitializeComponent();
_purchasingCompanyRepository = purchasingCompanyRepository ??
throw new ArgumentNullException(nameof(purchasingCompanyRepository));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
throw new Exception("Имеются незаполненные поля!");
}
if (_companyId.HasValue)
{
_purchasingCompanyRepository.UpdateCompanies(CreateCompany(_companyId.Value));
}
else
{
_purchasingCompanyRepository.CreateCompany(CreateCompany(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private PurchasingCompany CreateCompany(int id) =>
PurchasingCompany.CreateEntity(id, textBoxName.Text);
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using TradeAndProcurementEnterprice.Repositories;
using TradeAndProcurementEnterprice.Repositories.Implementations;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace TradeAndProcurementEnterprice
{
internal static class Program
@ -11,7 +20,36 @@ namespace TradeAndProcurementEnterprice
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
Application.Run(CreateContainer().Resolve<FormEnterprice>());
}
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IAgentsRepository, AgentsRepository>(new TransientLifetimeManager());
container.RegisterType<IContractRepository, ContractRepository>(new TransientLifetimeManager());
container.RegisterType<IProductRepository, ProductRepository>(new TransientLifetimeManager());
container.RegisterType<IPurchasingCompanyRepository, PurchasingCompanyRepository>(new TransientLifetimeManager());
container.RegisterType<IDelegateToAgentRepository, DelegateToAgentRepository>(new TransientLifetimeManager());
container.RegisterType<IConnectionString, ConnectionString>(new SingletonLifetimeManager());
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

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TradeAndProcurementEnterprice.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TradeAndProcurementEnterprice.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap add {
get {
object obj = ResourceManager.GetObject("add", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap edit {
get {
object obj = ResourceManager.GetObject("edit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap photo_2024_12_03_21_34_38 {
get {
object obj = ResourceManager.GetObject("photo_2024-12-03_21-34-38", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap remove {
get {
object obj = ResourceManager.GetObject("remove", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,133 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="photo_2024-12-03_21-34-38" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\photo_2024-12-03_21-34-38.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="add" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="remove" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\remove.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="edit" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\edit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

View File

@ -0,0 +1,56 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Repositories;
namespace TradeAndProcurementEnterprice.Reports;
internal class ChartReport
{
private readonly IDelegateToAgentRepository _delegateToAgentRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IDelegateToAgentRepository delegateToAgentRepository, ILogger<ChartReport> logger)
{
_delegateToAgentRepository = delegateToAgentRepository ??
throw new ArgumentNullException(nameof(delegateToAgentRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, DateTime dateTime)
{
try
{
new PdfBuilder(filePath)
.AddHeader("Передача товара агентам-реализаторам")
.AddPieChart("Выдача товара", GetData(dateTime))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа!");
return false;
}
}
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
return _delegateToAgentRepository
.ReadDelegatesToAgent()
.Where(x => x.Date.Date == dateTime.Date)
.GroupBy(x => x.ProductArticle, (key, group) => new
{
Id = key,
Quantity = group.Sum(x => x.Quantity)
})
.Select(x => (x.Id.ToString(), (double)x.Quantity))
.ToList();
}
}

View File

@ -0,0 +1,91 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Repositories;
namespace TradeAndProcurementEnterprice.Reports;
internal class DocReport
{
private readonly IProductRepository _productRepository;
private readonly IAgentsRepository _agentsRepository;
private readonly IPurchasingCompanyRepository _purchasingCompanyRepository;
private readonly ILogger _logger;
public DocReport(IProductRepository productRepository, IAgentsRepository agentsRepository, IPurchasingCompanyRepository purchasingCompanyRepository, ILogger logger)
{
_productRepository = productRepository ??
throw new ArgumentNullException(nameof(productRepository));
_agentsRepository = agentsRepository ??
throw new ArgumentNullException(nameof(agentsRepository));
_purchasingCompanyRepository = purchasingCompanyRepository ??
throw new ArgumentNullException(nameof(purchasingCompanyRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeProducts, bool includeAgents, bool includePurchasingCompany)
{
try
{
var builder = new WordBuilder(filePath)
.AddHeader("Документ со справочниками.");
if (includeProducts)
{
builder.AddParagraph("Номенклатура")
.AddTable([2400, 1200, 2400, 2400, 1200], GetProducts());
}
if (includeAgents)
{
builder.AddParagraph("Агенты-реализаторы")
.AddTable([3400, 2400, 2400], GetAgents());
}
if (includePurchasingCompany)
{
builder.AddParagraph("Компании-закупщики.")
.AddTable([4800], GetCompanies());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа!");
return false;
}
}
private List<string[]> GetProducts()
{
return [["Номенклатура", "Цена", "Единица изменерия", "Категория", "Количество на складе"],
.. _productRepository
.ReadProducts()
.Select(x => new string[] { x.Name, x.SellingPrice.ToString(), x.Unit.ToString(), x.Category.ToString(), x.InventoryQuantity.ToString()})
];
}
private List<string[]> GetAgents()
{
return [["Имя", "Квалификация", "Категория"],
.. _agentsRepository
.ReadAgents()
.Select(x => new string[] { x.Name, x.Qualification.ToString(), x.Category.ToString()})
];
}
private List<string[]> GetCompanies()
{
return [["Наименование компании"],
.. _purchasingCompanyRepository
.ReadCompanies()
.Select(x => new string[] { x.Name})
];
}
}

View File

@ -0,0 +1,334 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Reports;
internal class ExcelBuilder
{
private readonly string _filePath;
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public ExcelBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public ExcelBuilder AddHeader(string header, int startIndex, int cnt)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + cnt; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + cnt - 1)}{_rowIndex}")
}); _rowIndex++;
return this;
}
public ExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public ExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public void Build()
{
using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts()
{
Count = 2,
KnownFonts = BooleanValue.FromBoolean(true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
});
// Жирный шрифт.
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
},
Bold = new Bold() { Val = true }
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill.
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill() { PatternType = new EnumValue<PatternValues>(PatternValues.None) }
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border.
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
// Настройка с границами.
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin },
DiagonalBorder = new DiagonalBorder()
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format.
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
// Форматы.
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Right,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3,
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@ -0,0 +1,98 @@
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities.Enums;
namespace TradeAndProcurementEnterprice.Reports;
internal class PdfBuilder
{
private readonly string _filePath;
private readonly Document _document;
public PdfBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
DefineStyles();
}
public PdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public void Build()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(_filePath);
}
private void DefineStyles()
{
// Стиль для заголовка (жирный).
var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal");
headerStyle.Font.Bold = true;
headerStyle.Font.Size = 20;
}
}

View File

@ -0,0 +1,85 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Repositories;
namespace TradeAndProcurementEnterprice.Reports;
internal class TableReport
{
private readonly IContractRepository _contractRepository;
private readonly IDelegateToAgentRepository _delegateToAgentRepository;
private readonly ILogger _logger;
internal static readonly string[] item = ["Агент-реализатор", "Дата", "Передано агенту", "Продано агентом"];
public TableReport(IContractRepository contractRepository, IDelegateToAgentRepository
delegateToAgentRepository, ILogger<TableReport> logger)
{
_contractRepository = contractRepository ??
throw new ArgumentNullException(nameof(contractRepository));
_delegateToAgentRepository = delegateToAgentRepository ??
throw new ArgumentNullException(nameof(delegateToAgentRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(_logger));
}
public bool CreateTable(string filePath, int productArticle, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по передвижению товара", 0, 4)
.AddParagraph("За период", 0)
.AddTable([10, 10, 15, 15], GetData(productArticle, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при форматировании документа!");
return false;
}
}
private List<string[]> GetData(int productArticle, DateTime startDate, DateTime endDate)
{
var data = _contractRepository
.ReadContracts()
.Where(x => x.SaleDate >= startDate && x.SaleDate <= endDate && x.ProductSales.Any(y => y.ProductArticle == productArticle))
.Select(x => new
{
x.AgentsID,
CurrentDate = x.SaleDate,
CountIn = (int?)null,
CountOut = x.ProductSales.FirstOrDefault(y => y.ProductArticle == productArticle)?.ProductQuantity
})
.Union(
_delegateToAgentRepository
.ReadDelegatesToAgent()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.ProductArticle == productArticle)
.Select(x => new
{
x.AgentsID,
CurrentDate = x.Date,
CountIn = (int?)x.Quantity,
CountOut = (int?)null
}))
.OrderBy(x => x.CurrentDate);
return
new List<string[]>() { item }
.Union(
data
.Select(x => new string[] { x.AgentsID.ToString(), x.CurrentDate.ToString(), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Union(
[["Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]])
.ToList();
}
}

View File

@ -0,0 +1,105 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Reports;
internal class WordBuilder
{
private readonly string _filePath;
private readonly Document _document;
private readonly Body _body;
public WordBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
_body = _document.AppendChild(new Body());
}
public WordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
// Настройки под жирный текст.
//var runProperties = run.AppendChild(new RunProperties());
//runProperties.AppendChild(new Bold());
run.AppendChild(new Text(header));
return this;
}
public WordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
var runProperties = run.AppendChild(new RunProperties());
runProperties.AppendChild(new Bold());
run.AppendChild(new Text(text));
return this;
}
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0) { throw new ArgumentNullException(nameof(widths)); }
if (data == null || data.Count == 0) { throw new ArgumentNullException(nameof(data)); }
if (data.Any(x => x.Length != widths.Length)) { throw new InvalidOperationException("widths.Length != data.Length"); }
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
)));
// Заголовок.
var tableRow = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tableRow.Append(new TableCell(
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tableRow);
// Данные.
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public void Build()
{
using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories;
public interface IAgentsRepository
{
IEnumerable<Agent> ReadAgents();
Agent ReadAgentByID(int id);
void CreateAgent(Agent agent);
void UpdateAgent(Agent agent);
void DeleteAgent(int id);
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Repositories;
public interface IConnectionString
{
public 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 TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories;
public interface IContractRepository
{
IEnumerable<Contract> ReadContracts(DateTime? dateFrom = null, DateTime? dateTo = null,
int? productArticle = null, int? agentID = null, int? purchasingCompaniID = null);
void CreateContract(Contract contract);
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories;
public interface IDelegateToAgentRepository
{
IEnumerable<DelegateToAgents> ReadDelegatesToAgent(DateTime? dateFrom = null, DateTime? dateTo = null,
int? productArticle = null, int? agentID = null);
void CreateDelegatesToAgent(DelegateToAgents delegateToAgents);
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories;
public interface IProductRepository
{
IEnumerable<Product> ReadProducts();
Product ReadProductByArticle(int article);
void CreateProduct(Product product);
void UpdateProduct(Product product);
void DeleteProduct(int article);
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories;
public interface IPurchasingCompanyRepository
{
IEnumerable<PurchasingCompany> ReadCompanies();
PurchasingCompany ReadCompaniesByID(int id);
void CreateCompany(PurchasingCompany company);
void UpdateCompanies(PurchasingCompany company);
void DeleteCompany(int id);
}

View File

@ -0,0 +1,133 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories.Implementations;
internal class AgentsRepository : IAgentsRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<AgentsRepository> _logger;
public AgentsRepository(IConnectionString connectionString, ILogger<AgentsRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateAgent(Agent agent)
{
_logger.LogInformation("Добавление объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(agent));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Agents (Name, Qualification, Category)
VALUES (@Name, @Qualification, @Category)";
connection.Execute(queryInsert, agent);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта!");
throw;
}
}
public void DeleteAgent(int id)
{
_logger.LogInformation("Удаление объекта.");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Agents
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта!");
throw;
}
}
public Agent ReadAgentByID(int id)
{
_logger.LogInformation("Получение объекта по идентификатору.");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Agents
WHERE Id=@id";
var agent = connection.QueryFirst<Agent>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(agent));
return agent;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта!");
throw;
}
}
public IEnumerable<Agent> ReadAgents()
{
_logger.LogInformation("Получение всех объектов.");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Agents";
var agents = connection.Query<Agent>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(agents));
return agents;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов!");
throw;
}
}
public void UpdateAgent(Agent agent)
{
_logger.LogInformation("Редактирование объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(agent));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Agents
SET
Name=@Name,
Qualification=@Qualification,
Category=@Category
WHERE Id=@Id";
connection.Execute(queryUpdate, agent);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта!");
throw;
}
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TradeAndProcurementEnterprice.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localhost, 5432;Database=enterprice;Username=postgres;Password=maria;";
}

View File

@ -0,0 +1,81 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories.Implementations;
internal class ContractRepository : IContractRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ContractRepository> _logger;
public ContractRepository(IConnectionString connectionString, ILogger<ContractRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateContract(Contract contract)
{
_logger.LogInformation("Добавление объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(contract));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Contracts (SaleDate, PurchasingCompanyID, AgentsID)
VALUES (@SaleDate, @PurchasingCompanyID, @AgentsID);
SELECT MAX(ID) FROM Contracts";
var id = connection.QueryFirst<int>(queryInsert, contract, transaction);
var querySubInsert = @"
INSERT INTO ProductSales (ID, ProductArticle, ProductQuantity)
VALUES (@ID, @ProductArticle, @ProductQuantity)";
foreach (var elem in contract.ProductSales)
{
connection.Execute(querySubInsert, new { id, elem.ProductArticle, elem.ProductQuantity }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта!");
throw;
}
}
public IEnumerable<Contract> ReadContracts(DateTime? dateFrom = null, DateTime? dateTo = null, int? productArticle = null, int? agentID = null, int? purchasingCompaniID = null)
{
_logger.LogInformation("Получение всех объектов.");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT c.*, ps.ProductArticle, ps.ProductQuantity FROM Contracts c
INNER JOIN ProductSales ps ON ps.ID = c.ID";
var contracts = connection.Query<TempProductSales>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(contracts));
return contracts.GroupBy(x => x.ID, y => y,
(key, value) => Contract.CreateOperation(value.First(),
value.Select(z => ProductSales.CreateElement(0, z.ProductArticle, z.ProductQuantity)))).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов!");
throw;
}
}
}

View File

@ -0,0 +1,63 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories.Implementations;
internal class DelegateToAgentRepository : IDelegateToAgentRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<DelegateToAgentRepository> _logger;
public DelegateToAgentRepository(IConnectionString connectionString, ILogger<DelegateToAgentRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateDelegatesToAgent(DelegateToAgents delegateToAgents)
{
_logger.LogInformation("Добавление объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(delegateToAgents));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO DelegateToAgents (ProductArticle, AgentsID, Quantity, Date)
VALUES (@ProductArticle, @AgentsID, @Quantity, @Date)";
connection.Execute(queryInsert, delegateToAgents);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта!");
throw;
}
}
public IEnumerable<DelegateToAgents> ReadDelegatesToAgent(DateTime? dateFrom = null, DateTime? dateTo = null, int? productArticle = null, int? agentID = null)
{
_logger.LogInformation("Получение всех объектов.");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM DelegateToAgents";
var delegatesToAgents = connection.Query<DelegateToAgents>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(delegatesToAgents));
return delegatesToAgents;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов!");
throw;
}
}
}

View File

@ -0,0 +1,136 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories.Implementations;
internal class ProductRepository : IProductRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductRepository> _logger;
public ProductRepository(IConnectionString connectionString, ILogger<ProductRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateProduct(Product product)
{
_logger.LogInformation("Добавление объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Products (Name, SellingPrice, Unit, Category, InventoryQuantity)
VALUES (@Name, @SellingPrice, @Unit, @Category, @InventoryQuantity)";
connection.Execute(queryInsert, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта!");
throw;
}
}
public void UpdateProduct(Product product)
{
_logger.LogInformation("Редактирование объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Products
SET
Name=@Name,
SellingPrice=@SellingPrice,
Unit=@Unit,
Category=@Category,
InventoryQuantity=@InventoryQuantity
WHERE Article=@article";
connection.Execute(queryUpdate, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта!");
throw;
}
}
public void DeleteProduct(int article)
{
_logger.LogInformation("Удаление объекта.");
_logger.LogDebug("Объект: {article}", article);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Products
WHERE Article=@article";
connection.Execute(queryDelete, new { article });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта!");
throw;
}
}
public Product ReadProductByArticle(int article)
{
_logger.LogInformation("Получение объекта по идентификатору.");
_logger.LogDebug("Объект: {article}", article);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Products
WHERE Article=@article";
var product = connection.QueryFirst<Product>(querySelect, new { article });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product));
return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта!");
throw;
}
}
public IEnumerable<Product> ReadProducts()
{
_logger.LogInformation("Получение всех объектов.");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Products";
var products = connection.Query<Product>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products));
return products;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов!");
throw;
}
}
}

View File

@ -0,0 +1,125 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TradeAndProcurementEnterprice.Entities;
namespace TradeAndProcurementEnterprice.Repositories.Implementations;
internal class PurchasingCompanyRepository : IPurchasingCompanyRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PurchasingCompanyRepository> _logger;
public PurchasingCompanyRepository(IConnectionString connectionString, ILogger<PurchasingCompanyRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateCompany(PurchasingCompany company)
{
_logger.LogInformation("Добавление объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(company));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO PurchasingCompanies (Name)
VALUES (@Name)";
connection.Execute(queryInsert, company);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта!");
throw;
}
}
public void DeleteCompany(int id)
{
_logger.LogInformation("Удаление объекта.");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM purchasingCompanies
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта!");
throw;
}
}
public IEnumerable<PurchasingCompany> ReadCompanies()
{
_logger.LogInformation("Получение всех объектов.");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM purchasingCompanies";
var companies = connection.Query<PurchasingCompany>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(companies));
return companies;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов!");
throw;
}
}
public PurchasingCompany ReadCompaniesByID(int id)
{
_logger.LogInformation("Получение объекта по идентификатору.");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM PurchasingCompanies
WHERE Id=@id";
var company = connection.QueryFirst<PurchasingCompany>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(company));
return company;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта!");
throw;
}
}
public void UpdateCompanies(PurchasingCompany company)
{
_logger.LogInformation("Редактирование объекта.");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(company));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE PurchasingCompanies
SET
Name=@Name
WHERE Id=@Id";
connection.Execute(queryUpdate, company);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта!");
throw;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -6,6 +6,46 @@
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>12.0</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="Serilog" Version="4.0.2" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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