10 Commits
Lab1 ... Lab3

39 changed files with 2293 additions and 161 deletions

1
.gitignore vendored
View File

@@ -240,6 +240,7 @@ ClientBin/
*.pfx
*.publishsettings
orleans.codegen.cs
*.txt
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)

View File

@@ -6,17 +6,17 @@ namespace RealEstateTransactions.Entities
{
public int Id { get; private set; }
public AgencyType AgencyId { get; private set; }
public AgencyType Agency_ID { get; private set; }
public FormFactorType FormFactorId { get; private set; }
public FormFactorType Form_factor_ID { get; private set; }
public float Area { get; private set; }
public float PricePerSM { get; private set; }
public float Price_per_SM { get; private set; }
public float BasePrice { get; private set; }
public float Base_price { get; private set; }
public float DesiredPrice { get; private set; }
public float Desired_price { get; private set; }
public static Apartment CreateApartment(int id, AgencyType agencyId, FormFactorType formFactorId, float area,
float pricePerSM, float basePrice, float desiredPrice)
@@ -24,12 +24,12 @@ namespace RealEstateTransactions.Entities
return new Apartment
{
Id = id,
AgencyId = agencyId,
FormFactorId = formFactorId,
Agency_ID = agencyId,
Form_factor_ID = formFactorId,
Area = area,
PricePerSM = pricePerSM,
BasePrice = basePrice,
DesiredPrice = desiredPrice
Price_per_SM = pricePerSM,
Base_price = basePrice,
Desired_price = desiredPrice
};
}
}

View File

@@ -4,20 +4,20 @@
{
public int Id { get; private set; }
public string FullName { get; private set; } = string.Empty;
public string Full_name { get; private set; } = string.Empty;
public int PassportSeries { get; private set; }
public int Passport_series { get; private set; }
public int PassportNumber { get; private set; }
public int Passport_number { get; private set; }
public static Buyer CreateBuyer(int id, string fullName, int passportSeries, int passportNumber)
{
return new Buyer
{
Id = id,
FullName = fullName,
PassportSeries = passportSeries,
PassportNumber = passportNumber
Full_name = fullName,
Passport_series = passportSeries,
Passport_number = passportNumber
};
}
}

View File

@@ -4,13 +4,13 @@
{
public int Id { get; private set; }
public int ApartmentId { get; private set; }
public int Apartment_ID { get; private set; }
public int BuyerId { get; private set; }
public int Buyer_ID { get; private set; }
public float DealPrice { get; private set; }
public float Deal_price { get; private set; }
public DateTime DealDate { get; private set; }
public DateTime Deal_date { get; private set; }
public IEnumerable<ServicesDeal> DealServices { get; private set; } = [];
@@ -20,10 +20,10 @@
return new Deal
{
Id = id,
ApartmentId = apartmentId,
BuyerId = buyerId,
DealPrice = dealPrice,
DealDate = dealDate,
Apartment_ID = apartmentId,
Buyer_ID = buyerId,
Deal_price = dealPrice,
Deal_date = dealDate,
DealServices = dealServices
};
}

View File

