Compare commits

...

2 Commits

44 changed files with 1819 additions and 224 deletions

View File

@ -10,6 +10,8 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.IdentityModel.Tokens;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
namespace CarCenterAdministratorApp.Controllers
{
@ -271,7 +273,8 @@ namespace CarCenterAdministratorApp.Controllers
{
AdministratorId = APIClient.Administrator.Id,
EquipmentName = equipmentName,
EquipmentPrice = equipmentPrice
EquipmentPrice = equipmentPrice,
DateCreateEquipment = DateTime.Now
});
for (int i = 0; i < cars.Length; i++)
{
@ -291,11 +294,12 @@ namespace CarCenterAdministratorApp.Controllers
return Redirect("~/Home/Enter");
}
ViewBag.Equipments = APIClient.GetRequest<List<EquipmentViewModel>>($"api/main/getequipmentlist?administratorId={APIClient.Administrator.Id}");
ViewBag.Cars = APIClient.GetRequest<List<CarViewModel>>($"api/main/getcarlist?administratorid={APIClient.Administrator.Id}");
return View();
}
[HttpPost]
public void UpdateEquipment(int equipment, string equipmentName, double equipmentPrice)
public void UpdateEquipment(int equipment, string equipmentName, double equipmentPrice, List<int> cars)
{
if (APIClient.Administrator == null)
{
@ -309,12 +313,18 @@ namespace CarCenterAdministratorApp.Controllers
{
throw new Exception("Введите стоимость");
}
Dictionary<int, ICarModel> a = new Dictionary<int, ICarModel>();
foreach (int car in cars)
{
a.Add(car, new CarSearchModel { Id = car } as ICarModel);
}
APIClient.PostRequest("api/main/updateequipment", new EquipmentBindingModel
{
Id = equipment,
AdministratorId = APIClient.Administrator.Id,
EquipmentName = equipmentName,
EquipmentPrice = equipmentPrice
EquipmentPrice = equipmentPrice,
EquipmentCars = a,
});
Response.Redirect("ListEquipments");
}
@ -402,12 +412,13 @@ namespace CarCenterAdministratorApp.Controllers
{
return Redirect("~/Home/Enter");
}
ViewBag.Cars = APIClient.GetRequest<List<CarViewModel>>($"api/main/getcarlist?administratorid={APIClient.Administrator.Id}");
ViewBag.Inspections = APIClient.GetRequest<List<InspectionViewModel>>($"api/main/getinspectionlist?administratorId={APIClient.Administrator.Id}");
return View();
}
[HttpPost]
public void UpdateInspection(int inspection, string inspectionName, DateTime inspectionDate, int[] cars)
public void UpdateInspection(int inspection, string inspectionName, DateTime inspectionDate, List<int> cars)
{
if (APIClient.Administrator == null)
{
@ -416,13 +427,19 @@ namespace CarCenterAdministratorApp.Controllers
if (string.IsNullOrEmpty(inspectionName))
{
throw new Exception("Введите название");
}
Dictionary<int, ICarModel> a = new Dictionary<int, ICarModel>();
foreach (int car in cars)
{
a.Add(car, new CarSearchModel { Id = car } as ICarModel);
}
APIClient.PostRequest("api/main/updateinspection", new InspectionBindingModel
{
Id = inspection,
AdministratorId = APIClient.Administrator.Id,
InspectionName = inspectionName,
InspectionDate = inspectionDate
InspectionDate = inspectionDate,
InspectionCars = a,
});
Response.Redirect("ListInspections");
}
@ -488,13 +505,109 @@ namespace CarCenterAdministratorApp.Controllers
});
Response.Redirect("ListEquipments");
}
public IActionResult ListCarsToPdfFile()
/*public IActionResult ListCarsToPdfFile()
{
return View();
}
public IActionResult ListCarEquipmentToFile()
{
return View();
}*/
[HttpGet]
public IActionResult Report()
{
ViewBag.Report = new List<ReportEquipmentsEmployeesBindingModel>();
return View();
}
[HttpGet]
public string GetCarsReport(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Administrator == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
List<ReportEquipmentsEmployeesViewModel> result;
try
{
string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
result = APIClient.GetRequest<List<ReportEquipmentsEmployeesViewModel>>
($"api/main/GetEquipmentsEmployeesReport?datefrom={dateFromS}&dateto={dateToS}&administratorid={APIClient.Administrator.Id}")!;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
string table = "";
table += "<h2 class=\"text-custom-color-1\">Предварительный отчет</h2>";
table += "<div class=\"table-responsive\">";
table += "<table class=\"table table-striped table-bordered table-hover\">";
table += "<thead class=\"table-dark\">";
table += "<tr>";
table += "<th scope=\"col\">Дата</th>";
table += "<th scope=\"col\">Название машины</th>";
table += "<th scope=\"col\">Комплектация</th>";
table += "<th scope=\"col\">Сотрудник</th>";
table += "</tr>";
table += "</thead>";
foreach (var car in result)
{
table += "<tbody>";
table += "<tr>";
table += $"<td></td>";
table += $"<td>{car.BrandCar}</td>";
table += $"<td></td>";
table += $"<td></td>";
table += "</tr>";
/*foreach (var equipment in car.Equipments)
{
table += "<tr>";
table += $"<td>{equipment.DateCreateEquipment}</td>";
table += $"<td></td>";
table += $"<td>{equipment.EquipmentName}</td>";
table += $"<td></td>";
table += "</tr>";
}
foreach (var employee in car.Employees)
{
table += "<tr>";
table += $"<td>{employee.EmployeeFIO}</td>";
table += $"<td></td>";
table += $"<td></td>";
table += $"<td>{employee.EmployeeInspection}</td>";
table += "</tr>";
}
table += "</tbody>";*/
}
table += "</table>";
table += "</div>";
return table;
}
[HttpPost]
public void Report(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Administrator == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/main/sendEquipmentsEmployeesreporttoemail", new ReportEquipmentsEmployeesBindingModel
{
FileName = "C:\\Users\\kozlo\\Desktop\\reports\\pdffile.pdf",
AdministratorId = APIClient.Administrator.Id,
DateFrom = dateFrom,
DateTo = dateTo,
Email = APIClient.Administrator.AdministratorEmail
});
Response.Redirect("Report");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]

