Compare commits

..

85 Commits

Author SHA1 Message Date
c4e66e3245 форматирую себе диск цэ 2023-04-24 01:54:33 +04:00
632e6609a2 зависимости какие то 2023-04-24 00:01:34 +04:00
9c7400183c интерфейс 2023-04-23 23:13:35 +04:00
2d7ffc80ca приделал базу к харде и харду к базе 2023-04-23 23:05:26 +04:00
7a22a82042 merge 2023-04-23 23:05:06 +04:00
54c70a7aef Merge branch 'LabWork06_Hard' into LabWork07_Hard 2023-04-22 23:29:04 +04:00
c8a2bcd682 Merge branch 'LabWork07_Base' into LabWork07_Hard 2023-04-22 23:28:29 +04:00
c44f3c6d64 Merge branch 'LabWork06_Base' into LabWork06_Hard 2023-04-22 23:27:38 +04:00
c0fc48b7e4 Late night, come home
Work sucks, I know
She left me roses by the stairs
Surprises let me know she cares
2023-04-22 13:48:42 +04:00
ecfa871e1a Merge branch 'LabWork06_Hard' into LabWork07_Hard 2023-04-22 10:33:03 +04:00
1b57449e73 fix 2023-04-22 10:32:35 +04:00
9a6db9bd9e merge fix 2023-04-22 10:31:46 +04:00
356571305e merge fix 2023-04-22 10:29:04 +04:00
a52922a883 merge fix 2023-04-22 10:24:27 +04:00
e13229f35d сдана лаб6хард 2023-04-21 11:30:22 +04:00
ba8aac61f5 merge 2023-04-20 21:20:08 +04:00
3cf140e4a3 Merge branch 'LabWork05_Hard' into LabWork06_Hard 2023-04-20 20:46:09 +04:00
0b296d433f Merge branch 'LabWork05_Base' into LabWork05_Hard 2023-04-20 20:45:08 +04:00
7d7be6231f lab6hard is ready to go 2023-04-20 00:19:40 +04:00
5a541e540b работаем 2023-04-19 22:40:36 +04:00
bb689ff63b Merge branch 'LabWork06_Base' into LabWork06_Hard 2023-04-19 21:20:20 +04:00
c8741b8e51 merge completed 2023-04-18 18:34:09 +04:00
d280110fc1 merge lab5 hard 2023-04-18 17:45:17 +04:00
842ec7cded Merge branch 'LabWork04_Hard' into LabWork05_Hard 2023-04-09 16:14:40 +04:00
ca1e5c73be Merge branch 'LabWork03_Hard' into LabWork04_Hard 2023-04-09 16:14:16 +04:00
97736d8dde Исправлен апдейт магазина 2023-04-09 16:13:54 +04:00
9952625971 Что вершит судьбу человечества в этом мире? Некое незримое существо или закон, подобно Длани Господней парящей над миром? По крайне мере истинно то, что человек не властен даже над своей волей. 2023-04-09 00:53:06 +04:00
7b5ae3ea1e merge 2023-04-08 21:10:01 +04:00
d3c3de4047 Merge branch 'LabWork03_Hard' into LabWork04_Hard 2023-04-07 21:47:26 +04:00
8956013a65 Merge branch 'LabWork03_Base' into LabWork03_Hard 2023-04-07 21:46:32 +04:00
e096b326a6 Merge branch 'LabWork03_Hard' into LabWork04_Hard 2023-04-07 16:07:04 +04:00
4e7e88cb3f Merge branch 'LabWork02_Hard' into LabWork03_Hard 2023-04-07 16:06:22 +04:00
71f60ebf7a Исправление 2023-04-07 16:05:54 +04:00
0b3b9b391a Переделан под LINQ метод SellDocument 2023-04-07 16:04:49 +04:00
415e4c2d6f Merge branch 'LabWork04_Base' into LabWork04_Hard 2023-04-07 15:50:52 +04:00
d2653e9015 Сдана хард4 2023-03-27 10:09:32 +04:00
4b8f3eae04 Отчет по заказам по дате PDF 2023-03-26 22:39:05 +04:00
ced6ecb062 Отчет по магазинам в Excel 2023-03-26 21:38:36 +04:00
9a7407f156 Отчет списка магазинов в word файл 2023-03-26 21:03:24 +04:00
8a60e580e8 fix 2023-03-26 20:48:57 +04:00
33744d1560 Merge 2023-03-26 20:48:44 +04:00
793c2eae4e merge 2023-03-24 21:01:10 +04:00
5327fd4511 fix 2023-03-13 11:15:33 +04:00
00c2a39c41 Сдана 2 хард 2023-03-13 10:14:57 +04:00
0fb113ffbd Вроде готово 2023-03-12 19:26:43 +04:00
50a53fe8f4 Merge branch 'LabWork02_Hard' into LabWork03_Hard 2023-03-12 19:00:47 +04:00
51738e8616 Обновлена логика продажи из магазинов 2023-03-12 19:00:22 +04:00
cc30da7d11 созданы модели 2023-03-12 18:42:24 +04:00
c3e9384f23 Merge branch 'LabWork03_Base' into LabWork03_Hard 2023-03-12 17:56:03 +04:00
2036d05b3a фикс 2023-03-12 14:58:17 +04:00
27bd7178b1 Merge branch 'LabWork02_Base' into LabWork02_Hard 2023-03-10 21:06:32 +04:00
7aa92dbb74 Merge branch 'LabWork02_Base' into LabWork02_Hard 2023-03-10 19:39:05 +04:00
29a8bf30cc Merge branch 'LabWork01_Hard' into LabWork02_Hard 2023-03-10 19:38:46 +04:00
3b2493bbaf Merge branch 'LabWork01_Hard' of http://student.git.athene.tech/Danila_Mochalov/PIbd-23_Mochalov_D.V._LawFirm into LabWork01_Hard 2023-03-10 19:23:23 +04:00
b1dfb228b2 Сдана лаб 1 хард 2023-03-10 19:18:42 +04:00
cf13f3028e Доделал дату 2023-03-10 19:16:20 +04:00
5c57715fe3 Вроде готово. Надо исправить отображение даты открытия на форме FormShops 2023-03-10 19:16:20 +04:00
72b59a71eb Реализовано хранилище магазинов, класс магазина, изменен синглтон 2023-03-10 19:16:20 +04:00
14a2efbb78 Реализация логики магазина 2023-03-10 19:16:20 +04:00
8597edb910 Создание интерфейсов хранилища и логики магазина 2023-03-10 19:16:20 +04:00
d67f6123f2 Создание моделей магазина 2023-03-10 19:16:20 +04:00
bb74221578 Вот теперь точно все работает и все сделано (надеюсь) 2023-03-02 22:09:15 +04:00
0f604b38fe Исправил сохранение после продажи 2023-03-01 19:09:58 +04:00
6a68de1873 Вроде все работает, но было бы неплохо порефакторить 2023-03-01 19:04:30 +04:00
94dde9c5d9 Небольшой дебаг сохранения и пополнения магазина 2023-03-01 18:13:57 +04:00
f20984c4ba Изменена форма создания магазина с учетом вместимости 2023-02-27 10:31:58 +04:00
de6f3af8df Изменена логика пополнения магазина с учетом его максимальной вместимости 2023-02-27 10:19:40 +04:00
35ee01f552 Написана какая-то логика продажи в магазине 2023-02-27 09:49:29 +04:00
5b5b8cc6ac Фиксы 2023-02-27 08:49:14 +04:00
faef920c50 Начата файловая реализация магазина 2023-02-26 23:20:43 +04:00
0c47f0f7cd merge 2023-02-26 13:29:37 +04:00
675b6546f4 Сдана лаб 1 хард 2023-02-13 10:08:11 +04:00
461ada29fb Merge branch 'LabWork01_Hard' of http://student.git.athene.tech/Danila_Mochalov/PIbd-23_Mochalov_D.V._LawFirm into LabWork01_Hard 2023-02-13 09:35:02 +04:00
b199a71b8a Доделал дату 2023-02-13 09:33:49 +04:00
a8b8f627b3 Вроде готово. Надо исправить отображение даты открытия на форме FormShops 2023-02-13 09:33:49 +04:00
39c6ef7591 Реализовано хранилище магазинов, класс магазина, изменен синглтон 2023-02-13 09:33:49 +04:00
390d10adb9 Реализация логики магазина 2023-02-13 09:33:49 +04:00
f773128233 Создание интерфейсов хранилища и логики магазина 2023-02-13 09:33:49 +04:00
53432af1bb Создание моделей магазина 2023-02-13 09:33:49 +04:00
ef3d3d4114 Доделал дату 2023-02-13 08:48:47 +04:00
66e77b2a1a Вроде готово. Надо исправить отображение даты открытия на форме FormShops 2023-02-13 00:19:42 +04:00
4fb74a26c1 Реализовано хранилище магазинов, класс магазина, изменен синглтон 2023-02-12 18:42:09 +04:00
f221cd82d0 Реализация логики магазина 2023-02-12 18:23:39 +04:00
5043230479 Создание интерфейсов хранилища и логики магазина 2023-02-12 16:37:12 +04:00
a80b2b19fd Создание моделей магазина 2023-02-01 15:17:07 +04:00
262 changed files with 155193 additions and 289 deletions

View File