@@ -4,7 +4,7 @@
{
public int Id { get; private set; }
public int ApartmentId { get; private set; }
public int Apartment_ID { get; private set; }
public string Name { get; private set; } = string.Empty;
@@ -15,7 +15,7 @@
return new PreSalesServices
{
Id = id,
ApartmentId = apartmentId,
Apartment_ID = apartmentId,
Name = name,
Cost = cost
};

View File

@@ -2,19 +2,19 @@
{
public class ServicesDeal
{
public int ServicesId { get; private set; }
public int Services_ID { get; private set; }
public int DealId { get; private set; }
public int Deal_ID { get; private set; }
public float ExecutionTime { get; private set; }
public double Execution_time { get; private set; }
public static ServicesDeal CreateServicesDeal(int servicesId, int dealId, float executionTime)
public static ServicesDeal CreateServicesDeal(int servicesId, int dealId, double executionTime)
{
return new ServicesDeal
{
ServicesId = servicesId,
DealId = dealId,
ExecutionTime = executionTime
Services_ID = servicesId,
Deal_ID = dealId,
Execution_time = executionTime
};
}
}

View File

@@ -37,6 +37,9 @@
допродажныеУслугиToolStripMenuItem = new ToolStripMenuItem();
сделкиToolStripMenuItem = new ToolStripMenuItem();
отчётToolStripMenuItem = new ToolStripMenuItem();
DirectoryReportToolStripMenuItem = new ToolStripMenuItem();
PriceReportToolStripMenuItem = new ToolStripMenuItem();
ChartReportToolStripMenuItem1 = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
@@ -60,21 +63,21 @@
// квартирыToolStripMenuItem
//
квартирыToolStripMenuItem.Name = "квартирыToolStripMenuItem";
квартирыToolStripMenuItem.Size = new Size(224, 26);
квартирыToolStripMenuItem.Size = new Size(174, 26);
квартирыToolStripMenuItem.Text = "Квартиры";
квартирыToolStripMenuItem.Click += КвартирыToolStripMenuItem_Click;
//
// покупателиToolStripMenuItem
//
покупателиToolStripMenuItem.Name = "покупателиToolStripMenuItem";
покупателиToolStripMenuItem.Size = new Size(224, 26);
покупателиToolStripMenuItem.Size = new Size(174, 26);
покупателиToolStripMenuItem.Text = "Покупатели";
покупателиToolStripMenuItem.Click += ПокупателиToolStripMenuItem_Click;
//
// услугиToolStripMenuItem
//
услугиToolStripMenuItem.Name = "услугиToolStripMenuItem";
услугиToolStripMenuItem.Size = new Size(224, 26);
услугиToolStripMenuItem.Size = new Size(174, 26);
услугиToolStripMenuItem.Text = "Услуги";
услугиToolStripMenuItem.Click += УслугиToolStripMenuItem_Click;
//
@@ -101,10 +104,35 @@
//
// отчётToolStripMenuItem
//
отчётToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, PriceReportToolStripMenuItem, ChartReportToolStripMenuItem1 });
отчётToolStripMenuItem.Name = "отчётToolStripMenuItem";
отчётToolStripMenuItem.Size = new Size(73, 24);
отчётToolStripMenuItem.Text = "Отчёты";
//
// DirectoryReportToolStripMenuItem
//
DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem";
DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
DirectoryReportToolStripMenuItem.Size = new Size(343, 26);
DirectoryReportToolStripMenuItem.Text = "Документ по справочникам";
DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// PriceReportToolStripMenuItem
//
PriceReportToolStripMenuItem.Name = "PriceReportToolStripMenuItem";
PriceReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
PriceReportToolStripMenuItem.Size = new Size(343, 26);
PriceReportToolStripMenuItem.Text = "Документ по доходам";
PriceReportToolStripMenuItem.Click += PriceReportToolStripMenuItem_Click;
//
// ChartReportToolStripMenuItem1
//
ChartReportToolStripMenuItem1.Name = "ChartReportToolStripMenuItem1";
ChartReportToolStripMenuItem1.ShortcutKeys = Keys.Control | Keys.P;
ChartReportToolStripMenuItem1.Size = new Size(343, 26);
ChartReportToolStripMenuItem1.Text = "Документ по сделкам";
ChartReportToolStripMenuItem1.Click += ChartReportToolStripMenuItem1_Click;
//
// FormGeneral
//
AutoScaleDimensions = new SizeF(8F, 20F);
@@ -135,5 +163,8 @@
private ToolStripMenuItem отчётToolStripMenuItem;
private ToolStripMenuItem услугиToolStripMenuItem;
private ToolStripMenuItem сделкиToolStripMenuItem;
private ToolStripMenuItem DirectoryReportToolStripMenuItem;
private ToolStripMenuItem PriceReportToolStripMenuItem;
private ToolStripMenuItem ChartReportToolStripMenuItem1;
}
}

View File

@@ -73,5 +73,41 @@ namespace RealEstateTransactions
MessageBox.Show(ex.Message, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void PriceReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormPriceReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ChartReportToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormChartReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@@ -22,15 +22,15 @@ namespace RealEstateTransactions.Forms
foreach (FormFactorType elem in Enum.GetValues(typeof(FormFactorType)))
{
if ((elem & apartment.FormFactorId) != 0)
if ((elem & apartment.Form_factor_ID) != 0)
checkedListBoxFormFactor.SetItemChecked(checkedListBoxFormFactor.Items.IndexOf(elem), true);
}
comboBoxAgency.SelectedIndex = (int)apartment.AgencyId;
comboBoxAgency.SelectedIndex = (int)apartment.Agency_ID;
numericUpDownArea.Value = (decimal)apartment.Area;
numericUpDownPricePerSM.Value = (decimal)apartment.PricePerSM;
numericUpDownBasePrice.Value = (decimal)apartment.BasePrice;
numericUpDownDesiredPrice.Value = (decimal)apartment.DesiredPrice;
numericUpDownPricePerSM.Value = (decimal)apartment.Price_per_SM;
numericUpDownBasePrice.Value = (decimal)apartment.Base_price;
numericUpDownDesiredPrice.Value = (decimal)apartment.Desired_price;
_apartmentId = value;
}

