From 9c2c5f90e2d193b7f3b4d69cc1c0f1100c689071 Mon Sep 17 00:00:00 2001 From: Danila_Mochalov Date: Tue, 18 Apr 2023 20:11:50 +0400 Subject: [PATCH 1/4] =?UTF-8?q?=D0=98=D0=BD=D1=82=D0=B5=D1=80=D1=84=D0=B5?= =?UTF-8?q?=D0=B9=D1=81=D1=8B=20=D0=B8=20=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D0=B8=20=D0=BF=D0=B8=D1=81=D1=8C=D0=BC=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BindingModels/MessageInfoBindingModel.cs | 24 ++++++++++++++++++ .../IMessageInfoLogic.cs | 17 +++++++++++++ .../SearchModels/MessageInfoSearchModel.cs | 14 +++++++++++ .../StorageContracts/IMessageInfoStorage.cs | 19 ++++++++++++++ .../ViewModels/MessageInfoViewModel.cs | 25 +++++++++++++++++++ .../Models/IMessageInfoModel.cs | 18 +++++++++++++ 6 files changed, 117 insertions(+) create mode 100644 LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs create mode 100644 LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs create mode 100644 LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs create mode 100644 LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs create mode 100644 LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs create mode 100644 LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs diff --git a/LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs b/LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs new file mode 100644 index 0000000..e0cb256 --- /dev/null +++ b/LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs @@ -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 MessageInfoBindingModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + + public string SenderName { get; set; } = string.Empty; + + public DateTime DateDelivery { get; set; } + + public string Subject { get; set; } = string.Empty; + + public string Body { get; set; } = string.Empty; + } +} diff --git a/LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs b/LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs new file mode 100644 index 0000000..982278f --- /dev/null +++ b/LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs @@ -0,0 +1,17 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.SearchModels; +using LawFirmContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmContracts.BusinessLogicContracts +{ + public interface IMessageInfoLogic + { + List? ReadList(MessageInfoSearchModel? model); + bool Create(MessageInfoBindingModel model); + } +} diff --git a/LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs b/LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs new file mode 100644 index 0000000..cad0a9e --- /dev/null +++ b/LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs @@ -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 MessageInfoSearchModel + { + public int? ClientId { get; set; } + public string? MessageId { get; set; } + } +} diff --git a/LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs b/LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs new file mode 100644 index 0000000..299fd48 --- /dev/null +++ b/LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs @@ -0,0 +1,19 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.SearchModels; +using LawFirmContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmContracts.StorageContracts +{ + public interface IMessageInfoStorage + { + List GetFullList(); + List GetFilteredList(MessageInfoSearchModel model); + MessageInfoViewModel? GetElement(MessageInfoSearchModel model); + MessageInfoViewModel? Insert(MessageInfoBindingModel model); + } +} diff --git a/LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs b/LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs new file mode 100644 index 0000000..c5283b5 --- /dev/null +++ b/LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs @@ -0,0 +1,25 @@ +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 MessageInfoViewModel : IMessageInfoModel + { + public string MessageId { get; set; } = string.Empty; + + public int? ClientId { get; set; } + [DisplayName("Отправитель")] + public string SenderName { get; set; } = string.Empty; + [DisplayName("Дата письма")] + public DateTime DateDelivery { get; set; } + [DisplayName("Заголовок")] + public string Subject { get; set; } = string.Empty; + [DisplayName("Текст")] + public string Body { get; set; } = string.Empty; + } +} diff --git a/LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs b/LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs new file mode 100644 index 0000000..91ba52c --- /dev/null +++ b/LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmDataModels.Models +{ + public interface IMessageInfoModel + { + string MessageId { get; } + int? ClientId { get; } + string SenderName { get; } + DateTime DateDelivery { get; } + string Subject { get; } + string Body { get; } + } +} -- 2.25.1 From 3fb0bddc53d99cda08868d66f4452991ce4c7689 Mon Sep 17 00:00:00 2001 From: Danila_Mochalov Date: Tue, 18 Apr 2023 20:49:28 +0400 Subject: [PATCH 2/4] =?UTF-8?q?=D0=BD=D0=B0=D1=80=D0=B5=D0=B0=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=BE=D0=B2=D1=8B=D0=B2=D0=B0=D0=BB=20=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9=20=D1=81=D1=82=D0=B5=D0=BA=20=D0=B8=D0=B7?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=B2=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BC=D0=BC=D0=B8=D1=82=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogics/MessageInfoLogic.cs | 48 +++ .../Implements/MessageInfoStorage .cs | 57 ++++ .../LawFirmDatabase.cs | 3 +- .../20230418164528_fixmessages.Designer.cs | 298 ++++++++++++++++++ .../Migrations/20230418164528_fixmessages.cs | 48 +++ .../LawFirmDatabaseModelSnapshot.cs | 41 +++ .../LawFirmDatabaseImplement/Models/Client.cs | 4 +- .../Models/MessageInfo.cs | 58 ++++ .../LawFirmFileImplement/DataFileSingleton.cs | 12 +- .../Implements/MessageInfoStorage.cs | 58 ++++ .../Models/MessageInfo.cs | 80 +++++ .../DataListSingleton.cs | 6 +- .../Implements/MessageInfoStorage.cs | 65 ++++ .../Models/MessageInfo.cs | 54 ++++ .../Controllers/ImplementerController.cs | 2 +- 15 files changed, 825 insertions(+), 9 deletions(-) create mode 100644 LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs create mode 100644 LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs create mode 100644 LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.Designer.cs create mode 100644 LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.cs create mode 100644 LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs create mode 100644 LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs create mode 100644 LawFirm/LawFirmFileImplement/Models/MessageInfo.cs create mode 100644 LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs create mode 100644 LawFirm/LawFirmListImplements/Models/MessageInfo.cs diff --git a/LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..3af0179 --- /dev/null +++ b/LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,48 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.BusinessLogicContracts; +using LawFirmContracts.SearchModels; +using LawFirmContracts.StorageContracts; +using LawFirmContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + { + _logger = logger; + _messageInfoStorage = MessageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs b/LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs new file mode 100644 index 0000000..a0aa21c --- /dev/null +++ b/LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs @@ -0,0 +1,57 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.SearchModels; +using LawFirmContracts.StorageContracts; +using LawFirmContracts.ViewModels; +using LawFirmDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmDatabaseImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + using var context = new LawFirmDatabase(); + if (model.MessageId != null) + { + return context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + using var context = new LawFirmDatabase(); + return context.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new LawFirmDatabase(); + return context.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + using var context = new LawFirmDatabase(); + var newMessage = MessageInfo.Create(model); + if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) + { + return null; + } + context.Messages.Add(newMessage); + context.SaveChanges(); + return newMessage.GetViewModel; + } + } +} diff --git a/LawFirm/LawFirmDatabaseImplement/LawFirmDatabase.cs b/LawFirm/LawFirmDatabaseImplement/LawFirmDatabase.cs index 30201a6..3131e56 100644 --- a/LawFirm/LawFirmDatabaseImplement/LawFirmDatabase.cs +++ b/LawFirm/LawFirmDatabaseImplement/LawFirmDatabase.cs @@ -25,6 +25,7 @@ namespace LawFirmDatabaseImplement public virtual DbSet Orders { set; get; } public virtual DbSet Clients { set; get; } public virtual DbSet Implementers { set; get; } + public virtual DbSet Messages { set; get; } - } + } } diff --git a/LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.Designer.cs b/LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.Designer.cs new file mode 100644 index 0000000..c0ecfe9 --- /dev/null +++ b/LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.Designer.cs @@ -0,0 +1,298 @@ +// +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("20230418164528_fixmessages")] + partial class fixmessages + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BlankName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Blanks"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DocumentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Documents"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BlankId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DocumentId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BlankId"); + + b.HasIndex("DocumentId"); + + b.ToTable("DocumentBlanks"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("DocumentId") + .HasColumnType("int"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("DocumentId"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Orders"); + }); + + 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.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"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.cs b/LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.cs new file mode 100644 index 0000000..29e77b7 --- /dev/null +++ b/LawFirm/LawFirmDatabaseImplement/Migrations/20230418164528_fixmessages.cs @@ -0,0 +1,48 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LawFirmDatabaseImplement.Migrations +{ + /// + public partial class fixmessages : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Messages", + columns: table => new + { + MessageId = table.Column(type: "nvarchar(450)", nullable: false), + ClientId = table.Column(type: "int", nullable: true), + SenderName = table.Column(type: "nvarchar(max)", nullable: false), + DateDelivery = table.Column(type: "datetime2", nullable: false), + Subject = table.Column(type: "nvarchar(max)", nullable: false), + Body = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Messages", x => x.MessageId); + table.ForeignKey( + name: "FK_Messages_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_Messages_ClientId", + table: "Messages", + column: "ClientId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Messages"); + } + } +} diff --git a/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs b/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs index 616aac2..44ae9ad 100644 --- a/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs +++ b/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs @@ -140,6 +140,36 @@ namespace LawFirmDatabaseImplement.Migrations b.ToTable("Implementers"); }); + modelBuilder.Entity("LawFirmDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b => { b.Property("Id") @@ -202,6 +232,15 @@ namespace LawFirmDatabaseImplement.Migrations 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") @@ -234,6 +273,8 @@ namespace LawFirmDatabaseImplement.Migrations modelBuilder.Entity("LawFirmDatabaseImplement.Models.Client", b => { + b.Navigation("Messages"); + b.Navigation("Orders"); }); diff --git a/LawFirm/LawFirmDatabaseImplement/Models/Client.cs b/LawFirm/LawFirmDatabaseImplement/Models/Client.cs index 2c7af5e..e6f2a28 100644 --- a/LawFirm/LawFirmDatabaseImplement/Models/Client.cs +++ b/LawFirm/LawFirmDatabaseImplement/Models/Client.cs @@ -26,8 +26,10 @@ namespace LawFirmDatabaseImplement.Models [ForeignKey("ClientId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("ClientId")] + public virtual List Messages { get; set; } = new(); - public static Client? Create(ClientBindingModel model) + public static Client? Create(ClientBindingModel model) { if (model == null) { diff --git a/LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs b/LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..f5ceea7 --- /dev/null +++ b/LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs @@ -0,0 +1,58 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.ViewModels; +using LawFirmDataModels.Models; +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 MessageInfo : IMessageInfoModel + { + [Key] + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public virtual Client? Client { get; private set; } + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + } +} diff --git a/LawFirm/LawFirmFileImplement/DataFileSingleton.cs b/LawFirm/LawFirmFileImplement/DataFileSingleton.cs index 95eb3e4..8219f31 100644 --- a/LawFirm/LawFirmFileImplement/DataFileSingleton.cs +++ b/LawFirm/LawFirmFileImplement/DataFileSingleton.cs @@ -17,12 +17,14 @@ namespace LawFirmFileImplement private readonly string DocumentFileName = "Document.xml"; private readonly string ClientFileName = "Client.xml"; private readonly string ImplementerFileName = "Implementer.xml"; - public List Blanks { get; private set; } + private readonly string MessageInfoFileName = "MessageInfo.xml"; + public List Blanks { get; private set; } public List Orders { get; private set; } public List Documents { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } - public static DataFileSingleton GetInstance() + public List Messages { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) { @@ -35,14 +37,16 @@ namespace LawFirmFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); - private DataFileSingleton() + public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement); + private DataFileSingleton() { Blanks = LoadData(BlankFileName, "Blank", x => Blank.Create(x)!)!; Documents = LoadData(DocumentFileName, "Document", x => Document.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Impleneter", x => Implementer.Create(x)!)!; - } + Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!; + } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { if (File.Exists(filename)) diff --git a/LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs b/LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..2c3e31b --- /dev/null +++ b/LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs @@ -0,0 +1,58 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.SearchModels; +using LawFirmContracts.StorageContracts; +using LawFirmContracts.ViewModels; +using LawFirmFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmFileImplement.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataFileSingleton _source; + public MessageInfoStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + if (model.MessageId != null) + { + return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + return _source.Messages + .Where(x => x.ClientId == model.ClientId) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + return _source.Messages + .Select(x => x.GetViewModel) + .ToList(); + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + _source.SaveMessages(); + return newMessage.GetViewModel; + } + } +} diff --git a/LawFirm/LawFirmFileImplement/Models/MessageInfo.cs b/LawFirm/LawFirmFileImplement/Models/MessageInfo.cs new file mode 100644 index 0000000..e218081 --- /dev/null +++ b/LawFirm/LawFirmFileImplement/Models/MessageInfo.cs @@ -0,0 +1,80 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.ViewModels; +using LawFirmDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace LawFirmFileImplement.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public static MessageInfo? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Body = element.Attribute("Body")!.Value, + Subject = element.Attribute("Subject")!.Value, + ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value), + MessageId = element.Attribute("MessageId")!.Value, + SenderName = element.Attribute("SenderName")!.Value, + DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value), + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + public XElement GetXElement => new("MessageInfo", + new XAttribute("Body", Body), + new XAttribute("Subject", Subject), + new XAttribute("ClientId", ClientId), + new XAttribute("MessageId", MessageId), + new XAttribute("SenderName", SenderName), + new XAttribute("DateDelivery", DateDelivery) + ); + } +} diff --git a/LawFirm/LawFirmListImplements/DataListSingleton.cs b/LawFirm/LawFirmListImplements/DataListSingleton.cs index b21cdbc..b10c9d9 100644 --- a/LawFirm/LawFirmListImplements/DataListSingleton.cs +++ b/LawFirm/LawFirmListImplements/DataListSingleton.cs @@ -16,14 +16,16 @@ namespace LawFirmListImplements public List Documents { get; set; } public List Clients { get; set; } public List Implementers { get; set; } - private DataListSingleton() + public List Messages { get; set; } + private DataListSingleton() { Blanks = new List(); Orders = new List(); Documents = new List(); Clients= new List(); Implementers = new List(); - } + Messages = new List(); + } public static DataListSingleton GetInstance() { if (_instance == null) diff --git a/LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs b/LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs new file mode 100644 index 0000000..a1cedde --- /dev/null +++ b/LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs @@ -0,0 +1,65 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.SearchModels; +using LawFirmContracts.StorageContracts; +using LawFirmContracts.ViewModels; +using LawFirmListImplements.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmListImplements.Implements +{ + public class MessageInfoStorage : IMessageInfoStorage + { + private readonly DataListSingleton _source; + public MessageInfoStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) + { + foreach (var message in _source.Messages) + { + if (model.MessageId != null && model.MessageId.Equals(message.MessageId)) return message.GetViewModel; + } + return null; + } + + public List GetFilteredList(MessageInfoSearchModel model) + { + List result = new(); + foreach (var item in _source.Messages) + { + if (item.ClientId.HasValue && item.ClientId == model.ClientId) + { + result.Add(item.GetViewModel); + } + } + return result; + } + + public List GetFullList() + { + List result = new(); + foreach (var item in _source.Messages) + { + result.Add(item.GetViewModel); + } + return result; + } + + public MessageInfoViewModel? Insert(MessageInfoBindingModel model) + { + var newMessage = MessageInfo.Create(model); + if (newMessage == null) + { + return null; + } + _source.Messages.Add(newMessage); + return newMessage.GetViewModel; + } + } +} diff --git a/LawFirm/LawFirmListImplements/Models/MessageInfo.cs b/LawFirm/LawFirmListImplements/Models/MessageInfo.cs new file mode 100644 index 0000000..4e051b7 --- /dev/null +++ b/LawFirm/LawFirmListImplements/Models/MessageInfo.cs @@ -0,0 +1,54 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.ViewModels; +using LawFirmDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmListImplements.Models +{ + public class MessageInfo : IMessageInfoModel + { + public string MessageId { get; private set; } = string.Empty; + + public int? ClientId { get; private set; } + + public string SenderName { get; private set; } = string.Empty; + + public DateTime DateDelivery { get; private set; } = DateTime.Now; + + public string Subject { get; private set; } = string.Empty; + + public string Body { get; private set; } = string.Empty; + + public static MessageInfo? Create(MessageInfoBindingModel model) + { + if (model == null) + { + return null; + } + return new() + { + Body = model.Body, + Subject = model.Subject, + ClientId = model.ClientId, + MessageId = model.MessageId, + SenderName = model.SenderName, + DateDelivery = model.DateDelivery, + }; + } + + public MessageInfoViewModel GetViewModel => new() + { + Body = Body, + Subject = Subject, + ClientId = ClientId, + MessageId = MessageId, + SenderName = SenderName, + DateDelivery = DateDelivery, + }; + + } +} diff --git a/LawFirm/LawFirmRestApi/Controllers/ImplementerController.cs b/LawFirm/LawFirmRestApi/Controllers/ImplementerController.cs index ffe3bd1..fcb9c39 100644 --- a/LawFirm/LawFirmRestApi/Controllers/ImplementerController.cs +++ b/LawFirm/LawFirmRestApi/Controllers/ImplementerController.cs @@ -48,7 +48,7 @@ namespace LawFirmRestApi.Controllers { return _order.ReadList(new OrderSearchModel { - Statuses = new() { OrderStatus.Принят } + Status = OrderStatus.Принят }) ; } catch (Exception ex) -- 2.25.1 From 5528cd9ab8d94f79212e19c51259729d5b0bb78a Mon Sep 17 00:00:00 2001 From: Danila_Mochalov Date: Wed, 19 Apr 2023 02:03:56 +0400 Subject: [PATCH 3/4] =?UTF-8?q?=D1=87=D0=B0=D1=81=20=D0=BC=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=B8=D0=B7-=D0=B7=D0=B0=20=D0=BB?= =?UTF-8?q?=D0=B8=D1=88=D0=BD=D0=B5=D0=B3=D0=BE=20=D0=BF=D1=80=D0=BE=D0=B1?= =?UTF-8?q?=D0=B5=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LawFirm/LawFirm/App.config | 11 + LawFirm/LawFirm/FormMails.Designer.cs | 62 ++++ LawFirm/LawFirm/FormMails.cs | 49 +++ LawFirm/LawFirm/FormMails.resx | 60 ++++ LawFirm/LawFirm/FormMain.Designer.cs | 326 +++++++++--------- LawFirm/LawFirm/FormMain.cs | 297 ++++++++-------- LawFirm/LawFirm/LawFirmView.csproj | 8 + LawFirm/LawFirm/Program.cs | 45 ++- .../BusinessLogics/ClientLogic.cs | 11 +- .../BusinessLogics/OrderLogic.cs | 41 ++- .../LawFirmBusinessLogic.csproj | 1 + .../MailWorker/AbstractMailWorker.cs | 83 +++++ .../MailWorker/MailKitWorker.cs | 81 +++++ .../Controllers/HomeController.cs | 14 +- .../LawFirmClientApp/LawFirmClientApp.csproj | 8 + .../LawFirmClientApp/Views/Home/Mails.cshtml | 54 +++ .../Views/Shared/_Layout.cshtml | 3 + .../BindingModels/MailConfigBindingModel.cs | 18 + .../BindingModels/MailSendInfoBindingModel.cs | 16 + .../Controllers/ClientController.cs | 27 +- LawFirm/LawFirmRestApi/Program.cs | 17 + LawFirm/LawFirmRestApi/appsettings.json | 10 +- 22 files changed, 913 insertions(+), 329 deletions(-) create mode 100644 LawFirm/LawFirm/App.config create mode 100644 LawFirm/LawFirm/FormMails.Designer.cs create mode 100644 LawFirm/LawFirm/FormMails.cs create mode 100644 LawFirm/LawFirm/FormMails.resx create mode 100644 LawFirm/LawFirmBusinessLogic/MailWorker/AbstractMailWorker.cs create mode 100644 LawFirm/LawFirmBusinessLogic/MailWorker/MailKitWorker.cs create mode 100644 LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml create mode 100644 LawFirm/LawFirmContracts/BindingModels/MailConfigBindingModel.cs create mode 100644 LawFirm/LawFirmContracts/BindingModels/MailSendInfoBindingModel.cs diff --git a/LawFirm/LawFirm/App.config b/LawFirm/LawFirm/App.config new file mode 100644 index 0000000..9177656 --- /dev/null +++ b/LawFirm/LawFirm/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/LawFirm/LawFirm/FormMails.Designer.cs b/LawFirm/LawFirm/FormMails.Designer.cs new file mode 100644 index 0000000..cfb2a75 --- /dev/null +++ b/LawFirm/LawFirm/FormMails.Designer.cs @@ -0,0 +1,62 @@ +namespace LawFirmView +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(776, 426); + dataGridView.TabIndex = 0; + // + // FormMails + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(dataGridView); + Name = "FormMails"; + Text = "Письма"; + Load += FormMails_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/LawFirm/LawFirm/FormMails.cs b/LawFirm/LawFirm/FormMails.cs new file mode 100644 index 0000000..b3e9263 --- /dev/null +++ b/LawFirm/LawFirm/FormMails.cs @@ -0,0 +1,49 @@ +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 FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormMails_Load(object sender, EventArgs e) + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки писем"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } +} diff --git a/LawFirm/LawFirm/FormMails.resx b/LawFirm/LawFirm/FormMails.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/LawFirm/LawFirm/FormMails.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/LawFirm/LawFirm/FormMain.Designer.cs b/LawFirm/LawFirm/FormMain.Designer.cs index f37a9c4..56e8283 100644 --- a/LawFirm/LawFirm/FormMain.Designer.cs +++ b/LawFirm/LawFirm/FormMain.Designer.cs @@ -1,220 +1,218 @@ namespace LawFirmView { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.menuStrip = new System.Windows.Forms.MenuStrip(); - this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.бланкиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.документыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.исполнителиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.списокДокументовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.бланкиПоДокументамToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.dataGridView = new System.Windows.Forms.DataGridView(); - this.buttonCreateOrder = new System.Windows.Forms.Button(); - this.buttonSetToFinish = new System.Windows.Forms.Button(); - this.buttonUpdate = new System.Windows.Forms.Button(); - this.menuStrip.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); - this.SuspendLayout(); + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip = new MenuStrip(); + справочники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(); + buttonCreateOrder = new Button(); + buttonSetToFinish = new Button(); + buttonUpdate = new Button(); + письмаToolStripMenuItem = new ToolStripMenuItem(); + menuStrip.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); // // menuStrip // - this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); - this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.справочникиToolStripMenuItem, - this.отчетыToolStripMenuItem, - this.запускРаботToolStripMenuItem}); - this.menuStrip.Location = new System.Drawing.Point(0, 0); - this.menuStrip.Name = "menuStrip"; - this.menuStrip.Size = new System.Drawing.Size(1139, 28); - this.menuStrip.TabIndex = 0; - this.menuStrip.Text = "Справочники"; + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, запускРаботToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1139, 28); + menuStrip.TabIndex = 0; + menuStrip.Text = "Справочники"; // // справочникиToolStripMenuItem // - this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.бланкиToolStripMenuItem, - this.документыToolStripMenuItem, - this.клиентыToolStripMenuItem, - this.исполнителиToolStripMenuItem}); - this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24); - this.справочникиToolStripMenuItem.Text = "Справочники"; + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { бланкиToolStripMenuItem, документыToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem, письмаToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(117, 24); + справочникиToolStripMenuItem.Text = "Справочники"; // // бланкиToolStripMenuItem // - this.бланкиToolStripMenuItem.Name = "бланкиToolStripMenuItem"; - this.бланкиToolStripMenuItem.Size = new System.Drawing.Size(185, 26); - this.бланкиToolStripMenuItem.Text = "Бланки"; - this.бланкиToolStripMenuItem.Click += new System.EventHandler(this.бланкиToolStripMenuItem_Click); + бланкиToolStripMenuItem.Name = "бланкиToolStripMenuItem"; + бланкиToolStripMenuItem.Size = new Size(224, 26); + бланкиToolStripMenuItem.Text = "Бланки"; + бланкиToolStripMenuItem.Click += бланкиToolStripMenuItem_Click; // // документыToolStripMenuItem // - this.документыToolStripMenuItem.Name = "документыToolStripMenuItem"; - this.документыToolStripMenuItem.Size = new System.Drawing.Size(185, 26); - this.документыToolStripMenuItem.Text = "Документы"; - this.документыToolStripMenuItem.Click += new System.EventHandler(this.документыToolStripMenuItem_Click); + документыToolStripMenuItem.Name = "документыToolStripMenuItem"; + документыToolStripMenuItem.Size = new Size(224, 26); + документыToolStripMenuItem.Text = "Документы"; + документыToolStripMenuItem.Click += документыToolStripMenuItem_Click; // // клиентыToolStripMenuItem // - this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; - this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(185, 26); - this.клиентыToolStripMenuItem.Text = "Клиенты"; - this.клиентыToolStripMenuItem.Click += new System.EventHandler(this.клиентыToolStripMenuItem_Click); + клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; + клиентыToolStripMenuItem.Size = new Size(224, 26); + клиентыToolStripMenuItem.Text = "Клиенты"; + клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click; // // исполнителиToolStripMenuItem // - this.исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; - this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(185, 26); - this.исполнителиToolStripMenuItem.Text = "Исполнители"; - this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.исполнителиToolStripMenuItem_Click); + исполнителиToolStripMenuItem.Name = "исполнителиToolStripMenuItem"; + исполнителиToolStripMenuItem.Size = new Size(224, 26); + исполнителиToolStripMenuItem.Text = "Исполнители"; + исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click; // // отчетыToolStripMenuItem // - this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.списокДокументовToolStripMenuItem, - this.бланкиПоДокументамToolStripMenuItem, - this.списокЗаказовToolStripMenuItem}); - this.отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(73, 24); - this.отчетыToolStripMenuItem.Text = "Отчеты"; + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДокументовToolStripMenuItem, бланкиПоДокументамToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(73, 24); + отчетыToolStripMenuItem.Text = "Отчеты"; // // списокДокументовToolStripMenuItem // - this.списокДокументовToolStripMenuItem.Name = "списокДокументовToolStripMenuItem"; - this.списокДокументовToolStripMenuItem.Size = new System.Drawing.Size(252, 26); - this.списокДокументовToolStripMenuItem.Text = "Список документов"; - this.списокДокументовToolStripMenuItem.Click += new System.EventHandler(this.списокДокументовToolStripMenuItem_Click); + списокДокументовToolStripMenuItem.Name = "списокДокументовToolStripMenuItem"; + списокДокументовToolStripMenuItem.Size = new Size(252, 26); + списокДокументовToolStripMenuItem.Text = "Список документов"; + списокДокументовToolStripMenuItem.Click += списокДокументовToolStripMenuItem_Click; // // бланкиПоДокументамToolStripMenuItem // - this.бланкиПоДокументамToolStripMenuItem.Name = "бланкиПоДокументамToolStripMenuItem"; - this.бланкиПоДокументамToolStripMenuItem.Size = new System.Drawing.Size(252, 26); - this.бланкиПоДокументамToolStripMenuItem.Text = "Бланки по документам"; - this.бланкиПоДокументамToolStripMenuItem.Click += new System.EventHandler(this.бланкиПоДокументамToolStripMenuItem_Click); + бланкиПоДокументамToolStripMenuItem.Name = "бланкиПоДокументамToolStripMenuItem"; + бланкиПоДокументамToolStripMenuItem.Size = new Size(252, 26); + бланкиПоДокументамToolStripMenuItem.Text = "Бланки по документам"; + бланкиПоДокументамToolStripMenuItem.Click += бланкиПоДокументамToolStripMenuItem_Click; // // списокЗаказовToolStripMenuItem // - this.списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(252, 26); - this.списокЗаказовToolStripMenuItem.Text = "Список заказов"; - this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.списокЗаказовToolStripMenuItem_Click); + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(252, 26); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // // запускРаботToolStripMenuItem // - this.запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; - this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(114, 24); - this.запускРаботToolStripMenuItem.Text = "Запуск работ"; - this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click); + запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem"; + запускРаботToolStripMenuItem.Size = new Size(114, 24); + запускРаботToolStripMenuItem.Text = "Запуск работ"; + запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click; // // dataGridView // - this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView.Location = new System.Drawing.Point(12, 31); - this.dataGridView.Name = "dataGridView"; - this.dataGridView.RowHeadersWidth = 51; - this.dataGridView.RowTemplate.Height = 29; - this.dataGridView.Size = new System.Drawing.Size(915, 407); - this.dataGridView.TabIndex = 1; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 31); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(915, 407); + dataGridView.TabIndex = 1; // // buttonCreateOrder // - this.buttonCreateOrder.Location = new System.Drawing.Point(933, 45); - this.buttonCreateOrder.Name = "buttonCreateOrder"; - this.buttonCreateOrder.Size = new System.Drawing.Size(194, 29); - this.buttonCreateOrder.TabIndex = 2; - this.buttonCreateOrder.Text = "Создать заказ"; - this.buttonCreateOrder.UseVisualStyleBackColor = true; - this.buttonCreateOrder.Click += new System.EventHandler(this.buttonCreateOrder_Click); + buttonCreateOrder.Location = new Point(933, 45); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(194, 29); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += buttonCreateOrder_Click; // // buttonSetToFinish // - this.buttonSetToFinish.Location = new System.Drawing.Point(933, 80); - this.buttonSetToFinish.Name = "buttonSetToFinish"; - this.buttonSetToFinish.Size = new System.Drawing.Size(194, 29); - this.buttonSetToFinish.TabIndex = 5; - this.buttonSetToFinish.Text = "Заказ выдан"; - this.buttonSetToFinish.UseVisualStyleBackColor = true; - this.buttonSetToFinish.Click += new System.EventHandler(this.buttonSetToFinish_Click); + buttonSetToFinish.Location = new Point(933, 80); + buttonSetToFinish.Name = "buttonSetToFinish"; + buttonSetToFinish.Size = new Size(194, 29); + buttonSetToFinish.TabIndex = 5; + buttonSetToFinish.Text = "Заказ выдан"; + buttonSetToFinish.UseVisualStyleBackColor = true; + buttonSetToFinish.Click += buttonSetToFinish_Click; // // buttonUpdate // - this.buttonUpdate.Location = new System.Drawing.Point(933, 410); - this.buttonUpdate.Name = "buttonUpdate"; - this.buttonUpdate.Size = new System.Drawing.Size(194, 29); - this.buttonUpdate.TabIndex = 6; - this.buttonUpdate.Text = "Обновить"; - this.buttonUpdate.UseVisualStyleBackColor = true; - this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click); + buttonUpdate.Location = new Point(933, 410); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(194, 29); + buttonUpdate.TabIndex = 6; + buttonUpdate.Text = "Обновить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // письмаToolStripMenuItem + // + письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + письмаToolStripMenuItem.Size = new Size(224, 26); + письмаToolStripMenuItem.Text = "Письма"; + письмаToolStripMenuItem.Click += письмаToolStripMenuItem_Click; // // FormMain // - this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1139, 450); - this.Controls.Add(this.buttonUpdate); - this.Controls.Add(this.buttonSetToFinish); - this.Controls.Add(this.buttonCreateOrder); - this.Controls.Add(this.dataGridView); - this.Controls.Add(this.menuStrip); - this.MainMenuStrip = this.menuStrip; - this.Name = "FormMain"; - this.Text = "Юридическая компания"; - this.Load += new System.EventHandler(this.FormMain_Load); - this.menuStrip.ResumeLayout(false); - this.menuStrip.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); - this.ResumeLayout(false); - this.PerformLayout(); + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1139, 450); + Controls.Add(buttonUpdate); + Controls.Add(buttonSetToFinish); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Name = "FormMain"; + Text = "Юридическая компания"; + Load += FormMain_Load; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - } + #endregion - #endregion - - private MenuStrip menuStrip; - private ToolStripMenuItem справочникиToolStripMenuItem; - private ToolStripMenuItem бланкиToolStripMenuItem; - private ToolStripMenuItem документыToolStripMenuItem; - private DataGridView dataGridView; - private Button buttonCreateOrder; - private Button buttonSetToFinish; - private Button buttonUpdate; - private ToolStripMenuItem отчетыToolStripMenuItem; - private ToolStripMenuItem списокДокументовToolStripMenuItem; - private ToolStripMenuItem бланкиПоДокументамToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - private ToolStripMenuItem клиентыToolStripMenuItem; - private ToolStripMenuItem исполнителиToolStripMenuItem; - private ToolStripMenuItem запускРаботToolStripMenuItem; - } + private MenuStrip menuStrip; + private ToolStripMenuItem справочникиToolStripMenuItem; + private ToolStripMenuItem бланкиToolStripMenuItem; + private ToolStripMenuItem документыToolStripMenuItem; + private DataGridView dataGridView; + private Button buttonCreateOrder; + private Button buttonSetToFinish; + private Button buttonUpdate; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem списокДокументовToolStripMenuItem; + private ToolStripMenuItem бланкиПоДокументамToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem клиентыToolStripMenuItem; + private ToolStripMenuItem исполнителиToolStripMenuItem; + private ToolStripMenuItem запускРаботToolStripMenuItem; + private ToolStripMenuItem письмаToolStripMenuItem; + } } \ No newline at end of file diff --git a/LawFirm/LawFirm/FormMain.cs b/LawFirm/LawFirm/FormMain.cs index 930af3f..1e1ad9a 100644 --- a/LawFirm/LawFirm/FormMain.cs +++ b/LawFirm/LawFirm/FormMain.cs @@ -17,162 +17,171 @@ using System.Windows.Forms; namespace LawFirmView { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; - private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - _workProcess = workProcess; - } + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; + private readonly IWorkProcess _workProcess; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + _workProcess = workProcess; + } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["DocumentId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["ImplementerId"].Visible = false; - } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["DocumentId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["ImplementerId"].Visible = false; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void бланкиToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormBlanks)); - if (service is FormBlanks form) - { - form.ShowDialog(); - } - } + private void бланкиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormBlanks)); + if (service is FormBlanks form) + { + form.ShowDialog(); + } + } - private void документыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormDocuments)); - if (service is FormDocuments form) - { - form.ShowDialog(); - } - } + private void документыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormDocuments)); + if (service is FormDocuments form) + { + form.ShowDialog(); + } + } - private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) - { - form.ShowDialog(); - } - } + private void клиентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormClients)); + if (service is FormClients form) + { + form.ShowDialog(); + } + } - private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); - if (service is FormImplementers form) - { - form.ShowDialog(); - } - } + private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormImplementers)); + if (service is FormImplementers form) + { + form.ShowDialog(); + } + } - private void бланкиПоДокументамToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportDocumentBlanks)); - if (service is FormReportDocumentBlanks form) - { - form.ShowDialog(); - } - } + private void бланкиПоДокументамToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportDocumentBlanks)); + if (service is FormReportDocumentBlanks form) + { + form.ShowDialog(); + } + } - private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrder)); - if (service is FormReportOrder form) - { - form.ShowDialog(); - } - } + private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrder)); + if (service is FormReportOrder form) + { + form.ShowDialog(); + } + } - private void списокДокументовToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveDocumentsToWordFile(new ReportBindingModel - { - FileName = dialog.FileName - }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } + private void списокДокументовToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveDocumentsToWordFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } - } + } - private void buttonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + private void buttonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } - private void buttonSetToFinish_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = id - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void buttonSetToFinish_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + 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 buttonUpdate_Click(object sender, EventArgs e) + { + LoadData(); + } - private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) - { - _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); - MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e) + { + _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic); + MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + } + + private void письмаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + } + } + } } diff --git a/LawFirm/LawFirm/LawFirmView.csproj b/LawFirm/LawFirm/LawFirmView.csproj index c75a088..00e97d5 100644 --- a/LawFirm/LawFirm/LawFirmView.csproj +++ b/LawFirm/LawFirm/LawFirmView.csproj @@ -8,6 +8,14 @@ enable + + + + + + + + all diff --git a/LawFirm/LawFirm/Program.cs b/LawFirm/LawFirm/Program.cs index b336e9b..d6c4074 100644 --- a/LawFirm/LawFirm/Program.cs +++ b/LawFirm/LawFirm/Program.cs @@ -1,6 +1,8 @@ using LawFirmBusinessLogic.BusinessLogics; +using LawFirmBusinessLogic.MailWorker; using LawFirmBusinessLogic.OfficePackage; using LawFirmBusinessLogic.OfficePackage.Implements; +using LawFirmContracts.BindingModels; using LawFirmContracts.BusinessLogicContracts; using LawFirmContracts.StorageContracts; using LawFirmDatabaseImplement.Implements; @@ -30,10 +32,33 @@ namespace LawFirm ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost =System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + + Application.Run(_serviceProvider.GetRequiredService()); } - private static void ConfigureServices(ServiceCollection services) + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + + private static void ConfigureServices(ServiceCollection services) { services.AddLogging(option => { @@ -45,20 +70,24 @@ namespace LawFirm services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddSingleton(); + + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -70,7 +99,9 @@ namespace LawFirm services.AddTransient(); services.AddTransient(); services.AddTransient(); - } + services.AddTransient(); + + } - } + } } diff --git a/LawFirm/LawFirmBusinessLogic/BusinessLogics/ClientLogic.cs b/LawFirm/LawFirmBusinessLogic/BusinessLogics/ClientLogic.cs index 96d08e1..e0c4e55 100644 --- a/LawFirm/LawFirmBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/LawFirm/LawFirmBusinessLogic/BusinessLogics/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace LawFirmBusinessLogic.BusinessLogics @@ -103,7 +104,15 @@ namespace LawFirmBusinessLogic.BusinessLogics { throw new ArgumentNullException("Нет логина(почты) клиента", nameof(model.Email)); } - _logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email); + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введен email клиента", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) + { + throw new ArgumentException("Некорректно введен пароль клиента", nameof(model.Password)); + } + _logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email); var element = _clientStorage.GetElement(new ClientSearchModel { Email = model.Email, diff --git a/LawFirm/LawFirmBusinessLogic/BusinessLogics/OrderLogic.cs b/LawFirm/LawFirmBusinessLogic/BusinessLogics/OrderLogic.cs index 1fcae27..dff58a7 100644 --- a/LawFirm/LawFirmBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/LawFirm/LawFirmBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,4 +1,5 @@ -using LawFirmContracts.BindingModels; +using LawFirmBusinessLogic.MailWorker; +using LawFirmContracts.BindingModels; using LawFirmContracts.BusinessLogicContracts; using LawFirmContracts.SearchModels; using LawFirmContracts.StorageContracts; @@ -17,12 +18,16 @@ namespace LawFirmBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; - } + _mailWorker = mailWorker; + _clientLogic = clientLogic; + } public bool CreateOrder(OrderBindingModel model) { @@ -33,13 +38,15 @@ namespace LawFirmBusinessLogic.BusinessLogics return false; } model.Status = OrderStatus.Принят; - if (_orderStorage.Insert(model) == null) + var result = _orderStorage.Insert(model); + if (result == null) { model.Status = OrderStatus.Неизвестен; _logger.LogWarning("Insert operation failed"); return false; } - return true; + SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят"); + return true; } public bool StatusUpdate(OrderBindingModel rawModel, OrderStatus newStatus) @@ -78,13 +85,15 @@ namespace LawFirmBusinessLogic.BusinessLogics } model.Status = newStatus; if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; - if (_orderStorage.Update(model) == null) + var result = _orderStorage.Update(model); + if (result == null) { model.Status--; _logger.LogWarning("Update operation failed"); return false; } - return true; + SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{result.Id} изменен статус на {result.Status}"); + return true; } public bool TakeOrderInWork(OrderBindingModel model) @@ -131,7 +140,23 @@ namespace LawFirmBusinessLogic.BusinessLogics return element; } - private void CheckModel(OrderBindingModel model, bool withParams = true) + private bool SendOrderStatusMail(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + if (client == null) + { + return false; + } + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; + } + + private void CheckModel(OrderBindingModel model, bool withParams = true) { if (model == null) { diff --git a/LawFirm/LawFirmBusinessLogic/LawFirmBusinessLogic.csproj b/LawFirm/LawFirmBusinessLogic/LawFirmBusinessLogic.csproj index 8daf646..f739ad1 100644 --- a/LawFirm/LawFirmBusinessLogic/LawFirmBusinessLogic.csproj +++ b/LawFirm/LawFirmBusinessLogic/LawFirmBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/LawFirm/LawFirmBusinessLogic/MailWorker/AbstractMailWorker.cs b/LawFirm/LawFirmBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..c0e1db4 --- /dev/null +++ b/LawFirm/LawFirmBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,83 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.BusinessLogicContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly IClientLogic _clientLogic; + private readonly ILogger _logger; + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + _clientLogic = clientLogic; + } + public void MailConfig(MailConfigBindingModel config) + { + _mailLogin = config.MailLogin; + _mailPassword = config.MailPassword; + _smtpClientHost = config.SmtpClientHost; + _smtpClientPort = config.SmtpClientPort; + _popHost = config.PopHost; + _popPort = config.PopPort; + _logger.LogDebug("Config: {login}, {password}, {clientHost},{ clientPOrt}, { popHost}, { popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort); + } + public async void MailSendAsync(MailSendInfoBindingModel info) + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) + { + return; + } + if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) + { + return; + } + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id; + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> + ReceiveMailAsync(); + + } +} diff --git a/LawFirm/LawFirmBusinessLogic/MailWorker/MailKitWorker.cs b/LawFirm/LawFirmBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..56410f0 --- /dev/null +++ b/LawFirm/LawFirmBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,81 @@ +using LawFirmContracts.BindingModels; +using LawFirmContracts.BusinessLogicContracts; +using MailKit.Net.Pop3; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Mail; +using System.Security.Authentication; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic) : base(logger, messageInfoLogic, clientLogic) { } + protected override async Task SendMailAsync(MailSendInfoBindingModel info) + { + using var objMailMessage = new MailMessage(); + using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); + try + { + objMailMessage.From = new MailAddress(_mailLogin); + objMailMessage.To.Add(new MailAddress(info.MailAddress)); + objMailMessage.Subject = info.Subject; + objMailMessage.Body = info.Text; + objMailMessage.SubjectEncoding = Encoding.UTF8; + objMailMessage.BodyEncoding = Encoding.UTF8; + objSmtpClient.UseDefaultCredentials = false; + objSmtpClient.EnableSsl = true; + objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; + objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); + await Task.Run(() => objSmtpClient.Send(objMailMessage)); + } + catch (Exception) + { + throw; + } + } + protected override async Task> + ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + + } +} diff --git a/LawFirm/LawFirmClientApp/Controllers/HomeController.cs b/LawFirm/LawFirmClientApp/Controllers/HomeController.cs index 84943ea..101374a 100644 --- a/LawFirm/LawFirmClientApp/Controllers/HomeController.cs +++ b/LawFirm/LawFirmClientApp/Controllers/HomeController.cs @@ -2,6 +2,7 @@ using LawFirmContracts.BindingModels; using LawFirmContracts.ViewModels; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using System.Diagnostics; namespace LawFirmClientApp.Controllers @@ -135,5 +136,16 @@ namespace LawFirmClientApp.Controllers return count * (doc?.Price ?? 1); } - } + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + } + + + } } \ No newline at end of file diff --git a/LawFirm/LawFirmClientApp/LawFirmClientApp.csproj b/LawFirm/LawFirmClientApp/LawFirmClientApp.csproj index 4309d17..36b7170 100644 --- a/LawFirm/LawFirmClientApp/LawFirmClientApp.csproj +++ b/LawFirm/LawFirmClientApp/LawFirmClientApp.csproj @@ -14,4 +14,12 @@ + + + + + + <_ContentIncludedByDefault Remove="Views\Home\Mails.cshtml" /> + + diff --git a/LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml b/LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..850d41c --- /dev/null +++ b/LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,54 @@ +@using LawFirmContracts.ViewModels + +@model List + +@{ + ViewData["Title"] = "Mails"; +} + +
+