@ -17,9 +17,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmFileImplement", "Law
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmDatabaseImplement", "LawFirmDatabaseImplement\LawFirmDatabaseImplement.csproj", "{CB0444D3-5BDA-42DB-95F9-60191AE9073A}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmDatabaseImplement", "LawFirmDatabaseImplement\LawFirmDatabaseImplement.csproj", "{CB0444D3-5BDA-42DB-95F9-60191AE9073A}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LawFirmRestApi", "LawFirmRestApi\LawFirmRestApi.csproj", "{8DB8A004-DB42-46F2-8EAA-AAEB498FCD36}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmRestApi", "LawFirmRestApi\LawFirmRestApi.csproj", "{8DB8A004-DB42-46F2-8EAA-AAEB498FCD36}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LawFirmClientApp", "LawFirmClientApp\LawFirmClientApp.csproj", "{9D63F716-C761-423B-BBC2-DC5F51081B43}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LawFirmClientApp", "LawFirmClientApp\LawFirmClientApp.csproj", "{9D63F716-C761-423B-BBC2-DC5F51081B43}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LawFirmShopApp", "LawFirmShopApp\LawFirmShopApp.csproj", "{B246B813-6218-4DD6-B48E-42D0FF5588B6}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -63,6 +65,10 @@ Global
{9D63F716-C761-423B-BBC2-DC5F51081B43}.Debug|Any CPU.Build.0 = Debug|Any CPU {9D63F716-C761-423B-BBC2-DC5F51081B43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D63F716-C761-423B-BBC2-DC5F51081B43}.Release|Any CPU.ActiveCfg = Release|Any CPU {9D63F716-C761-423B-BBC2-DC5F51081B43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D63F716-C761-423B-BBC2-DC5F51081B43}.Release|Any CPU.Build.0 = Release|Any CPU {9D63F716-C761-423B-BBC2-DC5F51081B43}.Release|Any CPU.Build.0 = Release|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B246B813-6218-4DD6-B48E-42D0FF5588B6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -33,6 +33,7 @@ namespace LawFirmView
// ищем нужный нам атрибут // ищем нужный нам атрибут
if (attribute is ColumnAttribute columnAttr) if (attribute is ColumnAttribute columnAttr)
{ {
column.DefaultCellStyle.Format = columnAttr.Format;
column.HeaderText = columnAttr.Title; column.HeaderText = columnAttr.Title;
column.Visible = columnAttr.Visible; column.Visible = columnAttr.Visible;
if (columnAttr.IsUseAutoSize) if (columnAttr.IsUseAutoSize)

View File

@ -38,11 +38,11 @@
this.buttonEdit = new System.Windows.Forms.Button(); this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button(); this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView(); this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnBlankName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnBlankName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.groupBoxBlanks.SuspendLayout(); this.groupBoxBlanks.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
@ -148,26 +148,6 @@
this.dataGridView.TabIndex = 0; this.dataGridView.TabIndex = 0;
this.dataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellContentClick); this.dataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellContentClick);
// //
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(356, 379);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(155, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(536, 379);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(155, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// ID // ID
// //
this.ID.HeaderText = "ID"; this.ID.HeaderText = "ID";
@ -192,6 +172,26 @@
this.ColumnCount.Name = "ColumnCount"; this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.Width = 125; this.ColumnCount.Width = 125;
// //
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(356, 379);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(155, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(536, 379);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(155, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormDocument // FormDocument
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);

166
LawFirm/LawFirm/FormMail.Designer.cs generated Normal file
View File

@ -0,0 +1,166 @@
namespace LawFirmView
{
partial class FormMail
{
/// <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()
{
label1 = new Label();
label2 = new Label();
textBoxHead = new TextBox();
textBoxBody = new TextBox();
buttonCancel = new Button();
buttonSave = new Button();
label3 = new Label();
labelHead = new Label();
labelBody = new Label();
labelFrom = new Label();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(539, 53);
label1.Name = "label1";
label1.Size = new Size(84, 20);
label1.TabIndex = 0;
label1.Text = "Заголовок:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(539, 115);
label2.Name = "label2";
label2.Size = new Size(104, 20);
label2.TabIndex = 1;
label2.Text = "Текст письма:";
//
// textBoxHead
//
textBoxHead.Location = new Point(547, 85);
textBoxHead.Name = "textBoxHead";
textBoxHead.Size = new Size(318, 27);
textBoxHead.TabIndex = 3;
//
// textBoxBody
//
textBoxBody.Location = new Point(547, 138);
textBoxBody.Name = "textBoxBody";
textBoxBody.Size = new Size(318, 27);
textBoxBody.TabIndex = 4;
//
// buttonCancel
//
buttonCancel.Location = new Point(664, 230);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(771, 230);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 6;
buttonSave.Text = "Отправить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(541, 9);
label3.Name = "label3";
label3.Size = new Size(82, 20);
label3.TabIndex = 7;
label3.Text = "Ваш ответ:";
//
// labelHead
//
labelHead.AutoSize = true;
labelHead.Location = new Point(12, 9);
labelHead.Name = "labelHead";
labelHead.Size = new Size(165, 20);
labelHead.TabIndex = 8;
labelHead.Text = "Заголовок сообщения";
//
// labelBody
//
labelBody.AutoSize = true;
labelBody.Location = new Point(12, 53);
labelBody.Name = "labelBody";
labelBody.Size = new Size(129, 20);
labelBody.TabIndex = 9;
labelBody.Text = "Текст сообщения";
//
// labelFrom
//
labelFrom.AutoSize = true;
labelFrom.Location = new Point(12, 234);
labelFrom.Name = "labelFrom";
labelFrom.Size = new Size(33, 20);
labelFrom.TabIndex = 10;
labelFrom.Text = "От: ";
//
// FormMail
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(877, 266);
Controls.Add(labelFrom);
Controls.Add(labelBody);
Controls.Add(labelHead);
Controls.Add(label3);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
Controls.Add(textBoxBody);
Controls.Add(textBoxHead);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormMail";
Text = "Ответ на письмо";
Load += FormMail_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private TextBox textBoxHead;
private TextBox textBoxBody;
private Button buttonCancel;
private Button buttonSave;
private Label label3;
private Label labelHead;
private Label labelBody;
private Label labelFrom;
}
}

View File

@ -0,0 +1,81 @@
using LawFirmBusinessLogic.MailWorker;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormMail : Form
{
private readonly ILogger _logger;
private readonly AbstractMailWorker _mailWorker;
private readonly IMessageInfoLogic _logic;
private MessageInfoViewModel _message;
public string MessageId { get; set; } = string.Empty;
public FormMail(ILogger<FormMail> logger, AbstractMailWorker mailWorker, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_mailWorker = mailWorker;
_logic = logic;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void buttonSave_Click(object sender, EventArgs e)
{
_mailWorker.MailSendAsync(new()
{
MailAddress = _message.SenderName,
Subject = textBoxHead.Text,
Text = textBoxBody.Text,
});
_logic.Update(new()
{
MessageId = MessageId,
Reply = textBoxBody.Text,
IsReaded = true,
});
MessageBox.Show("Успешно отправлен ответ", "Отправлен ответ", MessageBoxButtons.OK);
DialogResult = DialogResult.OK;
Close();
}
private void FormMail_Load(object sender, EventArgs e)
{
try
{
_message = _logic.ReadElement(new() { MessageId = MessageId });
if (_message == null) throw new ArgumentNullException("Письма с таким Id не существует");
labelHead.Text = _message.Subject;
labelBody.Text = _message.Body;
labelFrom.Text = $"От: {_message.SenderName}";
if (_message.IsReaded is false)
{
_logic.Update(new() { MessageId = MessageId, IsReaded = true, Reply = _message.Reply });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения собщения");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,62 +1,114 @@
namespace LawFirmView namespace LawFirmView
{ {
partial class FormMails partial class FormMails
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
dataGridView = new DataGridView(); dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); buttonPrevPage = new Button();
SuspendLayout(); buttonNextPage = new Button();
// labelPage = new Label();
// dataGridView buttonReply = new Button();
// ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; SuspendLayout();
dataGridView.Location = new Point(12, 12); //
dataGridView.Name = "dataGridView"; // dataGridView
dataGridView.RowHeadersWidth = 51; //
dataGridView.RowTemplate.Height = 29; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Size = new Size(776, 426); dataGridView.Location = new Point(12, 12);
dataGridView.TabIndex = 0; dataGridView.Name = "dataGridView";
// dataGridView.RowHeadersWidth = 51;
// FormMails dataGridView.RowTemplate.Height = 29;
// dataGridView.Size = new Size(776, 426);
AutoScaleDimensions = new SizeF(8F, 20F); dataGridView.TabIndex = 0;
AutoScaleMode = AutoScaleMode.Font; //
ClientSize = new Size(800, 450); // buttonPrevPage
Controls.Add(dataGridView); //
Name = "FormMails"; buttonPrevPage.Location = new Point(594, 444);
Text = "Письма"; buttonPrevPage.Name = "buttonPrevPage";
Load += FormMails_Load; buttonPrevPage.Size = new Size(94, 29);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); buttonPrevPage.TabIndex = 1;
ResumeLayout(false); buttonPrevPage.Text = "Пред.";
} buttonPrevPage.UseVisualStyleBackColor = true;
buttonPrevPage.Click += buttonPrevPage_Click;
//
// buttonNextPage
//
buttonNextPage.Location = new Point(694, 444);
buttonNextPage.Name = "buttonNextPage";
buttonNextPage.Size = new Size(94, 29);
buttonNextPage.TabIndex = 2;
buttonNextPage.Text = "След.";
buttonNextPage.UseVisualStyleBackColor = true;
buttonNextPage.Click += buttonNextPage_Click;
//
// labelPage
//
labelPage.AutoSize = true;
labelPage.Location = new Point(462, 448);
labelPage.Name = "labelPage";
labelPage.Size = new Size(91, 20);
labelPage.TabIndex = 3;
labelPage.Text = "Страница: 0";
//
// buttonReply
//
buttonReply.Location = new Point(12, 444);
buttonReply.Name = "buttonReply";
buttonReply.Size = new Size(94, 29);
buttonReply.TabIndex = 4;
buttonReply.Text = "Ответить";
buttonReply.UseVisualStyleBackColor = true;
buttonReply.Click += buttonReply_Click;
//
// FormMails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 475);
Controls.Add(buttonReply);
Controls.Add(labelPage);
Controls.Add(buttonNextPage);
Controls.Add(buttonPrevPage);
Controls.Add(dataGridView);
Name = "FormMails";
Text = "Письма";
Load += FormMails_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private DataGridView dataGridView; private DataGridView dataGridView;
} private Button buttonPrevPage;
private Button buttonNextPage;
private Label labelPage;
private Button buttonReply;
}
} }

View File

@ -1,4 +1,7 @@
using LawFirmContracts.BusinessLogicContracts; using LawFirm;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.DI;
using LawFirmContracts.ViewModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -12,31 +15,91 @@ using System.Windows.Forms;
namespace LawFirmView namespace LawFirmView
{ {
public partial class FormMails : Form public partial class FormMails : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic; private readonly IMessageInfoLogic _logic;
private int currentPage = 1;
public int pageSize = 2;
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic logic) public FormMails(ILogger<FormMails> logger, IMessageInfoLogic logic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
} buttonPrevPage.Enabled = false;
}
private void FormMails_Load(object sender, EventArgs e) private void FormMails_Load(object sender, EventArgs e)
{ {
try LoadMail();
{ }
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
private bool LoadMail()
{
try
{
dataGridView.FillAndConfigGrid(_logic.ReadList(new()
{
Page = currentPage,
PageSize = pageSize,
}));
_logger.LogInformation("Загрузка писем"); _logger.LogInformation("Загрузка писем");
}
catch (Exception ex) _logger.LogInformation("Загрузка писем");
{ labelPage.Text = $"Страница: {currentPage}";
_logger.LogError(ex, "Ошибка загрузки писем"); return true;
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, }
MessageBoxIcon.Error); catch (Exception ex)
} {
} _logger.LogError(ex, "Ошибка загрузки писем");
} MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
}
private void buttonPrevPage_Click(object sender, EventArgs e)
{
if (currentPage == 1)
{
return;
}
currentPage--;
if (LoadMail())
{
buttonNextPage.Enabled = true;
if (currentPage == 1)
{
buttonPrevPage.Enabled = false;
}
}
}
private void buttonNextPage_Click(object sender, EventArgs e)
{
currentPage++;
if (!LoadMail() || ((List<MessageInfoViewModel>)dataGridView.DataSource).Count == 0)
{
currentPage--;
LoadMail();
buttonNextPage.Enabled = false;
}
else
{
buttonPrevPage.Enabled = true;
}
}
private void buttonReply_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var form = DependencyManager.Instance.Resolve<FormMail>();
form.MessageId = (string)(dataGridView.SelectedRows[0].Cells["MessageId"].Value);
form.ShowDialog();
LoadMail();
}
}
}
} }

View File

@ -32,6 +32,7 @@
справочникиToolStripMenuItem = new ToolStripMenuItem(); справочникиToolStripMenuItem = new ToolStripMenuItem();
бланкиToolStripMenuItem = new ToolStripMenuItem(); бланкиToolStripMenuItem = new ToolStripMenuItem();
документыToolStripMenuItem = new ToolStripMenuItem(); документыToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem(); клиентыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem(); исполнителиToolStripMenuItem = new ToolStripMenuItem();
письмаToolStripMenuItem = new ToolStripMenuItem(); письмаToolStripMenuItem = new ToolStripMenuItem();
@ -39,11 +40,20 @@
списокДокументовToolStripMenuItem = new ToolStripMenuItem(); списокДокументовToolStripMenuItem = new ToolStripMenuItem();
бланкиПоДокументамToolStripMenuItem = new ToolStripMenuItem(); бланкиПоДокументамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
запускРаботToolStripMenuItem = new ToolStripMenuItem();
списокМагазиновToolStripMenuItem = new ToolStripMenuItem();
документыВМагазинахToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовПоДатеToolStripMenuItem = new ToolStripMenuItem();
запускРаботыToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView(); dataGridView = new DataGridView();
buttonCreateOrder = new Button(); buttonCreateOrder = new Button();
buttonSetToFinish = new Button(); buttonSetToFinish = new Button();
buttonUpdate = new Button(); buttonUpdate = new Button();
buttonSupplyShop = new Button();
buttonSellDocuments = new Button();
создатьБэкапToolStripMenuItem = new ToolStripMenuItem(); создатьБэкапToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
@ -52,7 +62,7 @@
// menuStrip // menuStrip
// //
menuStrip.ImageScalingSize = new Size(20, 20); menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem, создатьБэкапToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботыToolStripMenuItem, создатьБэкапToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1139, 28); menuStrip.Size = new Size(1139, 28);
@ -61,7 +71,7 @@
// //
// справочникиToolStripMenuItem // справочникиToolStripMenuItem
// //
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { бланкиToolStripMenuItem, документыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem }); справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { бланкиToolStripMenuItem, документыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem, магазиныToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24); справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники"; справочникиToolStripMenuItem.Text = "Справочники";
@ -86,6 +96,14 @@
клиентыToolStripMenuItem.Size = new Size(185, 26); клиентыToolStripMenuItem.Size = new Size(185, 26);
клиентыToolStripMenuItem.Text = "Клиенты"; клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(224, 26);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click;
// //
// исполнителиToolStripMenuItem // исполнителиToolStripMenuItem
// //
@ -103,7 +121,7 @@
// //
// отчетыToolStripMenuItem // отчетыToolStripMenuItem
// //
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДокументовToolStripMenuItem, бланкиПоДокументамToolStripMenuItem, списокЗаказовToolStripMenuItem }); отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДокументовToolStripMenuItem, бланкиПоДокументамToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, списокЗаказовПоДатеToolStripMenuItem, документыВМагазинахToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(73, 24); отчетыToolStripMenuItem.Size = new Size(73, 24);
отчетыToolStripMenuItem.Text = "Отчеты"; отчетыToolStripMenuItem.Text = "Отчеты";
@ -127,14 +145,34 @@
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(252, 26); списокЗаказовToolStripMenuItem.Size = new Size(252, 26);
списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;// списокМагазиновToolStripMenuItem
//
списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem";
списокМагазиновToolStripMenuItem.Size = new Size(259, 26);
списокМагазиновToolStripMenuItem.Text = "Список магазинов";
списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click;
// //
// запускРаботToolStripMenuItem // документыВМагазинахToolStripMenuItem
//
документыВМагазинахToolStripMenuItem.Name = окументыВМагазинахToolStripMenuItem";
документыВМагазинахToolStripMenuItem.Size = new Size(259, 26);
документыВМагазинахToolStripMenuItem.Text = "Документы в магазинах";
документыВМагазинахToolStripMenuItem.Click += документыВМагазинахToolStripMenuItem_Click;
//
// списокЗаказовПоДатеToolStripMenuItem
//
списокЗаказовПоДатеToolStripMenuItem.Name = "списокЗаказовПоДатеToolStripMenuItem";
списокЗаказовПоДатеToolStripMenuItem.Size = new Size(259, 26);
списокЗаказовПоДатеToolStripMenuItem.Text = "Список заказов по дате";
списокЗаказовПоДатеToolStripMenuItem.Click += списокЗаказовПоДатеToolStripMenuItem_Click;
//
// запускРаботыToolStripMenuItem
//
запускРаботыToolStripMenuItem.Name = апускРаботыToolStripMenuItem";
запускРаботыToolStripMenuItem.Size = new Size(125, 24);
запускРаботыToolStripMenuItem.Text = "Запуск работы";
запускРаботыToolStripMenuItem.Click += запускРаботыToolStripMenuItem_Click;
// //
запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
запускРаботToolStripMenuItem.Size = new Size(114, 24);
запускРаботToolStripMenuItem.Text = "Запуск работ";
запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
// //
// dataGridView // dataGridView
// //
@ -182,6 +220,26 @@
создатьБэкапToolStripMenuItem.Size = new Size(122, 24); создатьБэкапToolStripMenuItem.Size = new Size(122, 24);
создатьБэкапToolStripMenuItem.Text = "Создать бэкап"; создатьБэкапToolStripMenuItem.Text = "Создать бэкап";
создатьБэкапToolStripMenuItem.Click += создатьБэкапToolStripMenuItem_Click; создатьБэкапToolStripMenuItem.Click += создатьБэкапToolStripMenuItem_Click;
buttonSupplyShop.Location = new Point(933, 115);
buttonSupplyShop.Name = "buttonSupplyShop";
buttonSupplyShop.Size = new Size(194, 29);
buttonSupplyShop.TabIndex = 7;
buttonSupplyShop.Text = "Пополнение магазина";
buttonSupplyShop.UseVisualStyleBackColor = true;
buttonSupplyShop.Click += buttonSupplyShop_Click;
//
// buttonSellDocuments
//
buttonSellDocuments.Location = new Point(933, 150);
buttonSellDocuments.Name = "buttonSellDocuments";
buttonSellDocuments.Size = new Size(194, 29);
buttonSellDocuments.TabIndex = 8;
buttonSellDocuments.Text = "Продажа документов";
buttonSellDocuments.UseVisualStyleBackColor = true;
buttonSellDocuments.Click += buttonSellDocuments_Click;
// //
// FormMain // FormMain
// //
@ -191,6 +249,10 @@
Controls.Add(buttonUpdate); Controls.Add(buttonUpdate);
Controls.Add(buttonSetToFinish); Controls.Add(buttonSetToFinish);
Controls.Add(buttonCreateOrder); Controls.Add(buttonCreateOrder);
Controls.Add(buttonSellDocuments);
Controls.Add(buttonSupplyShop);
Controls.Add(dataGridView); Controls.Add(dataGridView);
Controls.Add(menuStrip); Controls.Add(menuStrip);
MainMenuStrip = menuStrip; MainMenuStrip = menuStrip;
@ -220,8 +282,16 @@
private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem; private ToolStripMenuItem запускРаботыToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem; private ToolStripMenuItem письмаToolStripMenuItem;
private ToolStripMenuItem создатьБэкапToolStripMenuItem; private ToolStripMenuItem создатьБэкапToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private Button buttonSupplyShop;
private Button buttonSellDocuments;
private ToolStripMenuItem списокМагазиновToolStripMenuItem;
private ToolStripMenuItem документыВМагазинахToolStripMenuItem;
private ToolStripMenuItem списокЗаказовПоДатеToolStripMenuItem;
} }
} }