View File

@ -1,43 +0,0 @@
@using CarCenterContracts.ViewModels;
@using CarCenterDataModels.Models;
@{
ViewData["Title"] = "AddCarToEquipment";
}
@model Tuple<List<EquipmentViewModel>, List<CarViewModel>>
<div class="container">
<h2>Добавление машин в комплектацию</h2>
<form method="post">
<div class="form-group">
<label for="equipment">Выберите комплектацию</label>
</div>
<div class="form-group">
<label for="car">Выберите комплектацию</label>
<div class="card">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table mb-0">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Бренд машины</th>
<th scope="col">Модель</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br>
<div class="u-container-layout u-container-layout-2">
<input type="submit" value="Добавить" class="btn btn-outline-dark text-center d-flex justify-content-md-center" />
</div>
</form>
</div>

View File

@ -1,36 +0,0 @@
@using CarCenterContracts.ViewModels;
@using CarCenterDataModels.Models;
@{
ViewData["Title"] = "AddCarToInspection";
}
@model Tuple<List<InspectionViewModel>, List<CarViewModel>>
<div class="container">
<h2>Добавление машин в осмотры</h2>
<form method="post">
<div class="form-group">
<label for="inspection">осмотры:</label>
</div>
<div class="form-group">
<label>Машины для осмотров:</label>
<div class="table-responsive">
<table class="table">
<thead class="thead-dark">
<tr>
<th>Бренд машины</th>
<th>Модель</th>
</
<tbody>
</tbody>
</table>
</div>
</div>
<br>
<div class="u-container-layout u-container-layout-2">
<input type="submit" value="Добавить" class="btn btn-outline-dark text-center d-flex justify-content-md-center" />
</div>
</form>
</div>

View File

@ -1,49 +0,0 @@
@using CarCenterContracts.ViewModels
@{
ViewData["Title"] = "ListCarsToPdfFile";
}
<div class="container">
<div class="text-center mb-4">
<h2 class="text-custom-color-1">Отчет по машинам за период</h2>
</div>
<form method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="dateFrom" class="form-label text-custom-color-1">Начало периода:</label>
<input type="datetime-local" id="dateFrom" name="dateFrom" class="form-control" placeholder="Выберите дату начала периода">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="dateTo" class="form-label text-custom-color-1">Окончание периода:</label>
<input type="datetime-local" id="dateTo" name="dateTo" class="form-control" placeholder="Выберите дату окончания периода">
</div>
</div>
</div>
<div class="form-group mb-4">
<label for="headwaiterEmail" class="form-label text-custom-color-1">Введите почту:</label>
<input type="email" id="headwaiterEmail" name="headwaiterEmail" class="form-control" placeholder="Введите вашу почту">
</div>
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Отправить на почту</button>
</div>
</div>
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="button" id="demonstrate" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Продемонстрировать</button>
</div>
</div>
<div id="report"></div>
</form>
</div>

View File

@ -26,9 +26,6 @@
<th class="u-border-1 u-border-grey-50 u-table-cell">
Стоимость
</th>
<th class="u-border-1 u-border-grey-50 u-table-cell">
Предпродажная работа
</th>
</tr>
</thead>
<tbody class="u-table-body">

View File

@ -0,0 +1,86 @@
@using CarCenterContracts.ViewModels
@{
ViewData["Title"] = "Report";
}
<div class="container">
<div class="text-center mb-4">
<h2 class="text-custom-color-1">Отчет по машинам за период</h2>
</div>
<form method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="dateFrom" class="form-label text-custom-color-1">Начало периода:</label>
<input type="date" id="dateFrom" name="dateFrom" class="form-control" placeholder="Выберите дату начала периода">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="dateTo" class="form-label text-custom-color-1">Окончание периода:</label>
<input type="date" id="dateTo" name="dateTo" class="form-control" placeholder="Выберите дату окончания периода">
</div>
</div>
</div>
@* <div class="form-group mb-4">
<label for="headwaiterEmail" class="form-label text-custom-color-1">Введите почту:</label>
<input type="email" id="headwaiterEmail" name="headwaiterEmail" class="form-control" placeholder="Введите вашу почту">
</div>
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Отправить на почту</button>
</div>
</div> *@
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Отправить на почту</button>
</div>
</div>
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="button" id="demonstrate" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Продемонстрировать</button>
</div>
</div>
@*
<div class="row mb-4">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="button" id="demonstrate" class="btn btn-outline-dark w-100 text-center d-flex justify-content-md-center">Продемонстрировать</button>
</div>
</div> *@
<div id="report"></div>
</form>
</div>
@section Scripts {
<script>
function check() {
var dateFrom = $('#dateFrom').val();
var dateTo = $('#dateTo').val();
if (dateFrom && dateTo) {
$.ajax({
method: "GET",
url: "/Home/GetCarsReport",
data: { dateFrom: dateFrom, dateTo: dateTo },
success: function (result) {
if (result != null) {
$('#report').html(result);
}
}
});
};
}
check();
$('#demonstrate').on('click', (e) => check());
</script>
}

View File

