Server controller logic

This commit is contained in:
RavilGismatullin 2024-08-16 13:44:43 +04:00
parent 9bcec875a0
commit 23f4584b8a
12 changed files with 338 additions and 29 deletions

View File

@ -63,8 +63,7 @@ namespace ServiceSourceBusinessLogic.BusinessLogic {
return element;
}
public List<TaskViewModel>? ReadList(TaskSearchModel model) {
_logger.LogInformation($"ReadList.Id:{model.Id}");
public List<TaskViewModel>? ReadList() {
var list = _storage.GetFullList();
if (list == null) {
_logger.LogWarning("ReadList return null list");

View File

@ -1,9 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace ServiceSourceRestAPI.Controllers {
public class ClientController : Controller {
public IActionResult Index() {
return View();
}
}
}

View File

@ -1,9 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace ServiceSourceRestAPI.Controllers {
public class ExecutorController : Controller {
public IActionResult Index() {
return View();
}
}
}

View File

@ -1,9 +1,236 @@
using Microsoft.AspNetCore.Mvc;
using DocumentFormat.OpenXml.Presentation;
using Microsoft.AspNetCore.Mvc;
using ServiceSourceBusinessLogic.MailKitWorker;
using ServiceStationContracts.BindingModels;
using ServiceStationContracts.BusinessLogic;
using ServiceStationContracts.BusinessLogicContracts;
using ServiceStationContracts.SearchModels;
using ServiceStationContracts.ViewModels;
using ServiceStationDataModels.Models;
namespace ServiceSourceRestAPI.Controllers {
[Route("api/[controller]/[action]")]
[ApiController]
public class MainController : Controller {
public IActionResult Index() {
return View();
private readonly ILogger _logger;
private readonly IClientLogic _clientLogic;
private readonly IExecutorLogic _executorLogic;
private readonly IReportLogic _reportLogic;
private readonly ITaskLogic _taskLogic;
private readonly IWorkLogic _workLogic;
private readonly AbstractMailWorker _mailWorker;
public MainController(ILogger<MainController> logger, IClientLogic clientLogic, IExecutorLogic executorLogic,
IReportLogic reportLogic, ITaskLogic taskLogic, IWorkLogic workLogic, AbstractMailWorker mailWorker) {
_logger = logger;
_clientLogic = clientLogic;
_executorLogic = executorLogic;
_reportLogic = reportLogic;
_taskLogic = taskLogic;
_workLogic = workLogic;
_mailWorker = mailWorker;
}
public void Register(ExecutorBindingModel model) {
try {
_executorLogic.Create(model);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
[HttpGet]
public ExecutorViewModel? Login (string email, string password) {
try {
return _executorLogic.ReadElement(new ExecutorSearchModel {
Email = email,
Password = password
});
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка входа в систему");
throw;
}
}
[HttpPost]
public void UpdateData(ExecutorBindingModel model) {
try {
_executorLogic.Update(model);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка обновления данных");
throw;
}
}
public WorkBindingModel Make_New_Record_Work(WorkFromWebBindingModel model) {
var record = new WorkBindingModel {
Id = model.Id,
Date = model.Date,
Price = model.Price,
ExecutorId = model.ExecutorId,
TaskId = model.TaskId,
ClientList = new()
};
foreach (char id in model.client_ids) {
if (int.TryParse(id.ToString(), out int _id)) {
var client = _clientLogic.ReadElement(new ClientSearchModel { Id = _id }) ?? throw new Exception("Ошибка получения данных");
record.ClientList.Add(client.Id, (client));
}
}
return record;
}
[HttpPost]
public void CreateWork(WorkFromWebBindingModel model) {
var record = Make_New_Record_Work(model);
try {
_workLogic.Create(record);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания работы");
throw;
}
}
[HttpPost]
public void UpdateWork(WorkFromWebBindingModel model) {
var record = Make_New_Record_Work(model);
try {
_workLogic.Update(record);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка обновления работы");
}
}
[HttpPost]
public void DeleteWork(WorkBindingModel model) {
try {
_workLogic.Delete(model);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка удаления работы");
throw;
}
}
[HttpGet]
public List<WorkViewModel>? GetWorks(int _executorId) {
try {
return _workLogic.ReadList(new WorkSearchModel {
ExecutorId = _executorId
});
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения работ исполнителя || id = {_executorId}");
throw;
}
}
[HttpGet]
public WorkViewModel? GetWork(int _workId) {
try {
return _workLogic.ReadElement(new WorkSearchModel { Id = _workId });
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения работы || work_id = {_workId}");
throw;
}
}
[HttpGet]
public List<TaskViewModel>? GetTasks() {
try {
return _taskLogic.ReadList();
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения задач");
throw;
}
}
[HttpGet]
public List<ClientViewModel>? GetClients() {
try {
return _clientLogic.ReadList();
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка получения клиентов");
throw;
}
}
// todo Post method -- AddClientPoints
public List<int> Make_Report_Ids(string _ids) {
var ids = new List<int>();
foreach (char id in _ids) {
if (int.TryParse(id.ToString(), out int _id)) {
ids.Add(_id);
}
}
return ids;
}
[HttpGet]
public byte[]? CreateWordReport(string _ids) {
var ids_list = Make_Report_Ids(_ids);
try {
var document = _reportLogic.SaveToWordFile(new ReportBindeingModel {
ids = ids_list
});
return document;
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания документа");
throw;
}
}
[HttpGet]
public byte[]? CreateXlsxReport(string _ids) {
var ids_list = Make_Report_Ids(_ids);
try {
var document = _reportLogic.SaveToExcelFile(new ReportBindeingModel {
ids = ids_list
});
return document;
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания документа");
throw;
}
}
[HttpPost]
public void SendReportPdfMail (ReportBindeingModel model) {
try {
var _document = _reportLogic.SaveToPdfFile(model);
MemoryStream stream = new();
_document.Save(stream, true);
byte[] data = stream.ToArray();
_mailWorker.MailSendAsync(new() {
MailAddress = model.EmailAddress,
Subject = "Отчет",
Text = $"Отчет по работам с указания назначенных заданий за период с {model.DateFrom.ToLongDateString()} по " +
$"{model.DateTo.ToShortDateString()}",
document = data
});
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания/отправки отчета на почту");
throw;
}
}
}
}

View File

@ -1,9 +1,52 @@
using Microsoft.OpenApi.Models;
using Serilog;
using ServiceSourceBusinessLogic.BusinessLogic;
using ServiceSourceBusinessLogic.MailKitWorker;
using ServiceSourceBusinessLogic.OfficePackage;
using ServiceSourceBusinessLogic.OfficePackage.Implements;
using ServiceStationContracts.BindingModels;
using ServiceStationContracts.BusinessLogic;
using ServiceStationContracts.BusinessLogicContracts;
using ServiceStationsContracts.StorageContracts;
using ServiceStationsDataBaseImplement.Implements;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddSession();
// Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IExecutorStorage, ExecutorStorage>();
builder.Services.AddTransient<ITaskStorage, TaskStorage>();
builder.Services.AddTransient<IWorkStorage, WorkStorage>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IExecutorLogic, ExecutorLogic>();
builder.Services.AddTransient<IReportLogic, ReportLogic>();
builder.Services.AddTransient<ITaskLogic, TaskLogic>();
builder.Services.AddTransient<IWorkLogic, WorkLogic>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcek>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddLogging(option => {
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.AddSerilog(logger);
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
@ -11,6 +54,17 @@ builder.Services.AddSwaggerGen(x => x.SwaggerDoc("v1", new OpenApiInfo { Title =
var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
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()) {
app.UseSwagger();
@ -18,10 +72,16 @@ if (app.Environment.IsDevelopment()) {
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -7,7 +7,17 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog" Version="4.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ServiceSourceBusinessLogic\ServiceSourceBusinessLogic.csproj" />
<ProjectReference Include="..\ServiceStationsDataBaseImplement\ServiceStationsDataBaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "servicesource408@gmail.com",
"MailPassword": "Service_source010234"
}

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
namespace ServiceStationContracts.BindingModels {
public class ReportBindeingModel {
public string EmailAddress { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }

View File

@ -0,0 +1,23 @@
using ServiceStationDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceStationContracts.BindingModels {
public class WorkFromWebBindingModel {
public int Id { get; set; }
public DateTime Date { get; set; } = DateTime.Now;
public double Price { get; set; }
public int ExecutorId { get; set; }
public int TaskId { get; set; }
public string client_ids { get; set; } = string.Empty;
}
}

View File

@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace ServiceStationContracts.BusinessLogicContracts {
public interface ITaskLogic {
List<TaskViewModel>? ReadList(TaskSearchModel model);
List<TaskViewModel>? ReadList();
TaskViewModel? ReadElement(TaskSearchModel model);
bool Create(TaskBindingModel model);

View File

@ -4,5 +4,6 @@
{
public int? Id { get; set; }
public string? Email { get; set; }
public string? Password { get; set; }
}
}

View File

@ -64,7 +64,7 @@ namespace ServiceStationsDataBaseImplement.Implements
else {
return context.Executors
.Include (x => x.Works)
.FirstOrDefault(x => x.Email == model.Email)
.FirstOrDefault(x => x.Email == model.Email && x.Password == model.Password)
?.GetViewModel;
}
}