View File

@ -104,6 +104,36 @@ namespace LawFirmView
} }
private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveShopsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void документыВМагазинахToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormReportShopDocuments>();
form.ShowDialog();
}
private void списокЗаказовПоДатеToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormReportDateOrders>();
form.ShowDialog();
}
private void магазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormShops>();
form.ShowDialog();
}
private void buttonCreateOrder_Click(object sender, EventArgs e) private void buttonCreateOrder_Click(object sender, EventArgs e)
{ {
var form = DependencyManager.Instance.Resolve<FormCreateOrder>(); var form = DependencyManager.Instance.Resolve<FormCreateOrder>();
@ -143,13 +173,24 @@ namespace LawFirmView
LoadData(); LoadData();
} }
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) private void buttonSupplyShop_Click(object sender, EventArgs e)
{ {
_workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>(),_orderLogic); var form = DependencyManager.Instance.Resolve<FormShopSupply>();
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); form.ShowDialog();
} }
private void buttonSellDocuments_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormShopSell>();
form.ShowDialog();
}
private void запускРаботыToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork(DependencyManager.Instance.Resolve<IImplementerLogic>(), _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e) private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var form = DependencyManager.Instance.Resolve<FormMails>(); var form = DependencyManager.Instance.Resolve<FormMails>();

View File

@ -0,0 +1,86 @@
namespace LawFirmView
{
partial class FormReportDateOrders
{
/// <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.panel = new System.Windows.Forms.Panel();
this.buttonCreateToPdf = new System.Windows.Forms.Button();
this.buttonCreateReport = new System.Windows.Forms.Button();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonCreateToPdf);
this.panel.Controls.Add(this.buttonCreateReport);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(978, 69);
this.panel.TabIndex = 1;
//
// buttonCreateToPdf
//
this.buttonCreateToPdf.Location = new System.Drawing.Point(769, 39);
this.buttonCreateToPdf.Name = "buttonCreateToPdf";
this.buttonCreateToPdf.Size = new System.Drawing.Size(190, 27);
this.buttonCreateToPdf.TabIndex = 5;
this.buttonCreateToPdf.Text = "PDF";
this.buttonCreateToPdf.UseVisualStyleBackColor = true;
this.buttonCreateToPdf.Click += new System.EventHandler(this.buttonCreateToPdf_Click);
//
// buttonCreateReport
//
this.buttonCreateReport.Location = new System.Drawing.Point(554, 39);
this.buttonCreateReport.Name = "buttonCreateReport";
this.buttonCreateReport.Size = new System.Drawing.Size(190, 27);
this.buttonCreateReport.TabIndex = 4;
this.buttonCreateReport.Text = "Сформировать";
this.buttonCreateReport.UseVisualStyleBackColor = true;
this.buttonCreateReport.Click += new System.EventHandler(this.buttonCreateReport_Click);
//
// FormReportDateOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(978, 450);
this.Controls.Add(this.panel);
this.Name = "FormReportDateOrders";
this.Text = "Заказы по датам";
this.panel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonCreateToPdf;
private Button buttonCreateReport;
}
}

View File

@ -0,0 +1,79 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormReportDateOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportDateOrders(ILogger<FormReportDateOrders> logger, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_logic = reportLogic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrdersByDate.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void buttonCreateReport_Click(object sender, EventArgs e)
{
try
{
var dataSource = _logic.GetDateOrders();
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на весь период по датам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCreateToPdf_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveDateOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка заказов на весь период по датам");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,107 @@
namespace LawFirmView
{
partial class FormReportShopDocuments
{
/// <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.buttonSaveToExcel = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.Shop = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Document = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonSaveToExcel
//
this.buttonSaveToExcel.Location = new System.Drawing.Point(12, 8);
this.buttonSaveToExcel.Name = "buttonSaveToExcel";
this.buttonSaveToExcel.Size = new System.Drawing.Size(176, 29);
this.buttonSaveToExcel.TabIndex = 0;
this.buttonSaveToExcel.Text = "Сохранить в Excel";
this.buttonSaveToExcel.UseVisualStyleBackColor = true;
this.buttonSaveToExcel.Click += new System.EventHandler(this.buttonSaveToExcel_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Shop,
this.Document,
this.Count});
this.dataGridView.Location = new System.Drawing.Point(12, 43);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(776, 395);
this.dataGridView.TabIndex = 1;
//
// Shop
//
this.Shop.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Shop.HeaderText = "Магазин";
this.Shop.MinimumWidth = 6;
this.Shop.Name = "Shop";
//
// Document
//
this.Document.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Document.HeaderText = "Документ";
this.Document.MinimumWidth = 6;
this.Document.Name = "Document";
//
// Count
//
this.Count.HeaderText = "Количество";
this.Count.MinimumWidth = 6;
this.Count.Name = "Count";
this.Count.Width = 125;
//
// FormReportShopDocuments
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonSaveToExcel);
this.Name = "FormReportShopDocuments";
this.Text = "Документы в магазинах";
this.Load += new System.EventHandler(this.FormReportShopDocuments_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonSaveToExcel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn Shop;
private DataGridViewTextBoxColumn Document;
private DataGridViewTextBoxColumn Count;
}
}

View File

@ -0,0 +1,85 @@
using LawFirmBusinessLogic.BusinessLogics;
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormReportShopDocuments : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShopDocuments(ILogger<FormReportShopDocuments> logger, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_logic = reportLogic;
}
private void buttonSaveToExcel_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog
{
Filter = "xlsx|*.xlsx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveShopDocumentsToExcelFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка магазинов с изделиями в них");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка магазинов с изделиями в них");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void FormReportShopDocuments_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShopDocuments();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" });
foreach (var listElem in elem.Documents)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Всего:", "", elem.Count });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка магазинов с изделиями в них");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка магазинов с изделиями в них");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,78 @@
<root>
<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="Shop.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Document.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Shop.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Document.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

210
LawFirm/LawFirm/FormShop.Designer.cs generated Normal file
View File

@ -0,0 +1,210 @@
namespace LawFirmView
{
partial class FormShop
{
/// <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.textBoxAddress = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.labelAddress = new System.Windows.Forms.Label();
this.labelName = new System.Windows.Forms.Label();
this.labelOpeningDate = new System.Windows.Forms.Label();
this.dateTimePicker = new System.Windows.Forms.DateTimePicker();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ColumnId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDocumentName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.labelMaxCount = new System.Windows.Forms.Label();
this.textBoxMaxCountDocs = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(100, 45);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(315, 27);
this.textBoxAddress.TabIndex = 7;
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(100, 12);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(315, 27);
this.textBoxName.TabIndex = 6;
//
// labelAddress
//
this.labelAddress.AutoSize = true;
this.labelAddress.Location = new System.Drawing.Point(14, 51);
this.labelAddress.Name = "labelAddress";
this.labelAddress.Size = new System.Drawing.Size(54, 20);
this.labelAddress.TabIndex = 5;
this.labelAddress.Text = "Адрес:";
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(14, 15);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(80, 20);
this.labelName.TabIndex = 4;
this.labelName.Text = "Название:";
//
// labelOpeningDate
//
this.labelOpeningDate.AutoSize = true;
this.labelOpeningDate.Location = new System.Drawing.Point(14, 86);
this.labelOpeningDate.Name = "labelOpeningDate";
this.labelOpeningDate.Size = new System.Drawing.Size(126, 20);
this.labelOpeningDate.TabIndex = 8;
this.labelOpeningDate.Text = "Время открытия:";
//
// dateTimePicker
//
this.dateTimePicker.Location = new System.Drawing.Point(165, 81);
this.dateTimePicker.Name = "dateTimePicker";
this.dateTimePicker.Size = new System.Drawing.Size(250, 27);
this.dateTimePicker.TabIndex = 9;
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnId,
this.ColumnDocumentName,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(14, 173);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(401, 265);
this.dataGridView.TabIndex = 10;
//
// ColumnId
//
this.ColumnId.HeaderText = "ID";
this.ColumnId.MinimumWidth = 6;
this.ColumnId.Name = "ColumnId";
this.ColumnId.Visible = false;
this.ColumnId.Width = 125;
//
// ColumnDocumentName
//
this.ColumnDocumentName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnDocumentName.HeaderText = "Документ";
this.ColumnDocumentName.MinimumWidth = 6;
this.ColumnDocumentName.Name = "ColumnDocumentName";
//
// ColumnCount
//
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.MinimumWidth = 6;
this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.Width = 125;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(228, 448);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(155, 29);
this.buttonCancel.TabIndex = 12;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(48, 448);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(155, 29);
this.buttonSave.TabIndex = 11;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// labelMaxCount
//
this.labelMaxCount.AutoSize = true;
this.labelMaxCount.Location = new System.Drawing.Point(18, 128);
this.labelMaxCount.Name = "labelMaxCount";
this.labelMaxCount.Size = new System.Drawing.Size(216, 20);
this.labelMaxCount.TabIndex = 13;
this.labelMaxCount.Text = "Макс. количество документов";
//
// textBoxMaxCountDocs
//
this.textBoxMaxCountDocs.Location = new System.Drawing.Point(240, 128);
this.textBoxMaxCountDocs.Name = "textBoxMaxCountDocs";
this.textBoxMaxCountDocs.Size = new System.Drawing.Size(175, 27);
this.textBoxMaxCountDocs.TabIndex = 14;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(445, 489);
this.Controls.Add(this.textBoxMaxCountDocs);
this.Controls.Add(this.labelMaxCount);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.dateTimePicker);
this.Controls.Add(this.labelOpeningDate);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelAddress);
this.Controls.Add(this.labelName);
this.Name = "FormShop";
this.Text = "Магазин";
this.Load += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxAddress;
private TextBox textBoxName;
private Label labelAddress;
private Label labelName;
private Label labelOpeningDate;
private DateTimePicker dateTimePicker;
private DataGridView dataGridView;
private Button buttonCancel;
private Button buttonSave;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnDocumentName;
private DataGridViewTextBoxColumn ColumnCount;
private Label labelMaxCount;
private TextBox textBoxMaxCountDocs;
}
}

144
LawFirm/LawFirm/FormShop.cs Normal file
View File