@ -28,7 +28,17 @@
name="equipmentPrice"
class="form-control" />
</div>
<div class="row">
<div class="col-4">Машины:</div>
<div class="col-8">
<select name="cars" class="form-control" multiple size="5" id="cars">
@foreach (var car in ViewBag.Cars)
{
<option value="@car.Id" data-name="@car.Id">@car.BrandCar</option>
}
</select>
</div>
</div>
</div>
<br>
<div class="u-container-layout u-container-layout-2">
@ -43,15 +53,19 @@
<script>
function check() {
var equipment = $('#equipment').val();
$("#cars option:selected").removeAttr("selected");
if (equipment) {
$.ajax({
method: "GET",
url: "/Home/GetEquipment",
data: { equipmentId: equipment },
success: function (result) {
$('#equipmentName').val(result.equipmentName);
$('#equipmentPrice').val(result.equipmentPrice);
$('#table-elements').html(result.item2);
$('#equipmentName').val(result.item1.equipmentName);
$('#equipmentPrice').val(result.item1.equipmentPrice);
$('#table-elements').html(result.item1.item2);
$.map(result.item2, function (n) {
$(`option[data-name=${n.item2}]`).attr("selected", "selected")
});
}
});
};

View File

@ -29,6 +29,18 @@
class="form-control" />
</div>
<div class="row">
<div class="col-4">Машины:</div>
<div class="col-8">
<select name="cars" class="form-control" multiple size="5" id="cars">
@foreach (var car in ViewBag.Cars)
{
<option value="@car.Id" data-name="@car.Id">@car.BrandCar</option>
}
</select>
</div>
</div>
</div>
<br>
<div class="u-container-layout u-container-layout-2">
@ -43,15 +55,19 @@
<script>
function check() {
var inspection = $('#inspection').val();
$("#cars option:selected").removeAttr("selected");
if (inspection) {
$.ajax({
method: "GET",
url: "/Home/GetInspection",
data: { inspectionId: inspection },
success: function (result) {
$('#inspectionName').val(result.inspectionName);
$('#inspectionDate').val(result.inspectionDate);
$('#table-elements').html(result.item2);
$('#inspectionName').val(result.item1.inspectionName);
$('#inspectionDate').val(result.item1.inspectionDate);
$('#table-elements').html(result.item1.item2);
$.map(result.item2, function (n) {
$(`option[data-name=${n.item2}]`).attr("selected", "selected")
});
}
});
};

View File

@ -42,7 +42,7 @@
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<li><a class="nav-link " asp-area="" asp-controller="Home" asp-action="ListCarEquipmentToFile">Отчет (word/excel) </a></li>
<li><a class="nav-link " asp-area="" asp-controller="Home" asp-action="ListCarsToPdfFile">Отчет (pdf) </a></li>
<li><a class="nav-link " asp-area="" asp-controller="Home" asp-action="Report">Отчет (pdf) </a></li>
</ul>
</li>

View File

@ -0,0 +1,72 @@
using CarCenterContracts.BindingModels;
using CarCenterContracts.BusinessLogicsContracts;
using CarCenterContracts.StoragesContracts;
using CarCenterContracts.ViewModels;
using CarCenterBusinessLogic.OfficePackage;
using CarCenterBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterBusinessLogic.BusinessLogics
{
public class ReportLogicAdministrator : IReportLogicAdministrator
{
private readonly ICarStorage _carStorage;
/*private readonly AbstractSaveToExcelDoctor _saveToExcel;
private readonly AbstractSaveToWordDoctor _saveToWord;*/
private readonly AbstractSaveToPdfAdministrator _saveToPdf;
public ReportLogicAdministrator(ICarStorage carStorage,
/*AbstractSaveToExcelDoctor saveToExcel, AbstractSaveToWordDoctor saveToWord,*/ AbstractSaveToPdfAdministrator saveToPdf)
{
_carStorage = carStorage;
/*_saveToExcel = saveToExcel;
_saveToWord = saveToWord;*/
_saveToPdf = saveToPdf;
}
/*public void SavePurchasesToExcelFile(ReportPurchaseMedicationBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfoDoctor
{
FileName = model.FileName,
Title = "Список покупок по медикаментам",
PurchaseMedications = GetPurchaseMedications(model)
});
}
public void SavePurchasesToWordFile(ReportPurchaseMedicationBindingModel model)
{
_saveToWord.CreateDoc(new WordInfoDoctor
{
FileName = model.FileName,
Title = "Список покупок по медикаментам",
PurchaseMedications = GetPurchaseMedications(model)
});
}*/
/*public List<ReportPurchaseMedicationViewModel> GetPurchaseMedications(ReportPurchaseMedicationBindingModel model)
{
return _medicationStorage.GetReportMedicationPurchasesList(new() { medicationsIds = model.Medications });
}*/
public List<ReportEquipmentsEmployeesViewModel> GetEquipmentsEmployees(ReportEquipmentsEmployeesBindingModel model)
{
return _carStorage.GetReportEquipmentsEmployees(new() { DateFrom = model.DateFrom, DateTo = model.DateTo });
}
public void SaveCarsToPdfFile(ReportEquipmentsEmployeesBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список машин",
DateFrom = model.DateFrom!,
DateTo = model.DateTo!,
ReportEquipmentsEmployees = GetEquipmentsEmployees(model)
});
}
}
}

View File

@ -7,7 +7,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,64 @@
using CarCenterContracts.BindingModels;
using CarCenterContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterBusinessLogic.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 IAdministratorLogic _administratorLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IAdministratorLogic administratorLogic)
{
_logger = logger;
_administratorLogic = administratorLogic;
}
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);
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,52 @@
using CarCenterContracts.BindingModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CarCenterContracts.BusinessLogicsContracts;
using CarCenterBusinessLogic.BusinessLogics;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CarCenterBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger, IAdministratorLogic administratorLogic) : base(logger, administratorLogic) { }
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;
Attachment attachment = new Attachment("C:\\Users\\kozlo\\Desktop\\reports\\pdffile.pdf", new ContentType(MediaTypeNames.Application.Pdf));
objMailMessage.Attachments.Add(attachment);
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;
}
}
}
}

View File