View File

@@ -19,9 +19,9 @@ namespace RealEstateTransactions.Forms
if (buyer == null) throw new InvalidDataException(nameof(buyer));
textBoxFullName.Text = buyer.FullName;
numericUpDownPassportSeries.Value = buyer.PassportSeries;
numericUpDownPassportNumber.Value = buyer.PassportNumber;
textBoxFullName.Text = buyer.Full_name;
numericUpDownPassportSeries.Value = buyer.Passport_series;
numericUpDownPassportNumber.Value = buyer.Passport_number;
_buyerId = value;
}

View File

@@ -0,0 +1,108 @@
namespace RealEstateTransactions.Forms
{
partial class FormChartReport
{
/// <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()
{
buttonSelectFilePath = new Button();
labelFilePath = new Label();
labelDate = new Label();
dateTimePicker = new DateTimePicker();
buttonMakeReport = new Button();
SuspendLayout();
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(12, 12);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(94, 29);
buttonSelectFilePath.TabIndex = 0;
buttonSelectFilePath.Text = "Выбрать";
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// labelFilePath
//
labelFilePath.AutoSize = true;
labelFilePath.Location = new Point(123, 16);
labelFilePath.Name = "labelFilePath";
labelFilePath.Size = new Size(52, 20);
labelFilePath.TabIndex = 1;
labelFilePath.Text = "Файл: ";
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(12, 67);
labelDate.Name = "labelDate";
labelDate.Size = new Size(48, 20);
labelDate.TabIndex = 2;
labelDate.Text = "Дата: ";
//
// dateTimePicker
//
dateTimePicker.Location = new Point(86, 62);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(214, 27);
dateTimePicker.TabIndex = 1;
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(92, 113);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(136, 29);
buttonMakeReport.TabIndex = 2;
buttonMakeReport.Text = "сформировать";
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += ButtonMakeReport_Click;
//
// FormChartReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(328, 164);
Controls.Add(buttonMakeReport);
Controls.Add(dateTimePicker);
Controls.Add(labelDate);
Controls.Add(labelFilePath);
Controls.Add(buttonSelectFilePath);
Name = "FormChartReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Отчёт о доходе";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSelectFilePath;
private Label labelFilePath;
private Label labelDate;
private DateTimePicker dateTimePicker;
private Button buttonMakeReport;
}
}

View File

@@ -0,0 +1,66 @@
using RealEstateTransactions.Reports;
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 Unity;
namespace RealEstateTransactions.Forms
{
public partial class FormChartReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormChartReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void ButtonSelectFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
_fileName = sfd.FileName;
labelFilePath.Text = Path.GetFileName(_fileName);
}
}
private void ButtonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
throw new Exception("Отсутствует имя файла для отчета");
if (_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePicker.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

@@ -60,7 +60,8 @@ namespace RealEstateTransactions.Forms
{
continue;
}
list.Add(ServicesDeal.CreateServicesDeal((int)row.Cells["ColumnService"].Value, 0, (float)row.Cells["ColumnTimeSpan"].Value));
list.Add(ServicesDeal.CreateServicesDeal((int)row.Cells["ColumnService"].Value,
0, Convert.ToDouble(row.Cells["ColumnTimeSpan"].Value)));
}
return list;
}

View File

@@ -0,0 +1,104 @@
namespace RealEstateTransactions.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()
{
checkBoxApartment = new CheckBox();
checkBoxBuyer = new CheckBox();
checkBoxServices = new CheckBox();
buttonBuild = new Button();
SuspendLayout();
//
// checkBoxApartment
//
checkBoxApartment.AutoSize = true;
checkBoxApartment.Font = new Font("Segoe UI", 14F);
checkBoxApartment.Location = new Point(39, 22);
checkBoxApartment.Name = "checkBoxApartment";
checkBoxApartment.Size = new Size(144, 36);
checkBoxApartment.TabIndex = 0;
checkBoxApartment.Text = "Квартиры";
checkBoxApartment.UseVisualStyleBackColor = true;
//
// checkBoxBuyer
//
checkBoxBuyer.AutoSize = true;
checkBoxBuyer.Font = new Font("Segoe UI", 14F);
checkBoxBuyer.Location = new Point(39, 84);
checkBoxBuyer.Name = "checkBoxBuyer";
checkBoxBuyer.Size = new Size(167, 36);
checkBoxBuyer.TabIndex = 1;
checkBoxBuyer.Text = "Покупатели";
checkBoxBuyer.UseVisualStyleBackColor = true;
//
// checkBoxServices
//
checkBoxServices.AutoSize = true;
checkBoxServices.Font = new Font("Segoe UI", 14F);
checkBoxServices.Location = new Point(39, 144);
checkBoxServices.Name = "checkBoxServices";
checkBoxServices.Size = new Size(109, 36);
checkBoxServices.TabIndex = 2;
checkBoxServices.Text = "Услуги";
checkBoxServices.UseVisualStyleBackColor = true;
//
// buttonBuild
//
buttonBuild.Font = new Font("Segoe UI", 14F);
buttonBuild.Location = new Point(12, 204);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(222, 72);
buttonBuild.TabIndex = 3;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += ButtonBuild_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(246, 288);
Controls.Add(buttonBuild);
Controls.Add(checkBoxServices);
Controls.Add(checkBoxBuyer);
Controls.Add(checkBoxApartment);
Name = "FormDirectoryReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Выгрузка";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxApartment;
private CheckBox checkBoxBuyer;
private CheckBox checkBoxServices;
private Button buttonBuild;
}
}