@ -0,0 +1,144 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormShop : Form
{
private readonly IShopLogic _logic;
private readonly ILogger _logger;
private Dictionary<int, (IDocumentModel, int)> _shopDocuments;
private int? _id;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopDocuments = new();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var view = _logic.ReadElement(new ShopSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.Name;
textBoxAddress.Text = view.Adress;
_shopDocuments = view.ShopDocuments ?? new Dictionary<int, (IDocumentModel, int)>();
textBoxMaxCountDocs.Text = view.MaxCountDocuments.ToString();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка документов магазина");
try
{
if (_shopDocuments != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _shopDocuments)
{
dataGridView.Rows.Add(new object[]
{
pc.Key,
pc.Value.Item1.DocumentName,
pc.Value.Item2
}
);
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки документов магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxMaxCountDocs.Text))
{
MessageBox.Show("Заполните макс. количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
Name = textBoxName.Text,
Adress = textBoxAddress.Text,
OpeningDate = dateTimePicker.Value.Date,
MaxCountDocuments = Convert.ToInt32(textBoxMaxCountDocs.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<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="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnDocumentName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

119
LawFirm/LawFirm/FormShopSell.Designer.cs generated Normal file
View File

@ -0,0 +1,119 @@
namespace LawFirmView
{
partial class FormShopSell
{
/// <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.labelCount = new System.Windows.Forms.Label();
this.labelDocument = new System.Windows.Forms.Label();
this.comboBoxDocument = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSell = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(23, 76);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// labelDocument
//
this.labelDocument.AutoSize = true;
this.labelDocument.Location = new System.Drawing.Point(23, 24);
this.labelDocument.Name = "labelDocument";
this.labelDocument.Size = new System.Drawing.Size(79, 20);
this.labelDocument.TabIndex = 2;
this.labelDocument.Text = "Документ:";
//
// comboBoxDocument
//
this.comboBoxDocument.FormattingEnabled = true;
this.comboBoxDocument.Location = new System.Drawing.Point(124, 24);
this.comboBoxDocument.Name = "comboBoxDocument";
this.comboBoxDocument.Size = new System.Drawing.Size(278, 28);
this.comboBoxDocument.TabIndex = 4;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(124, 73);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(158, 27);
this.textBoxCount.TabIndex = 5;
//
// buttonSell
//
this.buttonSell.Location = new System.Drawing.Point(188, 142);
this.buttonSell.Name = "buttonSell";
this.buttonSell.Size = new System.Drawing.Size(94, 29);
this.buttonSell.TabIndex = 6;
this.buttonSell.Text = "Продажа";
this.buttonSell.UseVisualStyleBackColor = true;
this.buttonSell.Click += new System.EventHandler(this.buttonSell_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(308, 142);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormShopSell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(459, 198);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSell);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxDocument);
this.Controls.Add(this.labelDocument);
this.Controls.Add(this.labelCount);
this.Name = "FormShopSell";
this.Text = "Продажа из магазина";
this.Load += new System.EventHandler(this.FormShopSell_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelCount;
private Label labelDocument;
private ComboBox comboBoxDocument;
private TextBox textBoxCount;
private Button buttonSell;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,96 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormShopSell : Form
{
private readonly ILogger _logger;
private readonly IDocumentLogic _logicD;
private readonly IShopLogic _logicS;
public FormShopSell(ILogger<FormShopSell> logger, IDocumentLogic logicD, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicD = logicD;
_logicS = logicS;
}
private void FormShopSell_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка документов для продажи");
try
{
var list = _logicD.ReadList(null);
if (list != null)
{
comboBoxDocument.DisplayMember = "DocumentName";
comboBoxDocument.ValueMember = "Id";
comboBoxDocument.DataSource = list;
comboBoxDocument.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка документов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSell_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxDocument.SelectedValue == null)
{
MessageBox.Show("Выберите документ", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание продажи");
try
{
var operationResult = _logicS.SellDocument(
new DocumentBindingModel
{
Id = Convert.ToInt32(comboBoxDocument.SelectedValue)
},
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при создании продажи. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания продажи");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

144
LawFirm/LawFirm/FormShopSupply.Designer.cs generated Normal file
View File

@ -0,0 +1,144 @@
namespace LawFirmView
{
partial class FormShopSupply
{
/// <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.labelShop = new System.Windows.Forms.Label();
this.labelDocument = new System.Windows.Forms.Label();
this.labelDocumentCount = new System.Windows.Forms.Label();
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.comboBoxDocument = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(26, 19);
this.labelShop.Name = "labelShop";
this.labelShop.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.labelShop.Size = new System.Drawing.Size(72, 20);
this.labelShop.TabIndex = 0;
this.labelShop.Text = "Магазин:";
//
// labelDocument
//
this.labelDocument.AutoSize = true;
this.labelDocument.Location = new System.Drawing.Point(26, 72);
this.labelDocument.Name = "labelDocument";
this.labelDocument.Size = new System.Drawing.Size(79, 20);
this.labelDocument.TabIndex = 1;
this.labelDocument.Text = "Документ:";
//
// labelDocumentCount
//
this.labelDocumentCount.AutoSize = true;
this.labelDocumentCount.Location = new System.Drawing.Point(26, 122);
this.labelDocumentCount.Name = "labelDocumentCount";
this.labelDocumentCount.Size = new System.Drawing.Size(93, 20);
this.labelDocumentCount.TabIndex = 2;
this.labelDocumentCount.Text = "Количество:";
//
// comboBoxShop
//
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(148, 19);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(251, 28);
this.comboBoxShop.TabIndex = 3;
//
// comboBoxDocument
//
this.comboBoxDocument.FormattingEnabled = true;
this.comboBoxDocument.Location = new System.Drawing.Point(148, 69);
this.comboBoxDocument.Name = "comboBoxDocument";
this.comboBoxDocument.Size = new System.Drawing.Size(251, 28);
this.comboBoxDocument.TabIndex = 4;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(148, 122);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(125, 27);
this.textBoxCount.TabIndex = 5;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(305, 183);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 9;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(205, 183);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 8;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// FormShopSupply
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(436, 243);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxDocument);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.labelDocumentCount);
this.Controls.Add(this.labelDocument);
this.Controls.Add(this.labelShop);
this.Name = "FormShopSupply";
this.Text = "Пополнение магазина";
this.Load += new System.EventHandler(this.FormShopSupply_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelShop;
private Label labelDocument;
private Label labelDocumentCount;
private ComboBox comboBoxShop;
private ComboBox comboBoxDocument;
private TextBox textBoxCount;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,125 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormShopSupply : Form
{
private readonly ILogger _logger;
private readonly IDocumentLogic _logicD;
private readonly IShopLogic _logicS;
public FormShopSupply(ILogger<FormShopSupply> logger, IDocumentLogic logicD, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicD = logicD;
_logicS = logicS;
}
private void FormShopSupply_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка документов для пополнения");
try
{
var list = _logicD.ReadList(null);
if (list != null)
{
comboBoxDocument.DisplayMember = "DocumentName";
comboBoxDocument.ValueMember = "Id";
comboBoxDocument.DataSource = list;
comboBoxDocument.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка документов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка магазинов для пополнения");
try
{
var list = _logicS.ReadList(null);
if (list != null)
{
comboBoxShop.DisplayMember = "Name";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = list;
comboBoxShop.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxDocument.SelectedValue == null)
{
MessageBox.Show("Выберите документ", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxShop.SelectedValue== null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание поставки");
try
{
var operationResult = _logicS.SupplyDocuments(
new ShopSearchModel
{
Id = Convert.ToInt32(comboBoxShop.SelectedValue),
Name = comboBoxShop.Text
},
new DocumentBindingModel
{
Id = Convert.ToInt32(comboBoxDocument.SelectedValue),
DocumentName = comboBoxDocument.Text
},
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания поставки");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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>

115
LawFirm/LawFirm/FormShops.Designer.cs generated Normal file
View File

@ -0,0 +1,115 @@
namespace LawFirmView
{
partial class FormShops
{
/// <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.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(561, 426);
this.dataGridView.TabIndex = 0;
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(627, 409);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(152, 29);
this.buttonUpdate.TabIndex = 9;
this.buttonUpdate.Text = "Обновить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(627, 82);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(152, 29);
this.buttonDelete.TabIndex = 8;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
//
// buttonEdit
//
this.buttonEdit.Location = new System.Drawing.Point(627, 47);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(152, 29);
this.buttonEdit.TabIndex = 7;
this.buttonEdit.Text = "Изменить";
this.buttonEdit.UseVisualStyleBackColor = true;
this.buttonEdit.Click += new System.EventHandler(this.buttonEdit_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(627, 12);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(152, 29);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// FormShops
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonEdit);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormShops";
this.Text = "Магазины";
this.Load += new System.EventHandler(this.FormShops_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonEdit;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,113 @@
using LawFirm;
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.DI;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LawFirmView
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormDocuments> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
dataGridView.FillAndConfigGrid(_logic.ReadList(null));
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
LoadData();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var form = DependencyManager.Instance.Resolve<FormShop>();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void buttonEdit_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = DependencyManager.Instance.Resolve<FormShop>();
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonDelete_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить магазин?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление магазина");
try
{
if (!_logic.Delete(new ShopBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -65,22 +65,6 @@ namespace LawFirm
option.AddNLog("nlog.config"); option.AddNLog("nlog.config");
}); });
DependencyManager.Instance.RegisterType<IBlankLogic, BlankLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<IDocumentLogic, DocumentLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(isSingle: true);
DependencyManager.Instance.RegisterType<FormMain>(); DependencyManager.Instance.RegisterType<FormMain>();
DependencyManager.Instance.RegisterType<FormBlank>(); DependencyManager.Instance.RegisterType<FormBlank>();
DependencyManager.Instance.RegisterType<FormBlanks>(); DependencyManager.Instance.RegisterType<FormBlanks>();
@ -95,7 +79,14 @@ namespace LawFirm
DependencyManager.Instance.RegisterType<FormImplementer>(); DependencyManager.Instance.RegisterType<FormImplementer>();
DependencyManager.Instance.RegisterType<FormMails>(); DependencyManager.Instance.RegisterType<FormMails>();
} DependencyManager.Instance.RegisterType<FormMail>();
DependencyManager.Instance.RegisterType<FormReportShopDocuments>();
DependencyManager.Instance.RegisterType<FormReportDateOrders>();
DependencyManager.Instance.RegisterType<FormShop>();
DependencyManager.Instance.RegisterType<FormShops>();
DependencyManager.Instance.RegisterType<FormShopSupply>();
DependencyManager.Instance.RegisterType<FormShopSell>();
}
} }
} }

View File

@ -0,0 +1,424 @@
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<AutoRefresh>0</AutoRefresh>
<DataSources>
<DataSource Name="LawFirmContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>10791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetOrders">
<Query>
<DataSourceName>LawFirmContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="DateCreate">
<DataField>DateCreate</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="CountOrders">
<DataField>CountOrders</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
<Field Name="SumOrders">
<DataField>SumOrders</DataField>
<rd:TypeName>System.Double</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>LawFirmContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportDateOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>LawFirmContracts.ViewModels.ReportDateOrdersViewModel, LawFirmContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Заказы</Value>
<Style>
<FontSize>16pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>1cm</Height>
<Width>21cm</Width>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>3cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3cm</Width>
</TablixColumn>
<TablixColumn>
<Width>7cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Textbox1">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox1</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox3">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Количество</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox3</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox2">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Сумма</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox2</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="DateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!DateCreate.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>DateCreate</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="CountOrders">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!CountOrders.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>CountOrders</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="SumOrders">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!SumOrders.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>SumOrders</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
<TablixColumnHierarchy>
<TablixMembers>
<TablixMember />
<TablixMember />
<TablixMember />
</TablixMembers>
</TablixColumnHierarchy>
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
</TablixMember>
<TablixMember>
<Group Name="Подробности" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
<DataSetName>DataSetOrders</DataSetName>
<Top>2.48391cm</Top>
<Left>0.55245cm</Left>
<Height>1.2cm</Height>
<Width>13cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>Double</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxTotalSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Всего:</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>8.55245cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="SumTotal">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!SumOrders.Value, "DataSetOrders")</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>11.05245cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>3</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</ReportItems>
<Height>5.72875cm</Height>
<Style />
</Body>
<Width>21cm</Width>
<Page>
<PageHeight>29.7cm</PageHeight>
<PageWidth>21cm</PageWidth>
<LeftMargin>2cm</LeftMargin>
<RightMargin>2cm</RightMargin>
<TopMargin>2cm</TopMargin>
<BottomMargin>2cm</BottomMargin>
<ColumnSpacing>0.13cm</ColumnSpacing>
<Style />
</Page>
</ReportSection>
</ReportSections>
<ReportParameters>
<ReportParameter Name="ReportParameterPeriod">
<DataType>String</DataType>
<Nullable>true</Nullable>
<Prompt>ReportParameter1</Prompt>
</ReportParameter>
</ReportParameters>
<ReportParametersLayout>
<GridLayoutDefinition>
<NumberOfColumns>4</NumberOfColumns>
<NumberOfRows>2</NumberOfRows>
<CellDefinitions>
<CellDefinition>
<ColumnIndex>0</ColumnIndex>
<RowIndex>0</RowIndex>
<ParameterName>ReportParameterPeriod</ParameterName>
</CellDefinition>
</CellDefinitions>
</GridLayoutDefinition>
</ReportParametersLayout>
<rd:ReportUnitType>Cm</rd:ReportUnitType>
<rd:ReportID>2de0031a-4d17-449d-922d-d9fc54572312</rd:ReportID>
</Report>

View File

@ -32,7 +32,18 @@ namespace LawFirmBusinessLogic.BusinessLogics
return true; return true;
} }
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model) public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model)
{
var message = _messageInfoStorage.GetElement(model);
if (message == null)
{
_logger.LogWarning("Read message operation failed");
return null;
}
return message;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{ {
_logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId);
var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model);
@ -44,5 +55,15 @@ namespace LawFirmBusinessLogic.BusinessLogics
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
}
public bool Update(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
}
} }

View File

@ -5,6 +5,7 @@ using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts; using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels; using LawFirmContracts.ViewModels;
using LawFirmDataModels.Enums; using LawFirmDataModels.Enums;
using LawFirmDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -18,13 +19,20 @@ namespace LawFirmBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IDocumentStorage _documentStorage;
private readonly AbstractMailWorker _mailWorker; private readonly AbstractMailWorker _mailWorker;
private readonly IClientLogic _clientLogic; private readonly IClientLogic _clientLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IDocumentStorage documentStorage, IShopStorage shopStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_shopLogic = shopLogic;
_documentStorage = documentStorage;
_shopStorage = shopStorage;
_mailWorker = mailWorker; _mailWorker = mailWorker;
_clientLogic = clientLogic; _clientLogic = clientLogic;
} }
@ -79,11 +87,29 @@ namespace LawFirmBusinessLogic.BusinessLogics
} }
CheckModel(model, false); CheckModel(model, false);
if (model.Status + 1 != newStatus) if (model.Status + 1 != newStatus && model.Status!=OrderStatus.Ожидание)
{ {
_logger.LogWarning("Status update to " + newStatus.ToString() +" operation failed. Order status incorrect."); _logger.LogWarning("Status update to " + newStatus.ToString() +" operation failed. Order status incorrect.");
return false; return false;
} }
if (newStatus == OrderStatus.Готов)
{
var document = _documentStorage.GetElement(new DocumentSearchModel() { Id = model.DocumentId});
if (document == null)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Document not found.");
return false;
}
if (CheckThenSupplyMany(document, model.Count) == false)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Shop supply error.");
model.Status = OrderStatus.Ожидание;
_orderStorage.Update(model);
return false;
}
}
model.Status = newStatus; model.Status = newStatus;
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
var result = _orderStorage.Update(model); var result = _orderStorage.Update(model);
@ -97,6 +123,67 @@ namespace LawFirmBusinessLogic.BusinessLogics
return true; return true;
} }
public bool CheckThenSupplyMany(IDocumentModel document, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. Document count < 0.");
return false;
}
int freeSpace = 0;
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace += shop.MaxCountDocuments;
foreach (var doc in shop.ShopDocuments)
{
freeSpace -= doc.Value.Item2;
}
}
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new docs in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCountDocuments;
foreach (var doc in shop.ShopDocuments)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.SupplyDocuments(new() { Id = shop.Id }, document, count)) count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.SupplyDocuments(new() { Id = shop.Id }, document, freeSpace)) count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
public bool TakeOrderInWork(OrderBindingModel model) public bool TakeOrderInWork(OrderBindingModel model)
{ {
return StatusUpdate(model, OrderStatus.Выполняется); return StatusUpdate(model, OrderStatus.Выполняется);

View File

@ -18,14 +18,16 @@ namespace LawFirmBusinessLogic.BusinessLogics
private readonly IBlankStorage _blankStorage; private readonly IBlankStorage _blankStorage;
private readonly IDocumentStorage _documentStorage; private readonly IDocumentStorage _documentStorage;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf; private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IDocumentStorage documentStorage, IBlankStorage blankStorage, IOrderStorage orderStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) public ReportLogic(IDocumentStorage documentStorage, IBlankStorage blankStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{ {
_documentStorage = documentStorage; _documentStorage = documentStorage;
_blankStorage = blankStorage; _blankStorage = blankStorage;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_shopStorage = shopStorage;
_saveToExcel = saveToExcel; _saveToExcel = saveToExcel;
_saveToWord = saveToWord; _saveToWord = saveToWord;
_saveToPdf = saveToPdf; _saveToPdf = saveToPdf;
@ -104,5 +106,64 @@ namespace LawFirmBusinessLogic.BusinessLogics
}); });
} }
public void SaveShopsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateTableDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список магазинов",
Shops = _shopStorage.GetFullList()
});
}
public void SaveShopDocumentsToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateShopReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Загруженность магазинов",
ShopDocuments = GetShopDocuments()
});
}
public List<ReportShopDocumentsViewModel> GetShopDocuments()
{
var shops = _shopStorage.GetFullList();
var list = new List<ReportShopDocumentsViewModel>();
foreach (var shop in shops)
{
var record = new ReportShopDocumentsViewModel
{
ShopName = shop.Name,
Documents = new List<Tuple<string, int>>(),
Count = 0
};
foreach (var docCount in shop.ShopDocuments.Values)
{
record.Documents.Add(new Tuple<string, int>(docCount.Item1.DocumentName, docCount.Item2));
record.Count += docCount.Item2;
}
list.Add(record);
}
return list;
}
public List<ReportDateOrdersViewModel> GetDateOrders()
{
return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportDateOrdersViewModel
{
DateCreate = x.Key,
CountOrders = x.Count(),
SumOrders = x.Sum(y => y.Sum)
}).ToList();
}
public void SaveDateOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateReportDateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Заказы по датам",
DateOrders = GetDateOrders()
});
}
} }
} }