@ -0,0 +1,22 @@
using CarCenterBusinessLogic.OfficePackage.HelperModels;
namespace CarCenterBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
/// Создание pdf-файла
protected abstract void CreatePdf(PdfInfo info);
/// Создание параграфа с текстом
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// Создание таблицы
protected abstract void CreateTable(List<string> columns);
/// Создание и заполнение строки
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// Сохранение файла
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarCenterBusinessLogic.OfficePackage.HelperEnums;
using CarCenterBusinessLogic.OfficePackage.HelperModels;
/*using CarCenterDatabaseImplement.Implements;*/
namespace CarCenterBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdfAdministrator
{
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style =
"NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style
= "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "4cm", "4cm", "4cm", "4cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата", "Название машины", "Сотрудник ", "Комплектация" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var car in info.ReportEquipmentsEmployees)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "", car.BrandCar, "", "" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
/*foreach (var employee in car.Employees)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { employee.EmployeeFIO.ToString(), "", "", employee.Specialization },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
}*/
/*foreach (var guidance in car.Equipments)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { guidance.DateCreateEquipment.ToString(), "", guidance.EquipmentName, "" },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
}*/
}
SavePdf(info);
}
protected abstract void CreatePdf(PdfInfo info);
protected abstract void CreateParagraph(PdfParagraph paragraph);
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateRow(PdfRowParameters rowParameters);
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left,
Right
}
}

View File

@ -0,0 +1,20 @@
using CarCenterContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportEquipmentsEmployeesViewModel> ReportEquipmentsEmployees { get; set; } = new();
/*public List<ReportVisitsDrugsViewModel> ReportVisitsDrugs { get; set; } = new();*/// возможно надо убрать
}
}

View File