View File

@@ -0,0 +1,65 @@
using RealEstateTransactions.Reports;
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 Unity;
namespace RealEstateTransactions.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new
ArgumentNullException(nameof(container));
}
private void ButtonBuild_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxApartment.Checked &&
!checkBoxBuyer.Checked && !checkBoxServices.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки");
}
var sfd = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файла для отчета");
}
if (_container.Resolve<DocReport>().CreateDoc(sfd.FileName, checkBoxApartment.Checked,
checkBoxBuyer.Checked, checkBoxServices.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,167 @@
namespace RealEstateTransactions.Forms
{
partial class FormPriceReport
{
/// <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()
{
textBoxFilePath = new TextBox();
buttonSelectFilePath = new Button();
labelFilePath = new Label();
labelApartmentId = new Label();
comboBoxApartmentId = new ComboBox();
labelDateStart = new Label();
labelDateEnd = new Label();
dateTimePickerDateStart = new DateTimePicker();
dateTimePickerDateEnd = new DateTimePicker();
buttonMakeReport = new Button();
SuspendLayout();
//
// textBoxFilePath
//
textBoxFilePath.BorderStyle = BorderStyle.FixedSingle;
textBoxFilePath.Location = new Point(125, 12);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(182, 27);
textBoxFilePath.TabIndex = 0;
textBoxFilePath.TabStop = false;
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(313, 10);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(30, 29);
buttonSelectFilePath.TabIndex = 0;
buttonSelectFilePath.Text = "...";
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// labelFilePath
//
labelFilePath.AutoSize = true;
labelFilePath.Location = new Point(12, 14);
labelFilePath.Name = "labelFilePath";
labelFilePath.Size = new Size(112, 20);
labelFilePath.TabIndex = 1;
labelFilePath.Text = "Путь до файла:";
//
// labelApartmentId
//
labelApartmentId.AutoSize = true;
labelApartmentId.Location = new Point(12, 60);
labelApartmentId.Name = "labelApartmentId";
labelApartmentId.Size = new Size(78, 20);
labelApartmentId.TabIndex = 2;
labelApartmentId.Text = "Квартира:";
//
// comboBoxApartmentId
//
comboBoxApartmentId.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxApartmentId.FormattingEnabled = true;
comboBoxApartmentId.Location = new Point(125, 57);
comboBoxApartmentId.Name = "comboBoxApartmentId";
comboBoxApartmentId.Size = new Size(218, 28);
comboBoxApartmentId.TabIndex = 1;
//
// labelDateStart
//
labelDateStart.AutoSize = true;
labelDateStart.Location = new Point(12, 112);
labelDateStart.Name = "labelDateStart";
labelDateStart.Size = new Size(97, 20);
labelDateStart.TabIndex = 3;
labelDateStart.Text = "Дата начала:";
//
// labelDateEnd
//
labelDateEnd.AutoSize = true;
labelDateEnd.Location = new Point(12, 157);
labelDateEnd.Name = "labelDateEnd";
labelDateEnd.Size = new Size(90, 20);
labelDateEnd.TabIndex = 4;
labelDateEnd.Text = "Дата конца:";
//
// dateTimePickerDateStart
//
dateTimePickerDateStart.Location = new Point(125, 107);
dateTimePickerDateStart.Name = "dateTimePickerDateStart";
dateTimePickerDateStart.Size = new Size(218, 27);
dateTimePickerDateStart.TabIndex = 2;
//
// dateTimePickerDateEnd
//
dateTimePickerDateEnd.Location = new Point(125, 152);
dateTimePickerDateEnd.Name = "dateTimePickerDateEnd";
dateTimePickerDateEnd.Size = new Size(218, 27);
dateTimePickerDateEnd.TabIndex = 3;
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(125, 201);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(125, 29);
buttonMakeReport.TabIndex = 4;
buttonMakeReport.Text = "сформировать";
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += ButtonMakeReport_Click;
//
// FormPriceReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(360, 246);
Controls.Add(buttonMakeReport);
Controls.Add(dateTimePickerDateEnd);
Controls.Add(dateTimePickerDateStart);
Controls.Add(labelDateEnd);
Controls.Add(labelDateStart);
Controls.Add(comboBoxApartmentId);
Controls.Add(labelApartmentId);
Controls.Add(labelFilePath);
Controls.Add(buttonSelectFilePath);
Controls.Add(textBoxFilePath);
Name = "FormPriceReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Отчёт по доходу";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxFilePath;
private Button buttonSelectFilePath;
private Label labelFilePath;
private Label labelApartmentId;
private ComboBox comboBoxApartmentId;
private Label labelDateStart;
private Label labelDateEnd;
private DateTimePicker dateTimePickerDateStart;
private DateTimePicker dateTimePickerDateEnd;
private Button buttonMakeReport;
}
}

View File

@@ -0,0 +1,65 @@
using RealEstateTransactions.Reports;
using RealEstateTransactions.Repositories;
using Unity;
namespace RealEstateTransactions.Forms
{
public partial class FormPriceReport : Form
{
private readonly IUnityContainer _container;
public FormPriceReport(IUnityContainer container, IApartmentRepository repository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxApartmentId.DataSource = repository.ReadApartments();
comboBoxApartmentId.DisplayMember = "Id";
comboBoxApartmentId.ValueMember = "Id";
}
private void ButtonSelectFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK) return;
textBoxFilePath.Text = sfd.FileName;
}
private void ButtonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
throw new Exception("Отсутствует имя файла для отчета");
if (comboBoxApartmentId.SelectedIndex < 0)
throw new Exception("Не выбрана квартира");
if (dateTimePickerDateEnd.Value <= dateTimePickerDateStart.Value)
throw new Exception("Дата начала должна быть раньше даты окончания");
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text,
(int)comboBoxApartmentId.SelectedValue!,
dateTimePickerDateStart.Value, dateTimePickerDateEnd.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

@@ -1,6 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using RealEstateTransactions.Repositories;
using RealEstateTransactions.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace RealEstateTransactions
{
@@ -26,10 +30,25 @@ namespace RealEstateTransactions
container.RegisterType<IBuyerRepository, BuyerRepository>();
container.RegisterType<IDealRepository, DealRepository>();
container.RegisterType<IPreSalesServicesRepository, PreSalesServicesRepository>();
container.RegisterType<IServicesDealRepository, ServicesDealRepository>();
container.RegisterType<IServicesRepository, ServicesRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

@@ -9,7 +9,20 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@@ -27,4 +40,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,45 @@
using Microsoft.Extensions.Logging;
using RealEstateTransactions.Repositories;
namespace RealEstateTransactions.Reports
{
public class ChartReport
{
private readonly IDealRepository _dealRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IDealRepository dealRepository, ILogger<ChartReport> logger)
{
_dealRepository = dealRepository ?? throw new
ArgumentNullException(nameof(dealRepository));
_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 _dealRepository
.ReadDeals()
.Where(x => x.Deal_date.Date == dateTime.Date)
.Select(x => (x.Apartment_ID.ToString(), (double)x.Deal_price))
.ToList();
}
}
}

View File

@@ -0,0 +1,88 @@
using Microsoft.Extensions.Logging;
using RealEstateTransactions.Repositories;
namespace RealEstateTransactions.Reports
{
public class DocReport
{
private readonly IApartmentRepository _apartmentRepository;
private readonly IBuyerRepository _buyerRepository;
private readonly IServicesRepository _servicesRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IApartmentRepository apartmentRepository, IBuyerRepository buyerRepository,
IServicesRepository servicesRepository, ILogger<DocReport> logger)
{
_apartmentRepository = apartmentRepository ?? throw new
ArgumentNullException(nameof(apartmentRepository));
_buyerRepository = buyerRepository ?? throw new
ArgumentNullException(nameof(buyerRepository));
_servicesRepository = servicesRepository ?? throw new
ArgumentNullException(nameof(servicesRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeApartments, bool
includeBuyers, bool includeServices)
{
try
{
var builder = new WordBuilder(filePath)
.AddHeader("Документ со справочниками");
if (includeApartments)
{
builder.AddParagraph("Квартиры")
.AddTable([1040, 1040, 1040, 1040, 1040, 1040],
GetApartments());
}
if (includeBuyers)
{
builder.AddParagraph("Покупатели")
.AddTable([2400, 2400, 2400], GetBuyers());
}
if (includeServices)
{
builder.AddParagraph("Услуги")
.AddTable([3600, 3600], GetServices());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetApartments()
{
return [
["Номер агенства", "Комнаты", "Площадь", "Цена за кв. метр", "Базовая стоимость", "Желаемая цена продажи"],
.. _apartmentRepository
.ReadApartments()
.Select(x => new string[] { x.Agency_ID.ToString(), x.Form_factor_ID.ToString(),
x.Area.ToString(), x.Price_per_SM.ToString(), x.Base_price.ToString(), x.Desired_price.ToString() }),
];
}
private List<string[]> GetBuyers()
{
return [
["ФИО", "Серия паспорта", "Номер паспорта"],
.. _buyerRepository
.ReadBuyers()
.Select(x => new string[] { x.Full_name, x.Passport_series.ToString(),
x.Passport_number.ToString() }),
];
}
private List<string[]> GetServices()
{
return [
["Название", "Цена"],
.. _servicesRepository
.ReadServices()
.Select(x => new string[] { x.Name, x.Price.ToString() }),
];
}
}
}

View File

@@ -0,0 +1,320 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace RealEstateTransactions.Reports
{
public 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 count)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBobder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
CreateCell(i, _rowIndex, "", StyleIndex.BoldTextWithoutBobder);
_mergeCells.Append(new MergeCell()
{
Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:" +
$"{GetExcelColumnName(startIndex + count - 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()
});
workbookStylesPart.Stylesheet.Append(fonts);
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill()
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
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);
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 = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
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.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
BoldTextWithoutBobder = 1,
BoldTextWithBorder = 2,
SimpleTextWithBorder = 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,80 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace RealEstateTransactions.Reports
{
public 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("Normal Bold", "Normal");
headerStyle.Font.Bold = true;
headerStyle.Font.Size = 14;
}
}
}

View File

@@ -0,0 +1,78 @@
using Microsoft.Extensions.Logging;
using RealEstateTransactions.Repositories;
namespace RealEstateTransactions.Reports
{
public class TableReport
{
private readonly IDealRepository _dealRepository;
private readonly IPreSalesServicesRepository _preSalesServicesRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Сделка", "Дата", "Доход от сделки", "Доход от допродажных услуг"];
public TableReport(IDealRepository dealRepository,
IPreSalesServicesRepository preSalesServicesRepository, ILogger<TableReport> logger)
{
_dealRepository = dealRepository ?? throw new
ArgumentNullException(nameof(dealRepository));
_preSalesServicesRepository = preSalesServicesRepository ?? throw new
ArgumentNullException(nameof(preSalesServicesRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int apartmentId, DateTime startDate,
DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по доходу от продажи квартиры", 0, 4)
.AddParagraph("за период", 0)
.AddTable([10, 10, 10, 15], GetData(apartmentId, startDate,
endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int apartmentId, DateTime startDate, DateTime
endDate)
{
var data = _dealRepository
.ReadDeals()
.Where(x => x.Deal_date >= startDate && x.Deal_date <= endDate &&
x.Apartment_ID == apartmentId)
.Select(x => new {
DealId = (int?)x.Id, Date = (DateTime?)x.Deal_date, DealPrice = (float?)x.Deal_price, ServicesPrice = (float?)null
})
.Union(
_preSalesServicesRepository
.ReadPreSalesServices()
.Where(x => x.Apartment_ID == apartmentId)
.Select(x => new {
DealId = (int?)null, Date = (DateTime?)null, DealPrice = (float?)null, ServicesPrice = (float?)x.Cost
}))
.OrderBy(x => x.Date);
return
new List<string[]>() { item }
.Union(
data
.Select(x => new string[] {
x.DealId?.ToString() ?? string.Empty, x.Date?.ToString() ?? string.Empty,
x.DealPrice?.ToString() ?? string.Empty, x.ServicesPrice?.ToString() ?? string.Empty}))
.Union(
[["Всего", "", data.Sum(x => x.DealPrice ?? 0).ToString(),
data.Sum(x => x.ServicesPrice ?? 0).ToString()]])
.ToList();
}
}
}

View File

@@ -0,0 +1,126 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace RealEstateTransactions.Reports
{
public 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(new RunProperties(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());
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 tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.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(tr);
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,7 @@
namespace RealEstateTransactions.Repositories
{
public interface IConnectionString
{
string ConnectionString { get; }
}
}

View File

@@ -4,14 +4,11 @@ namespace RealEstateTransactions.Repositories
{
public interface IDealRepository
{
IEnumerable<Deal> ReadDeals();
Deal ReadDeal(int id);
IEnumerable<Deal> ReadDeals(DateTime? dateForm = null, DateTime? dateTo = null,
int? servicesID = null, int? dealID = null);
void CreateDeal(Deal deal);
void UpdateDeal(Deal deal);
void DeleteDeal(int id);
}
}

View File

@@ -1,11 +0,0 @@
using RealEstateTransactions.Entities;
namespace RealEstateTransactions.Repositories
{
public interface IServicesDealRepository
{
IEnumerable<ServicesDeal> ReadServicesDeal();
void CreateServicesDeal(ServicesDeal servicesDeal);
}
}

View File

@@ -1,38 +1,125 @@
using RealEstateTransactions.Entities;
using RealEstateTransactions.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RealEstateTransactions.Entities;
using Npgsql;
namespace RealEstateTransactions.Repositories.Implementations
{
public class ApartmentRepository : IApartmentRepository
{
public Apartment ReadApartment(int id)
{
return Apartment.CreateApartment(0, AgencyType.None, FormFactorType.None, 0, 0, 0, 0);
}
private readonly IConnectionString _connectionString;
public IEnumerable<Apartment> ReadApartments()
private readonly ILogger<ApartmentRepository> _logger;
public ApartmentRepository(IConnectionString connectionString, ILogger<ApartmentRepository> logger)
{
return [];
_connectionString = connectionString;
_logger = logger;
}
public void CreateApartment(Apartment apartment)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(apartment));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var insertQuery = @"
INSERT INTO Apartment (Agency_ID, Form_factor_ID, Area, Price_per_SM, Base_price, Desired_price)
VALUES (@Agency_ID, @Form_factor_ID, @Area, @Price_per_SM, @Base_price, @Desired_price)";
connection.Execute(insertQuery, apartment);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateApartment(Apartment apartment)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(apartment));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var updateQuery = @"
UPDATE Apartment
SET
Agency_ID = @Agency_ID,
Form_Factor_ID = @Form_factor_ID,
Area = @Area,
Price_per_SM = @Price_per_SM,
Base_price = @Base_price,
Desired_price = @Desired_price
WHERE Id = @Id";
connection.Execute(updateQuery, apartment);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании оьъекта");
throw;
}
}
public Apartment ReadApartment(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = @"
SELECT *
FROM Apartment
WHERE ID = @id";
var apartment = connection.QueryFirst<Apartment>(selectQuery, new { id });
_logger.LogDebug("Найден объект: {json}", JsonConvert.SerializeObject(apartment));
return apartment;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Apartment> ReadApartments()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = @"SELECT * FROM Apartment";
var apartments = connection.Query<Apartment>(selectQuery);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(apartments));
return apartments;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void DeleteApartment(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var deleteQuery = @"
DELETE FROM Apartment
WHERE ID = @id";
connection.Execute(deleteQuery, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public void UpdateApartment(Apartment apartment)
{
}
}
}
}

View File

@@ -1,38 +1,122 @@
using RealEstateTransactions.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using RealEstateTransactions.Entities;
namespace RealEstateTransactions.Repositories.Implementations
{
public class BuyerRepository : IBuyerRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<BuyerRepository> _logger;
public BuyerRepository(IConnectionString connectionString, ILogger<BuyerRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateBuyer(Buyer buyer)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(buyer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var insertQuery = @"
INSERT INTO Buyer (Full_name, Passport_series, Passport_number)
VALUES (@Full_name, @Passport_series, @Passport_number)";
connection.Execute(insertQuery, buyer);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteBuyer(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var deleteQuery = @"
DELETE FROM Buyer
WHERE Id = @id";
connection.Execute(deleteQuery, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Buyer ReadBuyer(int id)
{
return Buyer.CreateBuyer(0, "", 0, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = @"
SELECT *
FROM Buyer
WHERE Id = @id";
var buyer = connection.QueryFirst<Buyer>(selectQuery, new { id });
_logger.LogDebug("Найден объект: {json}", JsonConvert.SerializeObject(buyer));
return buyer;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Buyer> ReadBuyers()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = "SELECT * FROM Buyer";
var buyers = connection.Query<Buyer>(selectQuery);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(buyers));
return buyers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateBuyer(Buyer buyer)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(buyer));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var updateQuery = @"
UPDATE Buyer
SET
Full_name = @Full_name,
Passport_series = @Passport_series,
Passport_number = @Passport_number
WHERE Id = @Id";
connection.Execute(updateQuery, buyer);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}
}

View File

@@ -0,0 +1,7 @@
namespace RealEstateTransactions.Repositories.Implementations
{
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=Roma12345;Database=otp";
}
}

View File

@@ -1,32 +1,92 @@
using RealEstateTransactions.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using RealEstateTransactions.Entities;
namespace RealEstateTransactions.Repositories.Implementations
{
public class DealRepository : IDealRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<DealRepository> _logger;
public DealRepository(IConnectionString connectionString, ILogger<DealRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateDeal(Deal deal)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(deal));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var insertQuery = @"
INSERT INTO Deal (Apartment_ID, Buyer_ID, Deal_price, Deal_date)
VALUES (@Apartment_ID, @Buyer_ID, @Deal_price, @Deal_date);
SELECT MAX(Id) FROM Deal";
var dealId = connection.QueryFirst<int>(insertQuery, deal, transaction);
var subInsertQuery = @"
INSERT INTO Services_Deal (Services_ID, Deal_ID, Execution_time)
VALUES (@Services_ID, @Deal_ID, @Execution_time)";
foreach (var elem in deal.DealServices)
{
connection.Execute(subInsertQuery, new { elem.Services_ID,
Deal_ID = dealId, elem.Execution_time }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteDeal(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var deleteQuery = @"
DELETE FROM Deal
WHERE Id = @id";
connection.Execute(deleteQuery, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Deal ReadDeal(int id)
public IEnumerable<Deal> ReadDeals(DateTime? dateForm = null, DateTime? dateTo = null,
int? servicesID = null, int? dealID = null)
{
return Deal.CreateDeal(0, 0, 0, 0, DateTime.Now, []);
}
public IEnumerable<Deal> ReadDeals()
{
return [];
}
public void UpdateDeal(Deal deal)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = @"SELECT * FROM Deal";
var deals = connection.Query<Deal>(selectQuery);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(deals));
return deals;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}
}

View File

@@ -1,28 +1,77 @@
using RealEstateTransactions.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using RealEstateTransactions.Entities;
namespace RealEstateTransactions.Repositories.Implementations
{
public class PreSalesServicesRepository : IPreSalesServicesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PreSalesServicesRepository> _logger;
public PreSalesServicesRepository(IConnectionString connectionString, ILogger<PreSalesServicesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreatePreSalesService(PreSalesServices preSalesServices)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(preSalesServices));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var insertQuery = @"
INSERT INTO Pre_Sales_Services (Apartment_ID, Name, Cost)
VALUES (@Apartment_ID, @Name, @Cost)";
connection.Execute(insertQuery, preSalesServices);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeletePreSalesService(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var deleteQuery = @"
DELETE FROM Pre_Sales_Services
WHERE Id = @id";
connection.Execute(deleteQuery, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<PreSalesServices> ReadPreSalesServices()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = "SELECT * FROM Pre_Sales_Services";
var preSalesServices = connection.Query<PreSalesServices>(selectQuery);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(preSalesServices));
return preSalesServices;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}
}

View File

@@ -1,27 +0,0 @@
using RealEstateTransactions.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RealEstateTransactions.Repositories.Implementations
{
public class ServicesDealRepository : IServicesDealRepository
{
public void CreateServicesDeal(ServicesDeal servicesDeal)
{
}
public void DeleteServicesDeal(int id)
{
}
public IEnumerable<ServicesDeal> ReadServicesDeal()
{
return [];
}
}
}

View File

@@ -1,37 +1,121 @@
using RealEstateTransactions.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using RealEstateTransactions.Entities;
namespace RealEstateTransactions.Repositories.Implementations
{
public class ServicesRepository : IServicesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ServicesRepository> _logger;
public ServicesRepository(IConnectionString connectionString, ILogger<ServicesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateService(Services service)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var insertQuery = @"
INSERT INTO Services (Name, Price)
VALUES (@Name, @Price)";
connection.Execute(insertQuery, service);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteService(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var deleteQuery = @"
DELETE FROM Services
WHERE Id = @id";
connection.Execute(deleteQuery, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Services ReadService(int id)
{
return Services.CreateService(0, "", 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {Id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = @"
SELECT *
FROM Services
WHERE Id = @id";
var service = connection.QueryFirst<Services>(selectQuery, new { id });
_logger.LogDebug("Найден объект: {json}", JsonConvert.SerializeObject(service));
return service;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Services> ReadServices()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var selectQuery = "SELECT * FROM Services";
var services = connection.Query<Services>(selectQuery);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(services));
return services;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateService(Services service)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var updateQuery = @"
UPDATE Services
SET
Name = @Name,
Price = @Price
WHERE Id = @Id";
connection.Execute(updateQuery, service);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}
}

View File

@@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:/my/курс 2 сим 1/ОТП/Lab/Log.txt",
"rollingInterval": "Day"
}
}
]
}
}