View File

@ -0,0 +1,189 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmBusinessLogic.BusinessLogics
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Shop Name:{0}.ID:{1}", model.Name, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. Shop Name:{0}.ID:{1} ", model?.Name, model?.Id);
var list = (model == null) ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool SupplyDocuments(ShopSearchModel model, IDocumentModel document, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
if (count <= 0)
{
throw new ArgumentNullException("Count of documents in supply myst be more than 0", nameof(count));
}
var shopElement = _shopStorage.GetElement(model);
if (shopElement == null)
{
_logger.LogWarning("Required shop element not found in storage");
return false;
}
_logger.LogInformation("Shop element found. ID: {0}, Name: {1}", shopElement.Id, shopElement.Name);
var countDocs = 0;
foreach (var doc in shopElement.ShopDocuments)
{
countDocs += doc.Value.Item2;
}
if (shopElement.MaxCountDocuments - countDocs >= count)
{
if (shopElement.ShopDocuments.TryGetValue(document.Id, out var sameDocument))
{
shopElement.ShopDocuments[document.Id] = (document, sameDocument.Item2 + count);
_logger.LogInformation("Same document found by supply. Added {0} of {1} in {2} shop", count, document.DocumentName, shopElement.Name);
}
else
{
shopElement.ShopDocuments[document.Id] = (document, count);
_logger.LogInformation("New document added by supply. Added {0} of {1} in {2} shop", count, document.DocumentName, shopElement.Name);
}
_shopStorage.Update(new()
{
Id = shopElement.Id,
Name = shopElement.Name,
Adress = shopElement.Adress,
OpeningDate = shopElement.OpeningDate,
ShopDocuments = shopElement.ShopDocuments,
MaxCountDocuments = shopElement.MaxCountDocuments
});
}
else
{
_logger.LogWarning("Required shop is overflowed");
return false;
}
return true;
}
public bool SellDocument(IDocumentModel document, int count)
{;
return _shopStorage.SellDocument(document, count);
}
public bool Create(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия магазина!", nameof(model.Name));
}
if (model.MaxCountDocuments < 0)
{
throw new InvalidOperationException("Магазин с отрицательным количеством максимального количества документов!");
}
_logger.LogInformation("Shop. Name: {0}, Adress: {1}, ID: {2}", model.Name, model.Adress, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
}
}

View File

@ -35,7 +35,12 @@ namespace LawFirmBusinessLogic.BusinessLogics
_logger.LogWarning("DoWork. Implementers is null"); _logger.LogWarning("DoWork. Implementers is null");
return; return;
} }
var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
if (orders != null) {
orders.AddRange(_orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Выполняется }) ?? new());
orders.AddRange(_orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Ожидание }) ?? new());
}
if (orders == null || orders.Count == 0) if (orders == null || orders.Count == 0)
{ {
_logger.LogWarning("DoWork. Orders is null or empty"); _logger.LogWarning("DoWork. Orders is null or empty");
@ -54,6 +59,9 @@ namespace LawFirmBusinessLogic.BusinessLogics
{ {
return; return;
} }
await RunWaitingOrder(implementer);
await RunOrderInWork(implementer); await RunOrderInWork(implementer);
await Task.Run(() => await Task.Run(() =>
@ -100,44 +108,82 @@ namespace LawFirmBusinessLogic.BusinessLogics
private async Task RunOrderInWork(ImplementerViewModel implementer) private async Task RunOrderInWork(ImplementerViewModel implementer)
{ {
if (_orderLogic == null || implementer == null) if (_orderLogic == null || implementer == null)
{ {
return; return;
} }
try try
{ {
// Выбираем из всех заказов тот, который выполняется данным исполнителем
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{ {
ImplementerId = implementer.Id, ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется Status = OrderStatus.Выполняется
})); }));
if (runOrder == null) if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = runOrder.Id,
ImplementerId = implementer.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
private async Task RunWaitingOrder(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var order = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Ожидание
}));
if (order == null)
{ {
return; return;
} }
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id); _logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.DeliveryOrder(new OrderBindingModel _orderLogic.DeliveryOrder(new OrderBindingModel
{ {
Id = runOrder.Id Id = order.Id,
ImplementerId = implementer.Id
}); });
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100)); Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
} }
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
_logger.LogWarning(ex, "Error try get work"); _logger.LogWarning(ex, "Error try get work");
} }
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error while do work"); _logger.LogError(ex, "Error while do work");
throw; throw;
} }
} }
} }
} }

View File

@ -18,4 +18,8 @@
<ProjectReference Include="..\LawFirmContracts\LawFirmContracts.csproj" /> <ProjectReference Include="..\LawFirmContracts\LawFirmContracts.csproj" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)ImplementationExtensions\*.dll&quot;" />
</Target>
</Project> </Project>

View File

@ -0,0 +1,39 @@
using LawFirmBusinessLogic.BusinessLogics;
using LawFirmBusinessLogic.MailWorker;
using LawFirmBusinessLogic.OfficePackage.Implements;
using LawFirmBusinessLogic.OfficePackage;
using LawFirmContracts.BusinessLogicContracts;
using LawFirmContracts.DI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmBusinessLogic
{
public class LogicImplementationExtension : ILogicImplementationExtension
{
public int Priority => 0;
public void RegisterServices()
{
DependencyManager.Instance.RegisterType<IBlankLogic, BlankLogic>();
DependencyManager.Instance.RegisterType<IOrderLogic, OrderLogic>();
DependencyManager.Instance.RegisterType<IDocumentLogic, DocumentLogic>();
DependencyManager.Instance.RegisterType<IReportLogic, ReportLogic>();
DependencyManager.Instance.RegisterType<IClientLogic, ClientLogic>();
DependencyManager.Instance.RegisterType<IImplementerLogic, ImplementerLogic>();
DependencyManager.Instance.RegisterType<IWorkProcess, WorkModeling>();
DependencyManager.Instance.RegisterType<IMessageInfoLogic, MessageInfoLogic>();
DependencyManager.Instance.RegisterType<IBackUpLogic, BackUpLogic>();
DependencyManager.Instance.RegisterType<IShopLogic, ShopLogic>();
DependencyManager.Instance.RegisterType<AbstractSaveToWord, SaveToWord>();
DependencyManager.Instance.RegisterType<AbstractSaveToExcel, SaveToExcel>();
DependencyManager.Instance.RegisterType<AbstractSaveToPdf, SaveToPdf>();
DependencyManager.Instance.RegisterType<AbstractMailWorker, MailKitWorker>(isSingle: true);
}
}
}

View File

@ -27,6 +27,7 @@ namespace LawFirmBusinessLogic.OfficePackage
CellToName = "C1" CellToName = "C1"
}); });
uint rowIndex = 2; uint rowIndex = 2;
foreach (var pc in info.DocumentBlanks) foreach (var pc in info.DocumentBlanks)
{ {
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
@ -73,6 +74,69 @@ namespace LawFirmBusinessLogic.OfficePackage
} }
SaveExcel(info); SaveExcel(info);
} }
public void CreateShopReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var pc in info.ShopDocuments)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (DocumentName, Count) in pc.Documents)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = DocumentName,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = pc.Count.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
/// Создание excel-файла /// Создание excel-файла
protected abstract void CreateExcel(ExcelInfo info); protected abstract void CreateExcel(ExcelInfo info);
/// Добавляем новую ячейку в лист /// Добавляем новую ячейку в лист

View File

@ -47,6 +47,39 @@ namespace LawFirmBusinessLogic.OfficePackage
}); });
SavePdf(info); SavePdf(info);
} }
public void CreateReportDateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "3cm", "3cm", "7cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата", "Количество", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.DateOrders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.DateCreate.ToShortDateString(), order.CountOrders.ToString(), order.SumOrders.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph
{
Text = $"Итого: {info.DateOrders.Sum(x => x.SumOrders)}\t",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
SavePdf(info);
}
/// Создание pdf-файла /// Создание pdf-файла
protected abstract void CreatePdf(PdfInfo info); protected abstract void CreatePdf(PdfInfo info);
/// Создание параграфа с текстом /// Создание параграфа с текстом

View File

@ -39,11 +39,37 @@ namespace LawFirmBusinessLogic.OfficePackage
} }
SaveWord(info); SaveWord(info);
} }
public void CreateTableDoc(WordInfo wordInfo)
{
CreateWord(wordInfo);
var list = new List<string>();
foreach (var shop in wordInfo.Shops)
{
list.Add(shop.Name);
list.Add(shop.Adress);
list.Add(shop.OpeningDate.ToString());
}
var wordTable = new WordTable
{
Headers = new List<string> {
"Название",
"Адрес",
"Дата открытия"},
Texts = list
};
CreateTable(wordTable);
SaveWord(wordInfo);
}
/// Создание doc-файла /// Создание doc-файла
protected abstract void CreateWord(WordInfo info); protected abstract void CreateWord(WordInfo info);
/// Создание абзаца с текстом /// Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph); protected abstract void CreateParagraph(WordParagraph paragraph);
/// Сохранение файла /// Сохранение файла
protected abstract void SaveWord(WordInfo info); protected abstract void SaveWord(WordInfo info);
protected abstract void CreateTable(WordTable info);
} }
} }

View File

@ -12,5 +12,6 @@ namespace LawFirmBusinessLogic.OfficePackage.HelperModels
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
public List<ReportDocumentBlankViewModel> DocumentBlanks { get; set; } = new(); public List<ReportDocumentBlankViewModel> DocumentBlanks { get; set; } = new();
public List<ReportShopDocumentsViewModel> ShopDocuments { get; set; } = new();
} }
} }

View File

@ -14,5 +14,6 @@ namespace LawFirmBusinessLogic.OfficePackage.HelperModels
public DateTime DateFrom { get; set; } public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; } public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new(); public List<ReportOrdersViewModel> Orders { get; set; } = new();
public List<ReportDateOrdersViewModel> DateOrders { get; set; } = new();
} }
} }

View File

@ -12,5 +12,6 @@ namespace LawFirmBusinessLogic.OfficePackage.HelperModels
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
public List<DocumentViewModel> Documents { get; set; } = new(); public List<DocumentViewModel> Documents { get; set; } = new();
public List<ShopViewModel> Shops { get; set; } = new();
} }
} }

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmBusinessLogic.OfficePackage.HelperModels
{
public class WordTable
{
public List<string> Headers { get; set; } = new();
public List<string> Texts { get; set; } = new();
}
}

View File

@ -112,5 +112,86 @@ namespace LawFirmBusinessLogic.OfficePackage.Implements
_wordDocument.MainDocumentPart!.Document.Save(); _wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close(); _wordDocument.Close();
} }
protected override void CreateTable(WordTable table)
{
if (_docBody == null || table == null)
{
return;
}
Table tab = new Table();
TableProperties props = 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
}
)
);
tab.AppendChild<TableProperties>(props);
TableGrid tableGrid = new TableGrid();
for (int i = 0; i < table.Headers.Count; i++)
{
tableGrid.AppendChild(new GridColumn());
}
tab.AppendChild(tableGrid);
TableRow tableRow = new TableRow();
foreach (var text in table.Headers)
{
tableRow.AppendChild(CreateTableCell(text));
}
tab.AppendChild(tableRow);
int height = table.Texts.Count / table.Headers.Count;
int width = table.Headers.Count;
for (int i = 0; i < height; i++)
{
tableRow = new TableRow();
for (int j = 0; j < width; j++)
{
var element = table.Texts[i * table.Headers.Count + j];
tableRow.AppendChild(CreateTableCell(element));
}
tab.AppendChild(tableRow);
}
_docBody.AppendChild(tab);
}
private TableCell CreateTableCell(string element)
{
var tableParagraph = new Paragraph();
var run = new Run();
run.AppendChild(new Text { Text = element });
tableParagraph.AppendChild(run);
var tableCell = new TableCell();
tableCell.AppendChild(tableParagraph);
return tableCell;
}
} }
} }

View File

@ -10,7 +10,8 @@ namespace LawFirmClientApp
{ {
private static readonly HttpClient _client = new(); private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null; public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration) public static int CurrentPage { get; set; } = 0;
public static void Connect(IConfiguration configuration)
{ {
_client.BaseAddress = new Uri(configuration["IPAddress"]); _client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Clear();

View File

@ -4,6 +4,7 @@ using LawFirmContracts.ViewModels;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Diagnostics; using System.Diagnostics;
using System.Text;
namespace LawFirmClientApp.Controllers namespace LawFirmClientApp.Controllers
{ {
@ -136,16 +137,54 @@ namespace LawFirmClientApp.Controllers
return count * (doc?.Price ?? 1); return count * (doc?.Price ?? 1);
} }
[HttpGet] [HttpGet]
public IActionResult Mails() public IActionResult Mails()
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
return View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={APIClient.Client.Id}")); APIClient.CurrentPage = 0;
return View();
}
[HttpGet]
public Tuple<string?, string?, bool, bool>? SwitchPage(bool isNext)
{
if (isNext)
{
APIClient.CurrentPage++;
}
else
{
if (APIClient.CurrentPage == 1)
{
return null;
}
APIClient.CurrentPage--;
}
var messages = APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={APIClient.Client!.Id}&pageNum={APIClient.CurrentPage}");
if (isNext && (messages == null || messages.Count == 0))
{
APIClient.CurrentPage--;
return Tuple.Create<string?, string?, bool, bool>(null, null, APIClient.CurrentPage != 1, false);
}
StringBuilder htmlTable = new();
foreach (var mail in messages)
{
htmlTable.Append("<tr>" +
$"<td>{mail.DateDelivery}</td>" +
$"<td>{mail.Subject}</td>" +
$"<td>{mail.Body}</td>" +
"<td>" + (mail.IsReaded ? "Прочитано" : "Непрочитано") + "</td>" +
$"<td>{mail.Reply}</td>" +
"</tr>");
}
return Tuple.Create<string?, string?, bool, bool>(htmlTable.ToString(), APIClient.CurrentPage.ToString(), APIClient.CurrentPage != 1, true);
} }
} }
} }