Письма

+
+ + +
+ @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } + + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => item.DateDelivery) + + @Html.DisplayFor(modelItem => item.Subject) + + @Html.DisplayFor(modelItem => item.Body) +
+ } +
\ No newline at end of file diff --git a/LawFirm/LawFirmClientApp/Views/Shared/_Layout.cshtml b/LawFirm/LawFirmClientApp/Views/Shared/_Layout.cshtml index 957bdb4..7ca7113 100644 --- a/LawFirm/LawFirmClientApp/Views/Shared/_Layout.cshtml +++ b/LawFirm/LawFirmClientApp/Views/Shared/_Layout.cshtml @@ -27,6 +27,9 @@ + diff --git a/LawFirm/LawFirmContracts/BindingModels/MailConfigBindingModel.cs b/LawFirm/LawFirmContracts/BindingModels/MailConfigBindingModel.cs new file mode 100644 index 0000000..86e906a --- /dev/null +++ b/LawFirm/LawFirmContracts/BindingModels/MailConfigBindingModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmContracts.BindingModels +{ + public class MailConfigBindingModel + { + public string MailLogin { get; set; } = string.Empty; + public string MailPassword { get; set; } = string.Empty; + public string SmtpClientHost { get; set; } = string.Empty; + public int SmtpClientPort { get; set; } + public string PopHost { get; set; } = string.Empty; + public int PopPort { get; set; } + } +} diff --git a/LawFirm/LawFirmContracts/BindingModels/MailSendInfoBindingModel.cs b/LawFirm/LawFirmContracts/BindingModels/MailSendInfoBindingModel.cs new file mode 100644 index 0000000..6992e05 --- /dev/null +++ b/LawFirm/LawFirmContracts/BindingModels/MailSendInfoBindingModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LawFirmContracts.BindingModels +{ + public class MailSendInfoBindingModel + { + public string MailAddress { get; set; } = string.Empty; + public string Subject { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + } + +} diff --git a/LawFirm/LawFirmRestApi/Controllers/ClientController.cs b/LawFirm/LawFirmRestApi/Controllers/ClientController.cs index c564e39..792cf52 100644 --- a/LawFirm/LawFirmRestApi/Controllers/ClientController.cs +++ b/LawFirm/LawFirmRestApi/Controllers/ClientController.cs @@ -12,11 +12,14 @@ namespace LawFirmRestApi.Controllers { private readonly ILogger _logger; private readonly IClientLogic _logic; - public ClientController(IClientLogic logic, ILogger logger) + private readonly IMessageInfoLogic _mailLogic; + + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; _logic = logic; - } + _mailLogic = mailLogic; + } [HttpGet] public ClientViewModel? Login(string login, string password) { @@ -60,5 +63,23 @@ namespace LawFirmRestApi.Controllers throw; } } - } + + [HttpGet] + public List? GetMessages(int clientId) + { + try + { + return _mailLogic.ReadList(new MessageInfoSearchModel + { + ClientId = clientId + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения писем клиента"); + throw; + } + } + + } } diff --git a/LawFirm/LawFirmRestApi/Program.cs b/LawFirm/LawFirmRestApi/Program.cs index 9515ac5..1178c4f 100644 --- a/LawFirm/LawFirmRestApi/Program.cs +++ b/LawFirm/LawFirmRestApi/Program.cs @@ -1,4 +1,6 @@ using LawFirmBusinessLogic.BusinessLogics; +using LawFirmBusinessLogic.MailWorker; +using LawFirmContracts.BindingModels; using LawFirmContracts.BusinessLogicContracts; using LawFirmContracts.StorageContracts; using LawFirmDatabaseImplement.Implements; @@ -12,9 +14,13 @@ builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddSingleton(); +builder.Services.AddTransient(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -30,6 +36,17 @@ builder.Services.AddSwaggerGen(c => var app = builder.Build(); +var mailSender = app.Services.GetService(); +mailSender?.MailConfig(new MailConfigBindingModel +{ + MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty, + MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty, + SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty, + SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()), + PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty, + PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString()) +}); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/LawFirm/LawFirmRestApi/appsettings.json b/LawFirm/LawFirmRestApi/appsettings.json index 10f68b8..3feea06 100644 --- a/LawFirm/LawFirmRestApi/appsettings.json +++ b/LawFirm/LawFirmRestApi/appsettings.json @@ -5,5 +5,13 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + + "SmtpClientHost": "smtp.gmail.com", + "SmtpClientPort": "587", + "PopHost": "pop.gmail.com", + "PopPort": "995", + "MailLogin": "ulstulabs4me@gmail.com", + "MailPassword": "fmir rydi kqvu lklv" + } -- 2.25.1 From c0fc48b7e4e9e301c44be466bb102fb4ada55647 Mon Sep 17 00:00:00 2001 From: Danila_Mochalov Date: Sat, 22 Apr 2023 13:48:42 +0400 Subject: [PATCH 4/4] Late night, come home Work sucks, I know She left me roses by the stairs Surprises let me know she cares --- LawFirm/LawFirm/FormMail.Designer.cs | 166 ++++++++ LawFirm/LawFirm/FormMail.cs | 81 ++++ LawFirm/LawFirm/FormMail.resx | 60 +++ LawFirm/LawFirm/FormMails.Designer.cs | 160 +++++--- LawFirm/LawFirm/FormMails.cs | 129 ++++-- LawFirm/LawFirm/Program.cs | 4 +- .../BusinessLogics/MessageInfoLogic.cs | 25 +- LawFirm/LawFirmClientApp/APIClient.cs | 3 +- .../Controllers/HomeController.cs | 57 ++- .../LawFirmClientApp/Views/Home/Mails.cshtml | 121 +++--- .../BindingModels/MessageInfoBindingModel.cs | 4 +- .../IMessageInfoLogic.cs | 4 +- .../SearchModels/MessageInfoSearchModel.cs | 2 + .../StorageContracts/IMessageInfoStorage.cs | 3 +- .../ViewModels/MessageInfoViewModel.cs | 6 +- .../Models/IMessageInfoModel.cs | 4 +- .../Implements/MessageInfoStorage .cs | 29 +- ...230422091213_MessageInfoUpdate.Designer.cs | 381 ++++++++++++++++++ .../20230422091213_MessageInfoUpdate.cs | 39 ++ .../LawFirmDatabaseModelSnapshot.cs | 6 + .../Models/MessageInfo.cs | 24 +- .../Implements/MessageInfoStorage.cs | 24 +- .../Models/MessageInfo.cs | 34 +- .../Implements/MessageInfoStorage.cs | 37 +- .../Models/MessageInfo.cs | 24 +- .../Controllers/ClientController.cs | 15 +- 26 files changed, 1253 insertions(+), 189 deletions(-) create mode 100644 LawFirm/LawFirm/FormMail.Designer.cs create mode 100644 LawFirm/LawFirm/FormMail.cs create mode 100644 LawFirm/LawFirm/FormMail.resx create mode 100644 LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.Designer.cs create mode 100644 LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.cs diff --git a/LawFirm/LawFirm/FormMail.Designer.cs b/LawFirm/LawFirm/FormMail.Designer.cs new file mode 100644 index 0000000..9c251e4 --- /dev/null +++ b/LawFirm/LawFirm/FormMail.Designer.cs @@ -0,0 +1,166 @@ +namespace LawFirmView +{ + partial class FormMail + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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; + } +} \ No newline at end of file diff --git a/LawFirm/LawFirm/FormMail.cs b/LawFirm/LawFirm/FormMail.cs new file mode 100644 index 0000000..7260511 --- /dev/null +++ b/LawFirm/LawFirm/FormMail.cs @@ -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 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); + } + } + } +} diff --git a/LawFirm/LawFirm/FormMail.resx b/LawFirm/LawFirm/FormMail.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/LawFirm/LawFirm/FormMail.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/LawFirm/LawFirm/FormMails.Designer.cs b/LawFirm/LawFirm/FormMails.Designer.cs index cfb2a75..d0e46dd 100644 --- a/LawFirm/LawFirm/FormMails.Designer.cs +++ b/LawFirm/LawFirm/FormMails.Designer.cs @@ -1,62 +1,114 @@ namespace LawFirmView { - partial class FormMails - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - dataGridView = new DataGridView(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // dataGridView - // - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(12, 12); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(776, 426); - dataGridView.TabIndex = 0; - // - // FormMails - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); - Controls.Add(dataGridView); - Name = "FormMails"; - Text = "Письма"; - Load += FormMails_Load; - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonPrevPage = new Button(); + buttonNextPage = new Button(); + labelPage = new Label(); + buttonReply = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(776, 426); + dataGridView.TabIndex = 0; + // + // buttonPrevPage + // + buttonPrevPage.Location = new Point(594, 444); + buttonPrevPage.Name = "buttonPrevPage"; + buttonPrevPage.Size = new Size(94, 29); + buttonPrevPage.TabIndex = 1; + 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; + } } \ No newline at end of file diff --git a/LawFirm/LawFirm/FormMails.cs b/LawFirm/LawFirm/FormMails.cs index b3e9263..b62e70b 100644 --- a/LawFirm/LawFirm/FormMails.cs +++ b/LawFirm/LawFirm/FormMails.cs @@ -1,4 +1,6 @@ -using LawFirmContracts.BusinessLogicContracts; +using LawFirm; +using LawFirmContracts.BusinessLogicContracts; +using LawFirmContracts.ViewModels; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -12,38 +14,99 @@ using System.Windows.Forms; namespace LawFirmView { - public partial class FormMails : Form - { - private readonly ILogger _logger; - private readonly IMessageInfoLogic _logic; + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _logic; + private int currentPage = 1; + public int pageSize = 2; - public FormMails(ILogger logger, IMessageInfoLogic logic) - { - InitializeComponent(); - _logger = logger; - _logic = logic; - } + public FormMails(ILogger logger, IMessageInfoLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + buttonPrevPage.Enabled = false; + } - private void FormMails_Load(object sender, EventArgs e) - { - try - { - var list = _logic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["ClientId"].Visible = false; - dataGridView.Columns["MessageId"].Visible = false; - dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка писем"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки писем"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } + private void FormMails_Load(object sender, EventArgs e) + { + LoadMail(); + } + + private bool LoadMail() + { + try + { + var list = _logic.ReadList(new() + { + Page = currentPage, + PageSize = pageSize, + }); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка писем"); + labelPage.Text = $"Страница: {currentPage}"; + return true; + } + 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)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 service = Program.ServiceProvider?.GetService(typeof(FormMail)); + if (service is FormMail form) + { + form.MessageId = (string)(dataGridView.SelectedRows[0].Cells["MessageId"].Value); + form.ShowDialog(); + LoadMail(); + } + } + } + } } diff --git a/LawFirm/LawFirm/Program.cs b/LawFirm/LawFirm/Program.cs index 46a8947..ae3b151 100644 --- a/LawFirm/LawFirm/Program.cs +++ b/LawFirm/LawFirm/Program.cs @@ -109,8 +109,8 @@ namespace LawFirm services.AddTransient(); services.AddTransient(); services.AddTransient(); - - } + services.AddTransient(); + } } } diff --git a/LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs index 3af0179..876ec4a 100644 --- a/LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs +++ b/LawFirm/LawFirmBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -32,7 +32,18 @@ namespace LawFirmBusinessLogic.BusinessLogics return true; } - public List? 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? ReadList(MessageInfoSearchModel? model) { _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId); var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); @@ -44,5 +55,15 @@ namespace LawFirmBusinessLogic.BusinessLogics _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } - } + + public bool Update(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + } } diff --git a/LawFirm/LawFirmClientApp/APIClient.cs b/LawFirm/LawFirmClientApp/APIClient.cs index a7c2766..cd3f657 100644 --- a/LawFirm/LawFirmClientApp/APIClient.cs +++ b/LawFirm/LawFirmClientApp/APIClient.cs @@ -10,7 +10,8 @@ namespace LawFirmClientApp { private static readonly HttpClient _client = new(); 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.DefaultRequestHeaders.Accept.Clear(); diff --git a/LawFirm/LawFirmClientApp/Controllers/HomeController.cs b/LawFirm/LawFirmClientApp/Controllers/HomeController.cs index 101374a..75e7712 100644 --- a/LawFirm/LawFirmClientApp/Controllers/HomeController.cs +++ b/LawFirm/LawFirmClientApp/Controllers/HomeController.cs @@ -4,6 +4,7 @@ using LawFirmContracts.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Diagnostics; +using System.Text; namespace LawFirmClientApp.Controllers { @@ -136,16 +137,54 @@ namespace LawFirmClientApp.Controllers return count * (doc?.Price ?? 1); } - [HttpGet] - public IActionResult Mails() - { - if (APIClient.Client == null) - { - return Redirect("~/Home/Enter"); - } - return View(APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client.Id}")); + [HttpGet] + public IActionResult Mails() + { + if (APIClient.Client == null) + { + return Redirect("~/Home/Enter"); + } + APIClient.CurrentPage = 0; + return View(); + } + + [HttpGet] + public Tuple? SwitchPage(bool isNext) + { + if (isNext) + { + APIClient.CurrentPage++; + } + else + { + if (APIClient.CurrentPage == 1) + { + return null; + } + APIClient.CurrentPage--; + } + + var messages = APIClient.GetRequest>($"api/client/getmessages?clientId={APIClient.Client!.Id}&pageNum={APIClient.CurrentPage}"); + if (isNext && (messages == null || messages.Count == 0)) + { + APIClient.CurrentPage--; + return Tuple.Create(null, null, APIClient.CurrentPage != 1, false); + } + + StringBuilder htmlTable = new(); + foreach (var mail in messages) + { + htmlTable.Append("" + + $"{mail.DateDelivery}" + + $"{mail.Subject}" + + $"{mail.Body}" + + "" + (mail.IsReaded ? "Прочитано" : "Непрочитано") + "" + + $"{mail.Reply}" + + ""); + } + return Tuple.Create(htmlTable.ToString(), APIClient.CurrentPage.ToString(), APIClient.CurrentPage != 1, true); } - } + } } \ No newline at end of file diff --git a/LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml b/LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml index 850d41c..155cc32 100644 --- a/LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml +++ b/LawFirm/LawFirmClientApp/Views/Home/Mails.cshtml @@ -1,54 +1,79 @@ -@using LawFirmContracts.ViewModels - -@model List - -@{ - ViewData["Title"] = "Mails"; +@{ + ViewData["Title"] = "Mails"; } -
-

Письма

+

Письма

-
- @{ - if (Model == null) - { -

Авторизируйтесь

- return; - } + + + + + + + + + + + + +
+ Дата + + Заголовок + + Текст + + Прочитано + + Ответ +
+ +
- - - - - - - - - - @foreach (var item in Model) - { - - - - - - } - -
- Дата письма - - Заголовок - - Текст -
- @Html.DisplayFor(modelItem => item.DateDelivery) - - @Html.DisplayFor(modelItem => item.Subject) - - @Html.DisplayFor(modelItem => item.Body) -
- } - \ No newline at end of file + \ No newline at end of file diff --git a/LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs b/LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs index e0cb256..6013785 100644 --- a/LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs +++ b/LawFirm/LawFirmContracts/BindingModels/MessageInfoBindingModel.cs @@ -20,5 +20,7 @@ namespace LawFirmContracts.BindingModels public string Subject { get; set; } = string.Empty; public string Body { get; set; } = string.Empty; - } + public bool IsReaded { get; set; } + public string? Reply { get; set; } + } } diff --git a/LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs b/LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs index 982278f..c39d930 100644 --- a/LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs +++ b/LawFirm/LawFirmContracts/BusinessLogicContracts/IMessageInfoLogic.cs @@ -13,5 +13,7 @@ namespace LawFirmContracts.BusinessLogicContracts { List? ReadList(MessageInfoSearchModel? model); bool Create(MessageInfoBindingModel model); - } + bool Update(MessageInfoBindingModel model); + MessageInfoViewModel? ReadElement(MessageInfoSearchModel model); + } } diff --git a/LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs b/LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs index cad0a9e..72e57c3 100644 --- a/LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs +++ b/LawFirm/LawFirmContracts/SearchModels/MessageInfoSearchModel.cs @@ -10,5 +10,7 @@ namespace LawFirmContracts.SearchModels { public int? ClientId { get; set; } public string? MessageId { get; set; } + public int? Page { get; set; } + public int? PageSize { get; set; } } } diff --git a/LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs b/LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs index 299fd48..da6f80c 100644 --- a/LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs +++ b/LawFirm/LawFirmContracts/StorageContracts/IMessageInfoStorage.cs @@ -15,5 +15,6 @@ namespace LawFirmContracts.StorageContracts List GetFilteredList(MessageInfoSearchModel model); MessageInfoViewModel? GetElement(MessageInfoSearchModel model); MessageInfoViewModel? Insert(MessageInfoBindingModel model); - } + MessageInfoViewModel? Update(MessageInfoBindingModel model); + } } diff --git a/LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs b/LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs index c5283b5..e864976 100644 --- a/LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs +++ b/LawFirm/LawFirmContracts/ViewModels/MessageInfoViewModel.cs @@ -21,5 +21,9 @@ namespace LawFirmContracts.ViewModels public string Subject { get; set; } = string.Empty; [DisplayName("Текст")] public string Body { get; set; } = string.Empty; - } + [DisplayName("Прочитано")] + public bool IsReaded { get; set; } + [DisplayName("Ответ")] + public string? Reply { get; set; } + } } diff --git a/LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs b/LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs index 91ba52c..3ed6238 100644 --- a/LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs +++ b/LawFirm/LawFirmDataModels/Models/IMessageInfoModel.cs @@ -14,5 +14,7 @@ namespace LawFirmDataModels.Models DateTime DateDelivery { get; } string Subject { get; } string Body { get; } - } + public bool IsReaded { get; } + public string? Reply { get; } + } } diff --git a/LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs b/LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs index a0aa21c..59aa5c4 100644 --- a/LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs +++ b/LawFirm/LawFirmDatabaseImplement/Implements/MessageInfoStorage .cs @@ -3,6 +3,7 @@ using LawFirmContracts.SearchModels; using LawFirmContracts.StorageContracts; using LawFirmContracts.ViewModels; using LawFirmDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; @@ -27,10 +28,16 @@ namespace LawFirmDatabaseImplement.Implements public List GetFilteredList(MessageInfoSearchModel model) { using var context = new LawFirmDatabase(); - return context.Messages - .Where(x => x.ClientId == model.ClientId) - .Select(x => x.GetViewModel) - .ToList(); + var messages = context.Messages + .Where(x => (model.ClientId == null) || (x.ClientId == model.ClientId)) + .Select(x => x.GetViewModel); + + 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 GetFullList() @@ -53,5 +60,17 @@ namespace LawFirmDatabaseImplement.Implements context.SaveChanges(); 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; + } + } } diff --git a/LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.Designer.cs b/LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.Designer.cs new file mode 100644 index 0000000..d925b2a --- /dev/null +++ b/LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.Designer.cs @@ -0,0 +1,381 @@ +// +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 + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BlankName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Blanks"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DocumentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Documents"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.DocumentBlank", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BlankId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DocumentId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BlankId"); + + b.HasIndex("DocumentId"); + + b.ToTable("DocumentBlanks"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImplementerFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("WorkExperience") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.MessageInfo", b => + { + b.Property("MessageId") + .HasColumnType("nvarchar(450)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("DateDelivery") + .HasColumnType("datetime2"); + + b.Property("IsReaded") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + + b.Property("SenderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Subject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("MessageId"); + + b.HasIndex("ClientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("DocumentId") + .HasColumnType("int"); + + b.Property("ImplementerId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("MaxCountDocuments") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OpeningDate") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("LawFirmDatabaseImplement.Models.ShopDocument", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DocumentId") + .HasColumnType("int"); + + b.Property("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 + } + } +} diff --git a/LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.cs b/LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.cs new file mode 100644 index 0000000..7b2c586 --- /dev/null +++ b/LawFirm/LawFirmDatabaseImplement/Migrations/20230422091213_MessageInfoUpdate.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LawFirmDatabaseImplement.Migrations +{ + /// + public partial class MessageInfoUpdate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsReaded", + table: "Messages", + type: "bit", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "Reply", + table: "Messages", + type: "nvarchar(max)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsReaded", + table: "Messages"); + + migrationBuilder.DropColumn( + name: "Reply", + table: "Messages"); + } + } +} diff --git a/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs b/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs index f4a3261..ed7c45b 100644 --- a/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs +++ b/LawFirm/LawFirmDatabaseImplement/Migrations/LawFirmDatabaseModelSnapshot.cs @@ -155,6 +155,12 @@ namespace LawFirmDatabaseImplement.Migrations b.Property("DateDelivery") .HasColumnType("datetime2"); + b.Property("IsReaded") + .HasColumnType("bit"); + + b.Property("Reply") + .HasColumnType("nvarchar(max)"); + b.Property("SenderName") .IsRequired() .HasColumnType("nvarchar(max)"); diff --git a/LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs b/LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs index f5ceea7..2fe0829 100644 --- a/LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs +++ b/LawFirm/LawFirmDatabaseImplement/Models/MessageInfo.cs @@ -26,8 +26,10 @@ namespace LawFirmDatabaseImplement.Models public string Body { get; private set; } = string.Empty; 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) { @@ -41,10 +43,22 @@ namespace LawFirmDatabaseImplement.Models MessageId = model.MessageId, SenderName = model.SenderName, 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, Subject = Subject, @@ -52,7 +66,9 @@ namespace LawFirmDatabaseImplement.Models MessageId = MessageId, SenderName = SenderName, DateDelivery = DateDelivery, - }; + Reply = Reply, + IsReaded = IsReaded, + }; } } diff --git a/LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs b/LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs index 2c3e31b..00e59d7 100644 --- a/LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs +++ b/LawFirm/LawFirmFileImplement/Implements/MessageInfoStorage.cs @@ -30,10 +30,15 @@ namespace LawFirmFileImplement.Implements public List GetFilteredList(MessageInfoSearchModel model) { - return _source.Messages + var messages = _source.Messages .Where(x => x.ClientId == model.ClientId) - .Select(x => x.GetViewModel) - .ToList(); + .Select(x => x.GetViewModel); + + 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 GetFullList() @@ -54,5 +59,16 @@ namespace LawFirmFileImplement.Implements _source.SaveMessages(); 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; + } + } } diff --git a/LawFirm/LawFirmFileImplement/Models/MessageInfo.cs b/LawFirm/LawFirmFileImplement/Models/MessageInfo.cs index e218081..740f504 100644 --- a/LawFirm/LawFirmFileImplement/Models/MessageInfo.cs +++ b/LawFirm/LawFirmFileImplement/Models/MessageInfo.cs @@ -23,8 +23,10 @@ namespace LawFirmFileImplement.Models public string Subject { 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) { @@ -38,7 +40,9 @@ namespace LawFirmFileImplement.Models MessageId = model.MessageId, SenderName = model.SenderName, DateDelivery = model.DateDelivery, - }; + Reply = model.Reply, + IsReaded = model.IsReaded, + }; } public static MessageInfo? Create(XElement element) @@ -55,10 +59,22 @@ namespace LawFirmFileImplement.Models MessageId = element.Attribute("MessageId")!.Value, SenderName = element.Attribute("SenderName")!.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, Subject = Subject, @@ -66,7 +82,9 @@ namespace LawFirmFileImplement.Models MessageId = MessageId, SenderName = SenderName, DateDelivery = DateDelivery, - }; + Reply = Reply, + IsReaded = IsReaded, + }; public XElement GetXElement => new("MessageInfo", new XAttribute("Body", Body), @@ -74,7 +92,9 @@ namespace LawFirmFileImplement.Models new XAttribute("ClientId", ClientId), new XAttribute("MessageId", MessageId), new XAttribute("SenderName", SenderName), - new XAttribute("DateDelivery", DateDelivery) - ); + new XAttribute("DateDelivery", DateDelivery), + new XAttribute("Reply", Reply), + new XAttribute("HasRead", IsReaded) + ); } } diff --git a/LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs b/LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs index a1cedde..2bf75e5 100644 --- a/LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs +++ b/LawFirm/LawFirmListImplements/Implements/MessageInfoStorage.cs @@ -30,15 +30,29 @@ namespace LawFirmListImplements.Implements public List GetFilteredList(MessageInfoSearchModel model) { - List result = new(); + List messages = new(); 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 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 GetFullList() @@ -61,5 +75,18 @@ namespace LawFirmListImplements.Implements _source.Messages.Add(newMessage); 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; + } + } } diff --git a/LawFirm/LawFirmListImplements/Models/MessageInfo.cs b/LawFirm/LawFirmListImplements/Models/MessageInfo.cs index 4e051b7..ea0cc0a 100644 --- a/LawFirm/LawFirmListImplements/Models/MessageInfo.cs +++ b/LawFirm/LawFirmListImplements/Models/MessageInfo.cs @@ -22,8 +22,10 @@ namespace LawFirmListImplements.Models public string Subject { 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) { @@ -37,10 +39,22 @@ namespace LawFirmListImplements.Models MessageId = model.MessageId, SenderName = model.SenderName, 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, Subject = Subject, @@ -48,7 +62,9 @@ namespace LawFirmListImplements.Models MessageId = MessageId, SenderName = SenderName, DateDelivery = DateDelivery, - }; + Reply = Reply, + IsReaded = IsReaded, + }; } } diff --git a/LawFirm/LawFirmRestApi/Controllers/ClientController.cs b/LawFirm/LawFirmRestApi/Controllers/ClientController.cs index 792cf52..df5b117 100644 --- a/LawFirm/LawFirmRestApi/Controllers/ClientController.cs +++ b/LawFirm/LawFirmRestApi/Controllers/ClientController.cs @@ -13,8 +13,9 @@ namespace LawFirmRestApi.Controllers private readonly ILogger _logger; private readonly IClientLogic _logic; private readonly IMessageInfoLogic _mailLogic; + public int pageSize = 2; - public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) + public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger logger) { _logger = logger; _logic = logic; @@ -65,14 +66,16 @@ namespace LawFirmRestApi.Controllers } [HttpGet] - public List? GetMessages(int clientId) + public List? GetMessages(int clientId, int pageNum) { try { - return _mailLogic.ReadList(new MessageInfoSearchModel - { - ClientId = clientId - }); + return _mailLogic.ReadList(new() + { + ClientId = clientId, + Page = pageNum, + PageSize = pageSize + }); } catch (Exception ex) { -- 2.25.1