@ -0,0 +1,16 @@
using CarCenterBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterBusinessLogic.OfficePackage.HelperModels
{
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using CarCenterBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterBusinessLogic.OfficePackage.HelperModels
{
public class PdfRowParameters
{
public List<string> Texts { get; set; } = new();
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,107 @@
using CarCenterBusinessLogic.OfficePackage.HelperEnums;
using CarCenterBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using MigraDoc.DocumentObjectModel.Tables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarCenterBusinessLogic.BusinessLogics;
namespace CarCenterBusinessLogic.OfficePackage.Implements
{
public class SaveToPdfAdministrator : AbstractSaveToPdfAdministrator
{
private Document? _document;
private Section? _section;
private Table? _table;
private static ParagraphAlignment
GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment =
GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment =
GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -14,6 +14,7 @@ namespace CarCenterContracts.BindingModels
public double EquipmentPrice { get; set; }
public int AdministratorId { get; set; }
public int? PreSaleWorkId { get; set; }
public DateTime DateCreateEquipment { get; set; }
public Dictionary<int, ICarModel> EquipmentCars { get; set; } = new();
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterContracts.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; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterContracts.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;
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterContracts.BindingModels
{
public class ReportEquipmentsEmployeesBindingModel
{
public string FileName { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public int? AdministratorId { get; set; }
public string? Email { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterContracts.BindingModels
{
public class ReportPreSaleWorkCarBindingModel
{
public string FileName { get; set; } = string.Empty;
public List<int> Cars { get; set; } = new();
}
}

View File

@ -0,0 +1,20 @@
using CarCenterContracts.BindingModels;
using CarCenterContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterContracts.BusinessLogicsContracts
{
public interface IReportLogicAdministrator
{
List<ReportEquipmentsEmployeesViewModel> GetEquipmentsEmployees(ReportEquipmentsEmployeesBindingModel model);
/*List<ReportPurchaseMedicationViewModel> GetPurchaseMedications(ReportPurchaseMedicationBindingModel model);*/
/*void SavePurchasesToWordFile(ReportPurchaseMedicationBindingModel model);
void SavePurchasesToExcelFile(ReportPurchaseMedicationBindingModel model);*/
void SaveCarsToPdfFile(ReportEquipmentsEmployeesBindingModel model);
}
}

View File

@ -12,5 +12,8 @@ namespace CarCenterContracts.SearchModels
public string? EquipmentName { get; set; }
public int? AdministratorId { get; set; }
public int? PreSaleWorkId { get; set; }
public DateTime? DateCreateEquipment { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterContracts.SearchModels
{
public class ReportEquipmentsEmployeesSearchModel
{
public List<int>? carsIds { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}

View File

@ -22,5 +22,7 @@ namespace CarCenterContracts.StoragesContracts
CarViewModel? Update(CarBindingModel model);
CarViewModel? Delete(CarBindingModel model);
/*List<ReportPurchaseMedicationViewModel> GetReportMedicationPurchasesList(ListPurchasesSearchModel model);*/
List<ReportEquipmentsEmployeesViewModel> GetReportEquipmentsEmployees(ReportEquipmentsEmployeesSearchModel model);
}
}

View File

@ -18,6 +18,9 @@ namespace CarCenterContracts.ViewModels
[DisplayName("Цена комплектации")]
public double EquipmentPrice { get; set; }
[DisplayName("Дата создания")]
public DateTime DateCreateEquipment { get; set; }
public int AdministratorId { get; set; }
public int? PreSaleWorkId { get; set; }
public Dictionary<int, ICarModel> EquipmentCars { get; set; } = new();

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarCenterContracts.ViewModels
{
public class ReportEquipmentsEmployeesViewModel
{
public string BrandCar { get; set; } = string.Empty;
public List<EmployeeViewModel> Employees { get; set; }
/*public List<EquipmentViewModel> Equipments { get; set; }*/
public List<InspectionViewModel> Inspections { get; set; }
}
}

View File

@ -130,5 +130,31 @@ namespace CarCenterDataBaseImplement.Implements
return null;
}
public List<ReportEquipmentsEmployeesViewModel> GetReportEquipmentsEmployees(ReportEquipmentsEmployeesSearchModel model)
{
using var context = new CarCenterDataBase();
var per = context.Cars
.Select(car => new ReportEquipmentsEmployeesViewModel()
{
BrandCar = car.BrandCar,
/* Inspections = context.Inspections
.Where(equipment => equipment.InspectionDate <= model.DateTo &&
equipment.InspectionDate >= model.DateFrom && equipment.Cars.Any(m => m.CarId == car.Id))
.Select(equipment => equipment.GetViewModel)
.ToList(),*/
/* Employees = context.Inspections
.Include(service => service.Employee)
.Where(service => service.Employee != null && service.Cars.Any(m => m.CarId == car.Id))
.Select(service => service.Employee.GetViewModel)
.ToList(),*/
})
.ToList();
/*var allEquipments = context.Equipments
.Select(equipment => equipment.GetViewModel)
.ToList();*/
return per;
}
}
}

View File

@ -57,8 +57,20 @@ namespace CarCenterDataBaseImplement.Implements
}
using var context = new CarCenterDataBase();
if (model.AdministratorId.HasValue)
if (!model.DateFrom.HasValue && !model.DateTo.HasValue && model.DateFrom.HasValue)
{
return context.Equipments
.Include(x => x.Cars)
.ThenInclude(x => x.Car)
.ThenInclude(x => x.InspectionCar)
.ThenInclude(x => x.Inspection)
.Include(x => x.PreSaleWork)
.Include(x => x.Administrator)
.Where(x => x.DateCreateEquipment >= model.DateFrom && x.DateCreateEquipment <= model.DateTo && x.AdministratorId == model.AdministratorId)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.AdministratorId.HasValue)
{
return context.Equipments
.Include(x => x.Cars)
@ -128,10 +140,11 @@ namespace CarCenterDataBaseImplement.Implements
{
return null;
}
elem.UpdateCars(context, model);
context.SaveChanges();
elem.Update(model);
context.SaveChanges();
if (model.EquipmentCars != null)
elem.UpdateCars(context, model);
transaction.Commit();
return elem.GetViewModel;
}

View File

@ -136,11 +136,18 @@ namespace CarCenterDataBaseImplement.Implements
{
return null;
}
elem.Update(model);
/*elem.Update(model);
context.SaveChanges();
if (model.InspectionCars != null)
elem.UpdateCars(context, model);
transaction.Commit();
return elem.GetViewModel;*/
elem.UpdateCars(context, model);
context.SaveChanges();
elem.Update(model);
context.SaveChanges();
transaction.Commit();
return elem.GetViewModel;
}
catch

View File

@ -0,0 +1,564 @@
// <auto-generated />
using System;
using CarCenterDataBaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace CarCenterDataBaseImplement.Migrations
{
[DbContext(typeof(CarCenterDataBase))]
[Migration("20240527195701_addDateEquipment")]
partial class addDateEquipment
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Administrator", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AdministratorEmail")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("AdministratorFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("AdministratorLogin")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("AdministratorNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("AdministratorPassword")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Administrators");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("AdministratorId")
.HasColumnType("int");
b.Property<string>("BrandCar")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Model")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AdministratorId");
b.ToTable("Cars");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("EmployeeFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("ManagerId")
.HasColumnType("int");
b.Property<string>("Specialization")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ManagerId");
b.ToTable("Employees");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.EmployeeSale", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("EmployeeId")
.HasColumnType("int");
b.Property<int>("SaleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.HasIndex("SaleId");
b.ToTable("EmployeeSales");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Equipment", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("AdministratorId")
.HasColumnType("int");
b.Property<DateTime>("DateCreateEquipment")
.HasColumnType("datetime2");
b.Property<string>("EquipmentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("EquipmentPrice")
.HasColumnType("float");
b.Property<int?>("PreSaleWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AdministratorId");
b.HasIndex("PreSaleWorkId");
b.ToTable("Equipments");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.EquipmentCar", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("int");
b.Property<int>("EquipmentId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("EquipmentId");
b.ToTable("EquipmentCars");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Inspection", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("AdministratorId")
.HasColumnType("int");
b.Property<int?>("EmployeeId")
.HasColumnType("int");
b.Property<DateTime?>("InspectionDate")
.HasColumnType("datetime2");
b.Property<string>("InspectionName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AdministratorId");
b.HasIndex("EmployeeId");
b.ToTable("Inspections");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.InspectionCar", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("CarId")
.HasColumnType("int");
b.Property<int>("InspectionId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("InspectionId");
b.ToTable("InspectionCars");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Manager", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManagerEmail")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ManagerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ManagerLogin")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ManagerNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ManagerPassword")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Managers");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.PreSaleWork", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ManagerId")
.HasColumnType("int");
b.Property<double>("PreSaleWorkPrice")
.HasColumnType("float");
b.Property<string>("PreSaleWorkType")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ManagerId");
b.ToTable("PreSaleWorks");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.PreSaleWorkSale", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("PreSaleWorkId")
.HasColumnType("int");
b.Property<int>("SaleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PreSaleWorkId");
b.HasIndex("SaleId");
b.ToTable("PreSaleWorkSales");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Sale", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ManagerId")
.HasColumnType("int");
b.Property<DateTime?>("SaleDate")
.IsRequired()
.HasColumnType("datetime2");
b.Property<string>("SalePrice")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("ManagerId");
b.ToTable("Sales");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Car", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Administrator", "Administrator")
.WithMany("Cars")
.HasForeignKey("AdministratorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Administrator");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Employee", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Manager", "Manager")
.WithMany("Employees")
.HasForeignKey("ManagerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manager");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.EmployeeSale", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Employee", "Employee")
.WithMany("Sales")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarCenterDataBaseImplement.Models.Sale", "Sale")
.WithMany("EmployeeSales")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
b.Navigation("Sale");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Equipment", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Administrator", "Administrator")
.WithMany("Equipments")
.HasForeignKey("AdministratorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarCenterDataBaseImplement.Models.PreSaleWork", "PreSaleWork")
.WithMany("Equipments")
.HasForeignKey("PreSaleWorkId");
b.Navigation("Administrator");
b.Navigation("PreSaleWork");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.EquipmentCar", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Car", "Car")
.WithMany("EquipmentCars")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarCenterDataBaseImplement.Models.Equipment", "Equipment")
.WithMany("Cars")
.HasForeignKey("EquipmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Car");
b.Navigation("Equipment");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Inspection", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Administrator", "Administrator")
.WithMany("Inspections")
.HasForeignKey("AdministratorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarCenterDataBaseImplement.Models.Employee", "Employee")
.WithMany("Inspections")
.HasForeignKey("EmployeeId");
b.Navigation("Administrator");
b.Navigation("Employee");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.InspectionCar", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Car", "Car")
.WithMany("InspectionCar")
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarCenterDataBaseImplement.Models.Inspection", "Inspection")
.WithMany("Cars")
.HasForeignKey("InspectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Car");
b.Navigation("Inspection");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.PreSaleWork", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Manager", "Manager")
.WithMany("PreSaleWorks")
.HasForeignKey("ManagerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manager");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.PreSaleWorkSale", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.PreSaleWork", "PreSaleWork")
.WithMany("Sales")
.HasForeignKey("PreSaleWorkId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarCenterDataBaseImplement.Models.Sale", "Sale")
.WithMany("PreSaleWorkSale")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("PreSaleWork");
b.Navigation("Sale");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Sale", b =>
{
b.HasOne("CarCenterDataBaseImplement.Models.Manager", "Manager")
.WithMany("Sales")
.HasForeignKey("ManagerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manager");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Administrator", b =>
{
b.Navigation("Cars");
b.Navigation("Equipments");
b.Navigation("Inspections");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Car", b =>
{
b.Navigation("EquipmentCars");
b.Navigation("InspectionCar");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Employee", b =>
{
b.Navigation("Inspections");
b.Navigation("Sales");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Equipment", b =>
{
b.Navigation("Cars");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Inspection", b =>
{
b.Navigation("Cars");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Manager", b =>
{
b.Navigation("Employees");
b.Navigation("PreSaleWorks");
b.Navigation("Sales");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.PreSaleWork", b =>
{
b.Navigation("Equipments");
b.Navigation("Sales");
});
modelBuilder.Entity("CarCenterDataBaseImplement.Models.Sale", b =>
{
b.Navigation("EmployeeSales");
b.Navigation("PreSaleWorkSale");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CarCenterDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class addDateEquipment : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DateCreateEquipment",
table: "Equipments",
type: "datetime2",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DateCreateEquipment",
table: "Equipments");
}
}
}

View File

@ -141,6 +141,9 @@ namespace CarCenterDataBaseImplement.Migrations
b.Property<int>("AdministratorId")
.HasColumnType("int");
b.Property<DateTime>("DateCreateEquipment")
.HasColumnType("datetime2");
b.Property<string>("EquipmentName")
.IsRequired()
.HasColumnType("nvarchar(max)");

View File

@ -8,6 +8,7 @@ using System.Threading.Tasks;
using CarCenterDataModels.Models;
using CarCenterContracts.BindingModels;
using CarCenterContracts.ViewModels;
using System.Diagnostics;
namespace CarCenterDataBaseImplement.Models
{
@ -21,14 +22,35 @@ namespace CarCenterDataBaseImplement.Models
public int AdministratorId { get; private set; }
public int? PreSaleWorkId { get; private set; }
public int Id { get; private set; }
public DateTime DateCreateEquipment { get; private set; }
public virtual Administrator Administrator { get; set; }
public virtual PreSaleWork? PreSaleWork { get; set; }
[ForeignKey("EquipmentId")]
public virtual List<EquipmentCar> Cars { get; set; }
private Dictionary<int, ICarModel> _equipmentCars = null;
/*[NotMapped]
public Dictionary<int, ICarModel> EquipmentCars
{
get
{
if (_equipmentCars == null)
{
*//*using var context = new CarCenterDataBase();*//*
_equipmentCars = Cars
*//*.ToDictionary(x => x.CarId, x => (context.Cars
.FirstOrDefault(y => y.Id == x.CarId)! as ICarModel));*//*
.ToDictionary(recPC => recPC.CarId, recPC =>
(recPC.Car as ICarModel));
}
return _equipmentCars;
}
}*/
[NotMapped]
public Dictionary<int, ICarModel> EquipmentCars
{
@ -36,15 +58,47 @@ namespace CarCenterDataBaseImplement.Models
{
if (_equipmentCars == null)
{
using var context = new CarCenterDataBase();
_equipmentCars = Cars
.ToDictionary(x => x.CarId, x => (context.Cars
.FirstOrDefault(y => y.Id == x.CarId)! as ICarModel));
.ToDictionary(x => x.CarId, x => (x.Car as ICarModel));
}
return _equipmentCars;
}
}
/*public Dictionary<int, ICarModel> EquipmentCars
{
get
{
if (_equipmentCars == null)
{
if (Cars == null)
{
throw new InvalidOperationException("Cars collection is null.");
}
foreach (var car in Cars)
{
if (car == null)
{
throw new InvalidOperationException("One of the items in Cars collection is null.");
}
if (car.CarId == null)
{
throw new InvalidOperationException("One of the cars has a null CarId.");
}
if (car.Car == null)
{
throw new InvalidOperationException("One of the cars has a null Car property.");
}
}
_equipmentCars = Cars.ToDictionary(x => x.CarId, x => (x.Car as ICarModel));
}
return _equipmentCars;
}
}*/
public static Equipment Create(CarCenterDataBase context, EquipmentBindingModel model)
{
return new Equipment()
@ -54,6 +108,8 @@ namespace CarCenterDataBaseImplement.Models
EquipmentPrice = model.EquipmentPrice,
AdministratorId = model.AdministratorId,
PreSaleWorkId = model.PreSaleWorkId,
DateCreateEquipment = model.DateCreateEquipment,
Cars = model.EquipmentCars.Select(x => new EquipmentCar
{
Car = context.Cars.First(y => y.Id == x.Key),
@ -83,6 +139,12 @@ namespace CarCenterDataBaseImplement.Models
{
var equipmentCars = context.EquipmentCars.Where(rec => rec.EquipmentId == model.Id).ToList();
var list = new List<int>();
foreach (var rec in model.EquipmentCars)
{
list.Add(rec.Key);
}
if (equipmentCars != null && equipmentCars.Count > 0)
{
context.EquipmentCars.RemoveRange(equipmentCars.Where(rec => !model.EquipmentCars.ContainsKey(rec.CarId)));
@ -108,5 +170,35 @@ namespace CarCenterDataBaseImplement.Models
}
_equipmentCars = null;
}
/*public void UpdateCars(CarCenterDataBase context, EquipmentBindingModel model)
{
var equipmentCars = context.EquipmentCars.Where(rec => rec.EquipmentId == model.Id).ToList();
if (equipmentCars != null && equipmentCars.Count > 0)
{
context.EquipmentCars.RemoveRange(equipmentCars.Where(rec => !model.EquipmentCars.ContainsKey(rec.CarId)));
context.SaveChanges();
foreach (var updateCar in equipmentCars)
{
model.EquipmentCars.Remove(updateCar.CarId);
}
context.SaveChanges();
}
var equipment = context.Equipments.First(x => x.Id == Id);
foreach (var ec in model.EquipmentCars)
{
context.EquipmentCars.Add(new EquipmentCar
{
Equipment = equipment,
Car = context.Cars.First(x => x.Id == ec.Key),
});
context.SaveChanges();
}
_equipmentCars = null;
}*/
}
}

View File

@ -78,6 +78,12 @@ namespace CarCenterDataBaseImplement.Models
{
var inspectionCars = context.InspectionCars.Where(rec => rec.InspectionId == model.Id).ToList();
var list = new List<int>();
foreach (var rec in model.InspectionCars)
{
list.Add(rec.Key);
}
if (inspectionCars != null && inspectionCars.Count > 0)
{
context.InspectionCars.RemoveRange(inspectionCars.Where(rec => !model.InspectionCars.ContainsKey(rec.CarId)));

View File

@ -10,6 +10,7 @@ namespace CarCenterDataModels.Models
{
string EquipmentName { get; }
double EquipmentPrice { get; }
DateTime DateCreateEquipment { get; }
int AdministratorId { get; }
int? PreSaleWorkId { get; }
public Dictionary<int, ICarModel> EquipmentCars { get; }

View File

@ -6,6 +6,9 @@ using Microsoft.AspNetCore.Mvc;
using CarCenterContracts.ViewModels;
using CarCenterContracts.BindingModels;
using CarCenterDataBaseImplement;
using CarCenterBusinessLogic.MailWorker;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CarCenterRestApi.Controllers
{
@ -21,7 +24,12 @@ namespace CarCenterRestApi.Controllers
private readonly IInspectionLogic _inspection;
private readonly IEquipmentLogic _equipment;
public MainController(ILogger<MainController> logger, IEmployeeLogic employee, ISaleLogic sale, IPreSaleWorkLogic preSaleWork, ICarLogic car, IInspectionLogic inspection, IEquipmentLogic equipment)
private readonly AbstractMailWorker _mailWorker;
private readonly IReportLogicAdministrator _reportAdministrator;
public MainController(ILogger<MainController> logger, IEmployeeLogic employee, ISaleLogic sale, IPreSaleWorkLogic preSaleWork, ICarLogic car,
IInspectionLogic inspection, IEquipmentLogic equipment, IReportLogicAdministrator reportAdministrator, AbstractMailWorker mailWorker)
{
_logger = logger;
_employee = employee;
@ -30,6 +38,8 @@ namespace CarCenterRestApi.Controllers
_car = car;
_inspection = inspection;
_equipment = equipment;
_reportAdministrator = reportAdministrator;
_mailWorker = mailWorker;
}
[HttpGet]
@ -303,7 +313,7 @@ namespace CarCenterRestApi.Controllers
var elem = _employee.ReadElement(new EmployeeSearchModel { Id = employeeId });
if (elem == null)
return null;
return Tuple.Create(elem, elem.EmployeeSales.Select(x => Tuple.Create(x.Value.SaleDate, x.Value.SalePrice)).ToList());
return System.Tuple.Create(elem, elem.EmployeeSales.Select(x => System.Tuple.Create(x.Value.SaleDate, x.Value.SalePrice)).ToList());
}
catch (Exception ex)
{
@ -378,7 +388,7 @@ namespace CarCenterRestApi.Controllers
var elem = _preSaleWork.ReadElement(new PreSaleWorkSearchModel { Id = preSaleWorkId });
if (elem == null)
return null;
return Tuple.Create(elem, elem.PreSaleWorkSales.Select(x => Tuple.Create(x.Value.SaleDate, x.Value.SalePrice)).ToList(), context.Equipments.Where(x => x.PreSaleWorkId == elem.Id).Select(x => Tuple.Create(x.EquipmentName, x.EquipmentPrice)).ToList());
return System.Tuple.Create(elem, elem.PreSaleWorkSales.Select(x => System.Tuple.Create(x.Value.SaleDate, x.Value.SalePrice)).ToList(), context.Equipments.Where(x => x.PreSaleWorkId == elem.Id).Select(x => System.Tuple.Create(x.EquipmentName, x.EquipmentPrice)).ToList());
}
catch (Exception ex)
{
@ -448,7 +458,7 @@ namespace CarCenterRestApi.Controllers
{
try
{
model.EquipmentCars = null!;
/*model.EquipmentCars = null!;*/
_equipment.Update(model);
}
catch (Exception ex)
@ -483,7 +493,7 @@ namespace CarCenterRestApi.Controllers
var elem = _equipment.ReadElement(new EquipmentSearchModel { Id = equipmentId });
if (elem == null)
return null;
return Tuple.Create(elem, elem.EquipmentCars.Select(x => Tuple.Create(x.Value.BrandCar, x.Value.Model)).ToList());
return System.Tuple.Create(elem, elem.EquipmentCars.Select(x => System.Tuple.Create(x.Value.BrandCar, x.Value.Model)).ToList());
}
catch (Exception ex)
{
@ -525,7 +535,7 @@ namespace CarCenterRestApi.Controllers
try
{
model.InspectionCars = null!;
/*model.InspectionCars = null!;*/
_inspection.Update(model);
}
catch (Exception ex)
@ -543,7 +553,7 @@ namespace CarCenterRestApi.Controllers
var elem = _inspection.ReadElement(new InspectionSearchModel { Id = inspectionId });
if (elem == null)
return null;
return Tuple.Create(elem, elem.InspectionCars.Select(x => Tuple.Create(x.Value.BrandCar, x.Value.Model)).ToList());
return System.Tuple.Create(elem, elem.InspectionCars.Select(x => System.Tuple.Create(x.Value.BrandCar, x.Value.Model)).ToList());
}
catch (Exception ex)
{
@ -611,11 +621,6 @@ namespace CarCenterRestApi.Controllers
}
}
[HttpGet]
public List<PreSaleWorkViewModel>? GetPreSaleWorks()
{
@ -629,5 +634,46 @@ namespace CarCenterRestApi.Controllers
throw;
}
}
[HttpGet]
public List<ReportEquipmentsEmployeesViewModel> GetEquipmentsEmployeesReport(string dateFrom, string dateTo, int administratorId)
{
try
{
DateTime DateFrom = DateTime.Parse(dateFrom);
DateTime DateTo = DateTime.Parse(dateTo);
ReportEquipmentsEmployeesBindingModel model = new();
model.DateFrom = DateFrom;
model.DateTo = DateTo;
model.AdministratorId = administratorId;
return _reportAdministrator.GetEquipmentsEmployees(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void SendEquipmentsEmployeesReportToEmail(ReportEquipmentsEmployeesBindingModel model)
{
try
{
_reportAdministrator.SaveCarsToPdfFile(model);
_mailWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = model.Email!,
Subject = "Отчет по машинам",
Text = "отчет"
});
}
catch (Exception ex)
{
throw;
}
}
}
}

View File

@ -0,0 +1,87 @@
using CarCenterBusinessLogic.BusinessLogics;
using CarCenterBusinessLogic.MailWorker;
using CarCenterContracts.BindingModels;
using CarCenterContracts.BusinessLogicsContracts;
using CarCenterContracts.ViewModels;
using CarCenterDataBaseImplement.Models;
using Microsoft.AspNetCore.Mvc;
namespace CarCenterRestApi.Controllers
{
public class ReportController : Controller
{
private readonly IReportLogicAdministrator _reportAdministrator;
private readonly AbstractMailWorker _mailWorker;
public ReportController(ILogger<ReportController> logger, IReportLogicAdministrator reportAdministrator, AbstractMailWorker mailWorker)
{
_reportAdministrator = reportAdministrator;
_mailWorker = mailWorker;
}
[Microsoft.AspNetCore.Mvc.HttpGet]
public IActionResult Index(ReportLogicAdministrator reportAdministrator)
{
return View();
}
/*[HttpPost]
public void CreatePurchaseListWordFile(ReportPurchaseMedicationBindingModel model)
{
try
{
_reportDoctor.SavePurchasesToWordFile(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void CreatePurchaseListExcelFile(ReportPurchaseMedicationBindingModel model)
{
try
{
_reportDoctor.SavePurchasesToExcelFile(model);
}
catch (Exception ex)
{
throw;
}
}*/
/*[HttpGet]
public List<ReportEquipmentsEmployeesViewModel> GetEquipmentsEmployeesReport(string dateFrom, string dateTo, int administratorId)
{
try
{
DateTime DateFrom = DateTime.Parse(dateFrom);
DateTime DateTo = DateTime.Parse(dateTo);
ReportEquipmentsEmployeesBindingModel model = new();
model.DateFrom = DateFrom;
model.DateTo = DateTo;
model.AdministratorId = administratorId;
return _reportAdministrator.GetEquipmentsEmployees(model);
}
catch (Exception ex)
{
throw;
}
}*/
/*[HttpPost]
public void SendEquipmentsEmployeesReportToEmail(ReportEquipmentsEmployeesBindingModel model)
{
try
{
_reportAdministrator.SaveCarsToPdfFile(model);
_mailWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = model.Email!,
Subject = "Отчет по машинам",
Text = "отчет"
});
}
catch (Exception ex)
{
throw;
}
}*/
}
}

View File

@ -1,4 +1,8 @@
using CarCenterBusinessLogic.BusinessLogics;
using CarCenterBusinessLogic.MailWorker;
using CarCenterBusinessLogic.OfficePackage;
using CarCenterBusinessLogic.OfficePackage.Implements;
using CarCenterContracts.BindingModels;
using CarCenterContracts.BusinessLogicsContracts;
using CarCenterContracts.StoragesContracts;
using CarCenterDataBaseImplement.Implements;
@ -32,6 +36,10 @@ builder.Services.AddTransient<ICarLogic, CarLogic>();
builder.Services.AddTransient<IEquipmentLogic, EquipmentLogic>();
builder.Services.AddTransient<IInspectionLogic, InspectionLogic>();
builder.Services.AddTransient<IReportLogicAdministrator, ReportLogicAdministrator>();
builder.Services.AddTransient<AbstractSaveToPdfAdministrator, SaveToPdfAdministrator>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -47,6 +55,27 @@ builder.Services.AddSwaggerGen(c =>
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())
{

View File

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "rpp777rpp777@gmail.com",
"MailPassword": "uxag bpdb wfqg thvb"
}