View File

@ -1,54 +1,79 @@
@using LawFirmContracts.ViewModels @{
ViewData["Title"] = "Mails";
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
} }
<div class="text-center"> <div class="text-center">
<h1 class="display-4">Письма</h1> <h1 class="display-4">Письма</h1>
</div> </div>
<div class="text-center"> <div class="text-center">
@{ <table class="table">
if (Model == null) <thead>
{ <tr>
<h3 class="display-4">Авторизируйтесь</h3> <th>
return; Дата
} </th>
<th>
<table class="table"> Заголовок
<thead> </th>
<tr> <th>
<th> Текст
Дата письма </th>
</th> <th>
<th> Прочитано
Заголовок </th>
</th> <th>
<th> Ответ
Текст </th>
</th> </tr>
</tr> </thead>
</thead> <tbody id="mails-table-body">
<tbody> </tbody>
@foreach (var item in Model) </table>
{ <ul class="pagination justify-content-center">
<tr> <li id="prev-page" class="page-item">
<td> <a class="page-link" href="#" aria-label="Previous">
@Html.DisplayFor(modelItem => item.DateDelivery) <span aria-hidden="true">&laquo;</span>
</td> <span class="sr-only">Предыдущее</span>
<td> </a>
@Html.DisplayFor(modelItem => item.Subject) </li>
</td> <li class="page-item">
<td> <a id="current-page" class="page-link"></a>
@Html.DisplayFor(modelItem => item.Body) </li>
</td> <li id="next-page" class="page-item">
</tr> <a class="page-link" href="#" aria-label="Next">
} <span aria-hidden="true">&raquo;</span>
</tbody> <span class="sr-only">Следующее</span>
</table> </a>
} </li>
</ul>
</div> </div>
<script>
function onClicked(isNext) {
$.ajax({
method: "GET",
url: "/Home/SwitchPage",
data: { isNext: isNext },
success: function (result) {
if (result != null) {
if (result.item1 != null && result.item2 != null) {
$("#mails-table-body").html(result.item1);
$("#current-page").text(result.item2);
}
if (result.item3)
$("#prev-page").removeClass("page-item disabled");
else
$("#prev-page").addClass("page-item disabled");
if (result.item4)
$("#next-page").removeClass("page-item disabled");
else
$("#next-page").addClass("page-item disabled");
}
}
});
}
onClicked(true);
$("#prev-page").on('click', () => onClicked(false));
$("#next-page").on('click', () => onClicked(true));
</script>

View File

@ -9,19 +9,21 @@ namespace LawFirmContracts.Attributes
[AttributeUsage(AttributeTargets.Property)] [AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute public class ColumnAttribute : Attribute
{ {
public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false) public ColumnAttribute(string title = "", bool visible = true, int width = 0, GridViewAutoSize gridViewAutoSize = GridViewAutoSize.None, bool isUseAutoSize = false, string format = "")
{ {
Title = title; Title = title;
Visible = visible; Visible = visible;
Width = width; Width = width;
GridViewAutoSize = gridViewAutoSize; GridViewAutoSize = gridViewAutoSize;
IsUseAutoSize = isUseAutoSize; IsUseAutoSize = isUseAutoSize;
Format = format;
} }
public string Title { get; private set; } public string Title { get; private set; }
public bool Visible { get; private set; } public bool Visible { get; private set; }
public int Width { get; private set; } public int Width { get; private set; }
public GridViewAutoSize GridViewAutoSize { get; private set; } public GridViewAutoSize GridViewAutoSize { get; private set; }
public bool IsUseAutoSize { get; private set; } public bool IsUseAutoSize { get; private set; }
public string Format { get; private set; }
} }
} }

View File

@ -21,6 +21,10 @@ namespace LawFirmContracts.BindingModels
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
public bool IsReaded { get; set; }
public string? Reply { get; set; }
public int Id => throw new NotImplementedException(); public int Id => throw new NotImplementedException();
} }
} }

View File

@ -0,0 +1,24 @@
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public string Name { get; set; } = string.Empty;
public string Adress { get; set; } = string.Empty;
public DateTime OpeningDate { get; set; }
public Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; set; } = new();
public int Id { get; set; }
public int MaxCountDocuments { get; set; }
}
}

View File

@ -13,5 +13,7 @@ namespace LawFirmContracts.BusinessLogicContracts
{ {
List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model); List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
bool Create(MessageInfoBindingModel model); bool Create(MessageInfoBindingModel model);
} bool Update(MessageInfoBindingModel model);
MessageInfoViewModel? ReadElement(MessageInfoSearchModel model);
}
} }

View File

@ -20,5 +20,11 @@ namespace LawFirmContracts.BusinessLogicContracts
void SaveProductComponentToExcelFile(ReportBindingModel model); void SaveProductComponentToExcelFile(ReportBindingModel model);
/// Сохранение заказов в файл-Pdf /// Сохранение заказов в файл-Pdf
void SaveOrdersToPdfFile(ReportBindingModel model); void SaveOrdersToPdfFile(ReportBindingModel model);
// Сохранение магазинов в файл-Word
void SaveShopsToWordFile(ReportBindingModel model);
void SaveShopDocumentsToExcelFile(ReportBindingModel model);
List<ReportShopDocumentsViewModel> GetShopDocuments();
List<ReportDateOrdersViewModel> GetDateOrders();
void SaveDateOrdersToPdfFile(ReportBindingModel model);
} }
} }

View File

@ -0,0 +1,23 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.BusinessLogicContracts
{
public interface IShopLogic
{
ShopViewModel? ReadElement(ShopSearchModel model);
List<ShopViewModel>? ReadList(ShopSearchModel? model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool SupplyDocuments(ShopSearchModel model, IDocumentModel document, int count);
bool SellDocument(IDocumentModel document, int count);
}
}

View File

@ -27,13 +27,16 @@ namespace LawFirmContracts.DI
/// </summary> /// </summary>
public static void InitDependency() public static void InitDependency()
{ {
var ext = ServiceProviderLoader.GetImplementationExtensions(); // берем все расширения и проходимся по ним, регистрируя сервисы в каждом
if (ext == null) var extensions = ServiceProviderLoader.GetImplementationExtensions();
foreach (var extension in extensions)
{ {
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям"); if (extension == null)
{
throw new ArgumentNullException("Отсутствуют компоненты для загрузки зависимостей по модулям");
}
extension.RegisterServices();
} }
// регистрируем зависимости
ext.RegisterServices();
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.DI
{
public interface ILogicImplementationExtension : IImplementationExtension
{
}
}

View File

@ -9,34 +9,47 @@ namespace LawFirmContracts.DI
{ {
public class ServiceProviderLoader public class ServiceProviderLoader
{ {
/// <summary>
/// Загрузка всех классов-реализаций IImplementationExtension /// Загрузка всех классов-реализаций IImplementationExtension
public static IImplementationExtension? GetImplementationExtensions() /// </summary>
/// <returns></returns>
public static List<IImplementationExtension?> GetImplementationExtensions()
{ {
IImplementationExtension? source = null; // Список типов, по каждому из которых, должна быть выбрана наиболее приоритетная реализация
// IImplementationExtension должен быть последним, поскольку все классы реализации, наследуются от него и являются им в частности
Type[] types =
{
typeof(ILogicImplementationExtension),
typeof(IImplementationExtension)
};
var trueTypes = types.Select(x => (IImplementationExtension?)null).ToList();
var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories); var files = Directory.GetFiles(TryGetImplementationExtensionsFolder(), "*.dll", SearchOption.AllDirectories);
foreach (var file in files.Distinct()) foreach (var file in files.Distinct())
{ {
Assembly asm = Assembly.LoadFrom(file); Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes()) foreach (var t in asm.GetExportedTypes())
{ {
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t)) for (var i = 0; i < types.Length; i++)
{ {
if (source == null) if (t.IsClass && types[i].IsAssignableFrom(t))
{ {
source = (IImplementationExtension)Activator.CreateInstance(t)!; if (trueTypes[i] == null)
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > source.Priority)
{ {
source = newSource; trueTypes[i] = (IImplementationExtension)Activator.CreateInstance(t)!;
}
else
{
var newSource = (IImplementationExtension)Activator.CreateInstance(t)!;
if (newSource.Priority > trueTypes[i].Priority)
{
trueTypes[i] = newSource;
}
} }
} }
} }
} }
} }
return source; return trueTypes;
} }
private static string TryGetImplementationExtensionsFolder() private static string TryGetImplementationExtensionsFolder()

View File

@ -10,5 +10,7 @@ namespace LawFirmContracts.SearchModels
{ {
public int? ClientId { get; set; } public int? ClientId { get; set; }
public string? MessageId { get; set; } public string? MessageId { get; set; }
public int? Page { get; set; }
public int? PageSize { get; set; }
} }
} }

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? Name { get; set; }
}
}

View File

@ -15,5 +15,6 @@ namespace LawFirmContracts.StorageContracts
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model); List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model); MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model); MessageInfoViewModel? Insert(MessageInfoBindingModel model);
} MessageInfoViewModel? Update(MessageInfoBindingModel model);
}
} }

View File

@ -0,0 +1,23 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.StorageContracts
{
public interface IShopStorage
{
ShopViewModel? GetElement(ShopSearchModel model);
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellDocument(IDocumentModel model, int count);
}
}

View File

@ -14,7 +14,7 @@ namespace LawFirmContracts.ViewModels
[Column("Название бланка", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] [Column("Название бланка", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string BlankName { get; set; } = string.Empty; public string BlankName { get; set; } = string.Empty;
[Column("Цена", width: 100)] [Column("Цена", width: 100, format: "0.00")]
public double Cost { get; set; } public double Cost { get; set; }
[Column(visible: false)] [Column(visible: false)]

View File

@ -14,7 +14,7 @@ namespace LawFirmContracts.ViewModels
[Column("Название документа", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] [Column("Название документа", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string DocumentName {get; set;} = string.Empty; public string DocumentName {get; set;} = string.Empty;
[Column("Цена", width: 100)] [Column("Цена", width: 100, format:"0.00")]
public double Price { get; set; } public double Price { get; set; }
[Column(visible: false)] [Column(visible: false)]

View File

@ -20,7 +20,7 @@ namespace LawFirmContracts.ViewModels
[Column("Отправитель", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)] [Column("Отправитель", gridViewAutoSize: GridViewAutoSize.DisplayedCells, isUseAutoSize: true)]
public string SenderName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty;
[Column("Дата письма", width: 100)] [Column("Дата письма", width: 100, format:"D")]
public DateTime DateDelivery { get; set; } public DateTime DateDelivery { get; set; }
[Column("Заголовок", width: 150)] [Column("Заголовок", width: 150)]
@ -29,6 +29,12 @@ namespace LawFirmContracts.ViewModels
[Column("Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)] [Column("Текст", gridViewAutoSize: GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
[Column("Прочитано", width: 50)]
public bool IsReaded { get; set; }
[Column("Ответ", width: 150)]
public string? Reply { get; set; }
[Column(visible: false)] [Column(visible: false)]
public int Id => throw new NotImplementedException(); public int Id => throw new NotImplementedException();
} }

View File

@ -36,16 +36,16 @@ namespace LawFirmContracts.ViewModels
[Column("Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] [Column("Количество", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public int Count { get; set; } public int Count { get; set; }
[Column("Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] [Column("Сумма", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true, format:"0.00")]
public double Sum { get; set; } public double Sum { get; set; }
[Column("Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)] [Column("Статус", gridViewAutoSize: GridViewAutoSize.AllCells, isUseAutoSize: true)]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[Column("Дата создания", width: 100)] [Column("Дата создания", width: 100, format:"D")]
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
[Column("Дата выполнения", width: 100)] [Column("Дата выполнения", width: 100, format:"D")]
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.ViewModels
{
public class ReportDateOrdersViewModel
{
public DateTime DateCreate { get; set; }
public int CountOrders { get; set; }
public double SumOrders { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.ViewModels
{
public class ReportShopDocumentsViewModel
{
public string ShopName { get; set; } = string.Empty;
public int Count { get; set; }
public List<Tuple<string, int>> Documents { get; set; } = new();
}
}

View File

@ -0,0 +1,35 @@
using LawFirmContracts.Attributes;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
[Column("Название магазина", gridViewAutoSize:GridViewAutoSize.Fill, isUseAutoSize: true)]
public string Name { get; set; } = string.Empty;
[Column("Адрес", width: 150)]
public string Adress { get; set; } = string.Empty;
[Column("Дата открытия", format:"D", isUseAutoSize:true, gridViewAutoSize:GridViewAutoSize.AllCells)]
public DateTime OpeningDate { get; set; }
[Column(visible: false)]
public Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; set; } = new();
[Column(visible: false)]
public List<Tuple<string, int>>? DocumentCount { get; set; } = new();
[Column(visible: false)]
public int Id { get; set; }
[Column("Макс. документов в магазине", width:100)]
public int MaxCountDocuments { get; set; }
}
}

View File

@ -13,5 +13,6 @@ namespace LawFirmDataModels.Enums
Выполняется = 1, Выполняется = 1,
Готов = 2, Готов = 2,
Выдан = 3, Выдан = 3,
Ожидание = 4
} }
} }

View File

@ -14,5 +14,7 @@ namespace LawFirmDataModels.Models
DateTime DateDelivery { get; } DateTime DateDelivery { get; }
string Subject { get; } string Subject { get; }
string Body { get; } string Body { get; }
} public bool IsReaded { get; }
public string? Reply { get; }
}
} }

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDataModels.Models
{
public interface IShopModel : IId
{
String Name { get; }
String Adress { get; }
DateTime OpeningDate { get; }
Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; }
int MaxCountDocuments { get; }
}
}

View File

@ -22,6 +22,7 @@ namespace LawFirmDatabaseImplement
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>(); DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IDocumentStorage, DocumentStorage>(); DependencyManager.Instance.RegisterType<IDocumentStorage, DocumentStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>(); DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
} }
} }
} }

View File

@ -3,6 +3,7 @@ using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts; using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels; using LawFirmContracts.ViewModels;
using LawFirmDatabaseImplement.Models; using LawFirmDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -27,10 +28,16 @@ namespace LawFirmDatabaseImplement.Implements
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model) public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{ {
using var context = new LawFirmDatabase(); using var context = new LawFirmDatabase();
return context.Messages var messages = context.Messages
.Where(x => x.ClientId == model.ClientId) .Where(x => (model.ClientId == null) || (x.ClientId == model.ClientId))
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel);
.ToList();
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return messages.ToList();
}
return messages.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList();
} }
public List<MessageInfoViewModel> GetFullList() public List<MessageInfoViewModel> GetFullList()
@ -53,5 +60,17 @@ namespace LawFirmDatabaseImplement.Implements
context.SaveChanges(); context.SaveChanges();
return newMessage.GetViewModel; return newMessage.GetViewModel;
} }
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
using var context = new LawFirmDatabase();
var message = context.Messages.Include(x => x.Client).FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
if (message != null)
{
message.Update(model);
context.SaveChanges();
}
return message?.GetViewModel;
}
}
} }

View File

@ -17,6 +17,7 @@ namespace LawFirmDatabaseImplement.Implements
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
using var context = new LawFirmDatabase(); using var context = new LawFirmDatabase();
return context.Orders return context.Orders
.Include(x => x.Document) .Include(x => x.Document)
.Include(x => x.Client) .Include(x => x.Client)
@ -44,16 +45,16 @@ namespace LawFirmDatabaseImplement.Implements
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
if (model.Status!= null) if (model.Status != null)
{ {
return context.Orders return context.Orders
.Include(x => x.Document) .Include(x => x.Document)
.Include(x => x.Client) .Include(x => x.Client)
.Include(x => x.Implementer) .Include(x => x.Implementer)
.Where(x => model.Status.Equals(x.Status)) .Where(x => model.Status.Equals(x.Status))
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
return context.Orders return context.Orders
.Include(x => x.Document) .Include(x => x.Document)
.Include(x => x.Client) .Include(x => x.Client)

View File

@ -0,0 +1,146 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDatabaseImplement.Models;
using LawFirmDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return new();
}
using var context = new LawFirmDatabase();
return context.Shops.Include(x => x.Documents).ThenInclude(x => x.Document).FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new LawFirmDatabase();
return context.Shops.Include(x => x.Documents).ThenInclude(x => x.Document).Where(x => x.Name.Contains(model.Name)).ToList().Select(x => x.GetViewModel).ToList();
}
public List<ShopViewModel> GetFullList()
{
using var context = new LawFirmDatabase();
return context.Shops.Include(x => x.Documents).ThenInclude(x => x.Document).ToList().Select(x => x.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
if (context.Shops.Any(x => x.Name == newShop.Name))
{
throw new Exception("Название магазина уже занято");
}
context.Shops.Add(newShop);
context.SaveChanges();
transaction.Commit();
return newShop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var shop = context.Shops.Include(x => x.Documents).FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
context.SaveChanges();
if (model.ShopDocuments.Count > 0)
{
shop.UpdateDocuments(context, model);
}
transaction.Commit();
return shop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new LawFirmDatabase();
var shop = context.Shops.Include(x => x.Documents).FirstOrDefault(x => x.Id == model.Id);
if (shop != null)
{
context.Shops.Remove(shop);
context.SaveChanges();
return shop.GetViewModel;
}
return null;
}
public bool SellDocument(IDocumentModel model, int count)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
foreach (var shopDocs in context.ShopDocuments.Where(x => x.DocumentId == model.Id))
{
var min = Math.Min(count, shopDocs.Count);
shopDocs.Count -= min;
count -= min;
if (count <= 0)
{
break;
}
}
if (count == 0)
{
context.SaveChanges();
transaction.Commit();
}
else
{
transaction.Rollback();
}
if (count > 0)
{
return false;
}
return true;
}
}
}

View File

@ -23,6 +23,8 @@ namespace LawFirmDatabaseImplement
public virtual DbSet<Document> Documents { set; get; } public virtual DbSet<Document> Documents { set; get; }
public virtual DbSet<DocumentBlank> DocumentBlanks { set; get; } public virtual DbSet<DocumentBlank> DocumentBlanks { set; get; }
public virtual DbSet<Order> Orders { set; get; } public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopDocument> ShopDocuments { set; get; }
public virtual DbSet<Client> Clients { set; get; } public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; } public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> Messages { set; get; } public virtual DbSet<MessageInfo> Messages { set; get; }

View File

@ -0,0 +1,248 @@
// <auto-generated />
using System;
using LawFirmDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
[DbContext(typeof(LawFirmDatabase))]
[Migration("20230312152057_ShopsAdded")]
partial class ShopsAdded
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("BlankName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Blanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("DocumentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Documents");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BlankId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BlankId");
b.HasIndex("DocumentId");
b.ToTable("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.ToTable("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Adress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCountDocuments")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.HasIndex("ShopId");
b.ToTable("ShopDocuments");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Blank", "Blank")
.WithMany("DocumentBlanks")
.HasForeignKey("BlankId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Blanks")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Blank");
b.Navigation("Document");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Orders")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Shop", "Shop")
.WithMany("Documents")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
b.Navigation("Shop");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Navigation("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Navigation("Blanks");
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Documents");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,78 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ShopsAdded : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Adress = table.Column<string>(type: "nvarchar(max)", nullable: false),
OpeningDate = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCountDocuments = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ShopDocuments",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
DocumentId = table.Column<int>(type: "int", nullable: false),
ShopId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopDocuments", x => x.Id);
table.ForeignKey(
name: "FK_ShopDocuments_Documents_DocumentId",
column: x => x.DocumentId,
principalTable: "Documents",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopDocuments_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ShopDocuments_DocumentId",
table: "ShopDocuments",
column: "DocumentId");
migrationBuilder.CreateIndex(
name: "IX_ShopDocuments_ShopId",
table: "ShopDocuments",
column: "ShopId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ShopDocuments");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
#nullable disable #nullable disable
@ -10,7 +12,7 @@ namespace LawFirmDatabaseImplement.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.AddColumn<int>( migrationBuilder.AddColumn<int>(
name: "ImplementerId", name: "ImplementerId",
table: "Orders", table: "Orders",
type: "int", type: "int",

View File

@ -0,0 +1,381 @@
// <auto-generated />
using System;
using LawFirmDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
[DbContext(typeof(LawFirmDatabase))]
[Migration("20230422091213_MessageInfoUpdate")]
partial class MessageInfoUpdate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("BlankName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Blanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("DocumentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Documents");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BlankId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BlankId");
b.HasIndex("DocumentId");
b.ToTable("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<bool>("IsReaded")
.HasColumnType("bit");
b.Property<string>("Reply")
.HasColumnType("nvarchar(max)");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("DocumentId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Adress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCountDocuments")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.HasIndex("ShopId");
b.ToTable("ShopDocuments");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Blank", "Blank")
.WithMany("DocumentBlanks")
.HasForeignKey("BlankId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Blanks")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Blank");
b.Navigation("Document");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany("Orders")
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Document");
b.Navigation("Implementer");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Shop", "Shop")
.WithMany("Documents")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
b.Navigation("Shop");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{
b.Navigation("DocumentBlanks");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b =>
{
b.Navigation("Blanks");
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Documents");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace LawFirmDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class MessageInfoUpdate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsReaded",
table: "Messages",
type: "bit",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<string>(
name: "Reply",
table: "Messages",
type: "nvarchar(max)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsReaded",
table: "Messages");
migrationBuilder.DropColumn(
name: "Reply",
table: "Messages");
}
}
}

View File

@ -155,6 +155,12 @@ namespace LawFirmDatabaseImplement.Migrations
b.Property<DateTime>("DateDelivery") b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2"); .HasColumnType("datetime2");
b.Property<bool>("IsReaded")
.HasColumnType("bit");
b.Property<string>("Reply")
.HasColumnType("nvarchar(max)");
b.Property<string>("SenderName") b.Property<string>("SenderName")
.IsRequired() .IsRequired()
.HasColumnType("nvarchar(max)"); .HasColumnType("nvarchar(max)");
@ -213,6 +219,59 @@ namespace LawFirmDatabaseImplement.Migrations
b.ToTable("Orders"); b.ToTable("Orders");
}); });
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Adress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCountDocuments")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DocumentId");
b.HasIndex("ShopId");
b.ToTable("ShopDocuments");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b => modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b =>
{ {
b.HasOne("LawFirmDatabaseImplement.Models.Blank", "Blank") b.HasOne("LawFirmDatabaseImplement.Models.Blank", "Blank")
@ -266,6 +325,25 @@ namespace LawFirmDatabaseImplement.Migrations
b.Navigation("Implementer"); b.Navigation("Implementer");
}); });
modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b =>
{
b.HasOne("LawFirmDatabaseImplement.Models.Document", "Document")
.WithMany()
.HasForeignKey("DocumentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("LawFirmDatabaseImplement.Models.Shop", "Shop")
.WithMany("Documents")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Document");
b.Navigation("Shop");
});
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b => modelBuilder.Entity("LawFirmDatabaseImplement.Models.Blank", b =>
{ {
b.Navigation("DocumentBlanks"); b.Navigation("DocumentBlanks");
@ -289,6 +367,11 @@ namespace LawFirmDatabaseImplement.Migrations
{ {
b.Navigation("Orders"); b.Navigation("Orders");
}); });
modelBuilder.Entity("LawFirmDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Documents");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -29,8 +29,10 @@ namespace LawFirmDatabaseImplement.Models
public string Body { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty;
public virtual Client? Client { get; private set; } public virtual Client? Client { get; private set; }
public bool IsReaded { get; private set; }
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model) public static MessageInfo? Create(MessageInfoBindingModel model)
{ {
if (model == null) if (model == null)
{ {
@ -44,10 +46,22 @@ namespace LawFirmDatabaseImplement.Models
MessageId = model.MessageId, MessageId = model.MessageId,
SenderName = model.SenderName, SenderName = model.SenderName,
DateDelivery = model.DateDelivery, DateDelivery = model.DateDelivery,
}; IsReaded = model.IsReaded,
Reply = model.Reply
};
} }
public MessageInfoViewModel GetViewModel => new() public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
IsReaded = model.IsReaded;
}
public MessageInfoViewModel GetViewModel => new()
{ {
Body = Body, Body = Body,
Subject = Subject, Subject = Subject,
@ -55,7 +69,9 @@ namespace LawFirmDatabaseImplement.Models
MessageId = MessageId, MessageId = MessageId,
SenderName = SenderName, SenderName = SenderName,
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; Reply = Reply,
IsReaded = IsReaded,
};
public int Id => throw new NotImplementedException(); public int Id => throw new NotImplementedException();
} }

View File

@ -0,0 +1,120 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace LawFirmDatabaseImplement.Models
{
[DataContract]
public class Shop : IShopModel
{
[DataMember]
public int Id { get; set; }
[Required]
[DataMember]
public string Name { get; set; } = string.Empty;
[Required]
[DataMember]
public string Adress { get; set; } = string.Empty;
[Required]
[DataMember]
public DateTime OpeningDate { get; set; }
[ForeignKey("ShopId")]
public List<ShopDocument> Documents { get; set; } = new();
private Dictionary<int, (IDocumentModel, int)>? _shopDocuments = null;
[NotMapped]
[DataMember]
public Dictionary<int, (IDocumentModel, int)> ShopDocuments
{
get
{
if (_shopDocuments == null)
{
_shopDocuments = Documents.ToDictionary(recPC => recPC.DocumentId, recPC => (recPC.Document as IDocumentModel, recPC.Count));
}
return _shopDocuments;
}
}
[Required]
public int MaxCountDocuments { get; set; }
public static Shop Create(LawFirmDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
Name = model.Name,
Adress = model.Adress,
OpeningDate = model.OpeningDate,
Documents = model.ShopDocuments.Select(x => new ShopDocument
{
Document = context.Documents.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
MaxCountDocuments = model.MaxCountDocuments
};
}
public void Update(ShopBindingModel model)
{
Name = model.Name;
Adress = model.Adress;
OpeningDate = model.OpeningDate;
MaxCountDocuments = model.MaxCountDocuments;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Adress = Adress,
OpeningDate = OpeningDate,
ShopDocuments = ShopDocuments,
MaxCountDocuments = MaxCountDocuments
};
public void UpdateDocuments(LawFirmDatabase context, ShopBindingModel model)
{
var ShopDocuments = context.ShopDocuments.Where(rec => rec.ShopId == model.Id).ToList();
if (ShopDocuments != null && ShopDocuments.Count > 0)
{
// удалили те, которых нет в модели
context.ShopDocuments.RemoveRange(ShopDocuments.Where(rec => !model.ShopDocuments.ContainsKey(rec.DocumentId)));
context.SaveChanges();
ShopDocuments = context.ShopDocuments.Where(rec => rec.ShopId == model.Id).ToList();
// обновили количество у существующих записей
foreach (var updateDoc in ShopDocuments)
{
updateDoc.Count = model.ShopDocuments[updateDoc.DocumentId].Item2;
model.ShopDocuments.Remove(updateDoc.DocumentId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var elem in model.ShopDocuments)
{
context.ShopDocuments.Add(new ShopDocument
{
Shop = shop,
Document = context.Documents.First(x => x.Id == elem.Key),
Count = elem.Value.Item2
});
context.SaveChanges();
}
_shopDocuments = null;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Models
{
public class ShopDocument
{
public int Id { get; set; }
[Required]
public int DocumentId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Document Document { get; set; } = new();
}
}

View File

@ -15,12 +15,15 @@ namespace LawFirmFileImplement
private readonly string BlankFileName = "Blank.xml"; private readonly string BlankFileName = "Blank.xml";
private readonly string OrderFileName = "Order.xml"; private readonly string OrderFileName = "Order.xml";
private readonly string DocumentFileName = "Document.xml"; private readonly string DocumentFileName = "Document.xml";
private readonly string ShopFileName = "Shop.xml";
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml"; private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageInfoFileName = "MessageInfo.xml"; private readonly string MessageInfoFileName = "MessageInfo.xml";
public List<Blank> Blanks { get; private set; } public List<Blank> Blanks { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Document> Documents { get; private set; } public List<Document> Documents { get; private set; }
public List<Shop> Shops { get; private set; }
public List<Client> Clients { get; private set; } public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; } public List<Implementer> Implementers { get; private set; }
public List<MessageInfo> Messages { get; private set; } public List<MessageInfo> Messages { get; private set; }
@ -35,6 +38,7 @@ namespace LawFirmFileImplement
public void SaveBlanks() => SaveData(Blanks, BlankFileName, "Blanks", x => x.GetXElement); public void SaveBlanks() => SaveData(Blanks, BlankFileName, "Blanks", x => x.GetXElement);
public void SaveDocuments() => SaveData(Documents, DocumentFileName, "Documents", x => x.GetXElement); public void SaveDocuments() => SaveData(Documents, DocumentFileName, "Documents", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement);
@ -43,6 +47,7 @@ namespace LawFirmFileImplement
Blanks = LoadData(BlankFileName, "Blank", x => Blank.Create(x)!)!; Blanks = LoadData(BlankFileName, "Blank", x => Blank.Create(x)!)!;
Documents = LoadData(DocumentFileName, "Document", x => Document.Create(x)!)!; Documents = LoadData(DocumentFileName, "Document", x => Document.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Impleneter", x => Implementer.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Impleneter", x => Implementer.Create(x)!)!;
Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!;

View File

@ -22,6 +22,7 @@ namespace LawFirmFileImplement
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>(); DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IDocumentStorage, DocumentStorage>(); DependencyManager.Instance.RegisterType<IDocumentStorage, DocumentStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>(); DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
} }
} }
} }

View File

@ -8,6 +8,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmFileImplement.Implements namespace LawFirmFileImplement.Implements
{ {

View File

@ -30,10 +30,15 @@ namespace LawFirmFileImplement.Implements
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model) public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{ {
return _source.Messages var messages = _source.Messages
.Where(x => x.ClientId == model.ClientId) .Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel);
.ToList();
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return messages.ToList();
}
return messages.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList();
} }
public List<MessageInfoViewModel> GetFullList() public List<MessageInfoViewModel> GetFullList()
@ -54,5 +59,16 @@ namespace LawFirmFileImplement.Implements
_source.SaveMessages(); _source.SaveMessages();
return newMessage.GetViewModel; return newMessage.GetViewModel;
} }
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
var message = _source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
if (message != null)
{
message.Update(model);
_source.SaveMessages();
}
return message?.GetViewModel;
}
}
} }

View File

@ -0,0 +1,148 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using LawFirmFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
return source.Shops
.Select(x => x.GetViewModel)
.Where(x => x.Name.Contains(model.Name ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(shop => shop.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
public bool SellDocument(IDocumentModel model, int count)
{
var document = source.Documents.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return false;
}
var countStore = count;
var shopDocuments = source.Shops.SelectMany(shop => shop.ShopDocuments.Where(doc => doc.Value.Item1.Id == document.Id));
foreach (var doc in shopDocuments)
{
count -= doc.Value.Item2;
if (count <= 0)
{
break;
}
}
if (count > 0)
{
return false;
}
count = countStore;
foreach (var shop in source.Shops)
{
var documents = shop.ShopDocuments;
foreach (var doc in documents.Where(x => x.Value.Item1.Id == document.Id))
{
var min = Math.Min(doc.Value.Item2, count);
documents[doc.Value.Item1.Id] = (doc.Value.Item1, doc.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
Name = shop.Name,
Adress = shop.Adress,
OpeningDate = shop.OpeningDate,
MaxCountDocuments = shop.MaxCountDocuments,
ShopDocuments = documents
});
source.SaveShops();
if (count <= 0) break;
}
return count <= 0;
}
}
}

View File

@ -96,7 +96,7 @@ namespace LawFirmFileImplement.Models
}; };
public XElement GetXElement => new( public XElement GetXElement => new(
"Document", "Document",
new XAttribute("Id", Id), new XAttribute("Id", Id),
new XElement("DocumentName", DocumentName), new XElement("DocumentName", DocumentName),
new XElement("Price", Price.ToString()), new XElement("Price", Price.ToString()),

View File

@ -26,8 +26,12 @@ namespace LawFirmFileImplement.Models
public string Subject { get; private set; } = string.Empty; public string Subject { get; private set; } = string.Empty;
[DataMember] [DataMember]
public string Body { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty;
[DataMember]
public bool IsReaded { get; private set; }
[DataMember]
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model) public static MessageInfo? Create(MessageInfoBindingModel model)
{ {
if (model == null) if (model == null)
{ {
@ -41,7 +45,9 @@ namespace LawFirmFileImplement.Models
MessageId = model.MessageId, MessageId = model.MessageId,
SenderName = model.SenderName, SenderName = model.SenderName,
DateDelivery = model.DateDelivery, DateDelivery = model.DateDelivery,
}; Reply = model.Reply,
IsReaded = model.IsReaded,
};
} }
public static MessageInfo? Create(XElement element) public static MessageInfo? Create(XElement element)
@ -58,10 +64,22 @@ namespace LawFirmFileImplement.Models
MessageId = element.Attribute("MessageId")!.Value, MessageId = element.Attribute("MessageId")!.Value,
SenderName = element.Attribute("SenderName")!.Value, SenderName = element.Attribute("SenderName")!.Value,
DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value),
}; Reply = element.Attribute("Reply")!.Value,
IsReaded = Convert.ToBoolean(element.Attribute("IsReaded")!.Value),
};
} }
public MessageInfoViewModel GetViewModel => new() public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
IsReaded = model.IsReaded;
}
public MessageInfoViewModel GetViewModel => new()
{ {
Body = Body, Body = Body,
Subject = Subject, Subject = Subject,
@ -69,7 +87,9 @@ namespace LawFirmFileImplement.Models
MessageId = MessageId, MessageId = MessageId,
SenderName = SenderName, SenderName = SenderName,
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; Reply = Reply,
IsReaded = IsReaded,
};
public XElement GetXElement => new("MessageInfo", public XElement GetXElement => new("MessageInfo",
new XAttribute("Body", Body), new XAttribute("Body", Body),
@ -77,8 +97,10 @@ namespace LawFirmFileImplement.Models
new XAttribute("ClientId", ClientId), new XAttribute("ClientId", ClientId),
new XAttribute("MessageId", MessageId), new XAttribute("MessageId", MessageId),
new XAttribute("SenderName", SenderName), new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery) new XAttribute("DateDelivery", DateDelivery),
); new XAttribute("Reply", Reply),
new XAttribute("HasRead", IsReaded)
);
public int Id => throw new NotImplementedException(); public int Id => throw new NotImplementedException();
} }

View File

@ -0,0 +1,127 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmFileImplement.Models
{
[DataContract]
public class Shop : IShopModel
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string Name { get; private set; } = string.Empty;
[DataMember]
public string Adress { get; private set; } = string.Empty;
[DataMember]
public int MaxCountDocuments { get; private set; }
[DataMember]
public DateTime OpeningDate { get; private set; }
public Dictionary<int, int> Documents { get; private set; } = new();
private Dictionary<int, (IDocumentModel, int)>? _shopDocuments = null;
[DataMember]
public Dictionary<int, (IDocumentModel, int)> ShopDocuments
{
get
{
if (_shopDocuments == null)
{
var source = DataFileSingleton.GetInstance();
_shopDocuments = Documents.ToDictionary(
x => x.Key,
y => ((source.Documents.FirstOrDefault(z => z.Id == y.Key) as IDocumentModel)!, y.Value)
);
}
return _shopDocuments;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Adress = model.Adress,
MaxCountDocuments = model.MaxCountDocuments,
OpeningDate = model.OpeningDate,
Documents = model.ShopDocuments.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Name = element.Element("Name")!.Value,
Adress = element.Element("Address")!.Value,
MaxCountDocuments = Convert.ToInt32(element.Element("MaxCountDocuments")!.Value),
OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value),
Documents= element.Element("ShopDocuments")!.Elements("ShopDocument").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Adress = model.Adress;
OpeningDate = model.OpeningDate;
MaxCountDocuments = model.MaxCountDocuments;
if (model.ShopDocuments.Count > 0)
{
Documents = model.ShopDocuments.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopDocuments = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Adress = Adress,
OpeningDate = OpeningDate,
ShopDocuments = ShopDocuments,
MaxCountDocuments = MaxCountDocuments
};
public XElement GetXElement => new(
"Shop",
new XAttribute("Id", Id),
new XElement("Name", Name),
new XElement("Address", Adress),
new XElement("MaxCountDocuments", MaxCountDocuments),
new XElement("OpeningDate", OpeningDate.ToString()),
new XElement("ShopDocuments", Documents.Select (x =>
new XElement("ShopDocument",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -15,6 +15,7 @@ namespace LawFirmListImplements
public List<Order> Orders { get; set; } public List<Order> Orders { get; set; }
public List<Document> Documents { get; set; } public List<Document> Documents { get; set; }
public List<Client> Clients { get; set; } public List<Client> Clients { get; set; }
public List<Shop> Shops { get; set; }
public List<Implementer> Implementers { get; set; } public List<Implementer> Implementers { get; set; }
public List<MessageInfo> Messages { get; set; } public List<MessageInfo> Messages { get; set; }
private DataListSingleton() private DataListSingleton()
@ -22,6 +23,7 @@ namespace LawFirmListImplements
Blanks = new List<Blank>(); Blanks = new List<Blank>();
Orders = new List<Order>(); Orders = new List<Order>();
Documents = new List<Document>(); Documents = new List<Document>();
Shops = new List<Shop>();
Clients= new List<Client>(); Clients= new List<Client>();
Implementers = new List<Implementer>(); Implementers = new List<Implementer>();
Messages = new List<MessageInfo>(); Messages = new List<MessageInfo>();

View File

@ -30,15 +30,29 @@ namespace LawFirmListImplements.Implements
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model) public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{ {
List<MessageInfoViewModel> result = new(); List<MessageInfoViewModel> messages = new();
foreach (var item in _source.Messages) foreach (var item in _source.Messages)
{ {
if (item.ClientId.HasValue && item.ClientId == model.ClientId) if (item.ClientId == model.ClientId)
{ {
result.Add(item.GetViewModel); messages.Add(item.GetViewModel);
} }
} }
return result;
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return messages;
}
if (model.Page * model.PageSize >= messages.Count)
{
return null;
}
List<MessageInfoViewModel> filterMessages = new();
for (var i = (model.Page.Value - 1) * model.PageSize.Value; i < model.Page.Value * model.PageSize.Value; i++)
{
filterMessages.Add(messages[i]);
}
return filterMessages;
} }
public List<MessageInfoViewModel> GetFullList() public List<MessageInfoViewModel> GetFullList()
@ -61,5 +75,18 @@ namespace LawFirmListImplements.Implements
_source.Messages.Add(newMessage); _source.Messages.Add(newMessage);
return newMessage.GetViewModel; return newMessage.GetViewModel;
} }
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
foreach (var message in _source.Messages)
{
if (message.MessageId.Equals(model.MessageId))
{
message.Update(model);
return message.GetViewModel;
}
}
return null;
}
}
} }

View File

@ -0,0 +1,125 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using LawFirmListImplements.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;
namespace LawFirmListImplements.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.Name) && shop.Name == model.Name) || (model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.Name))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.Name.Contains(model.Name))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public bool SellDocument(IDocumentModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -22,6 +22,7 @@ namespace LawFirmListImplements
DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>(); DependencyManager.Instance.RegisterType<IOrderStorage, OrderStorage>();
DependencyManager.Instance.RegisterType<IDocumentStorage, DocumentStorage>(); DependencyManager.Instance.RegisterType<IDocumentStorage, DocumentStorage>();
DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>(); DependencyManager.Instance.RegisterType<IBackUpInfo, BackUpInfo>();
DependencyManager.Instance.RegisterType<IShopStorage, ShopStorage>();
} }
} }
} }

View File

@ -22,8 +22,10 @@ namespace LawFirmListImplements.Models
public string Subject { get; private set; } = string.Empty; public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty; public string Body { get; private set; } = string.Empty;
public bool IsReaded { get; private set; }
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model) public static MessageInfo? Create(MessageInfoBindingModel model)
{ {
if (model == null) if (model == null)
{ {
@ -37,10 +39,22 @@ namespace LawFirmListImplements.Models
MessageId = model.MessageId, MessageId = model.MessageId,
SenderName = model.SenderName, SenderName = model.SenderName,
DateDelivery = model.DateDelivery, DateDelivery = model.DateDelivery,
}; Reply = model.Reply,
IsReaded = model.IsReaded,
};
} }
public MessageInfoViewModel GetViewModel => new() public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
IsReaded = model.IsReaded;
}
public MessageInfoViewModel GetViewModel => new()
{ {
Body = Body, Body = Body,
Subject = Subject, Subject = Subject,
@ -48,7 +62,9 @@ namespace LawFirmListImplements.Models
MessageId = MessageId, MessageId = MessageId,
SenderName = SenderName, SenderName = SenderName,
DateDelivery = DateDelivery, DateDelivery = DateDelivery,
}; Reply = Reply,
IsReaded = IsReaded,
};
public int Id => throw new NotImplementedException(); public int Id => throw new NotImplementedException();
} }

View File

@ -0,0 +1,70 @@
using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;
namespace LawFirmListImplements.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Adress { get; private set; } = string.Empty;
public DateTime OpeningDate { get; private set; }
public int MaxCountDocuments { get; private set; }
public Dictionary<int, (IDocumentModel, int)> ShopDocuments { get; private set; } = new();
public static Shop? Create (ShopBindingModel model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Adress = model.Adress,
OpeningDate = model.OpeningDate,
MaxCountDocuments = model.MaxCountDocuments,
ShopDocuments = new()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Adress = model.Adress;
OpeningDate = model.OpeningDate;
ShopDocuments = model.ShopDocuments;
MaxCountDocuments= model.MaxCountDocuments;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Adress = Adress,
OpeningDate = OpeningDate,
ShopDocuments = ShopDocuments,
MaxCountDocuments = MaxCountDocuments
};
}
}

View File

@ -13,8 +13,9 @@ namespace LawFirmRestApi.Controllers
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IClientLogic _logic; private readonly IClientLogic _logic;
private readonly IMessageInfoLogic _mailLogic; private readonly IMessageInfoLogic _mailLogic;
public int pageSize = 2;
public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController> logger) public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController> logger)
{ {
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
@ -65,14 +66,16 @@ namespace LawFirmRestApi.Controllers
} }
[HttpGet] [HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId) public List<MessageInfoViewModel>? GetMessages(int clientId, int pageNum)
{ {
try try
{ {
return _mailLogic.ReadList(new MessageInfoSearchModel return _mailLogic.ReadList(new()
{ {
ClientId = clientId ClientId = clientId,
}); Page = pageNum,
PageSize = pageSize
});
} }
catch (Exception ex) catch (Exception ex)
{ {

Some files were not shown because too many files have changed in this diff Show More