This commit is contained in:
Николай 2023-05-18 17:21:54 +04:00
parent 5333817ea8
commit f6657eaa0d
16 changed files with 581 additions and 74 deletions

View File

@ -6,25 +6,33 @@ using HardwareShopContracts.BindingModels;
using HardwareShopContracts.SearchModels; using HardwareShopContracts.SearchModels;
using HardwareShopContracts.StoragesContracts; using HardwareShopContracts.StoragesContracts;
using HardwareShopContracts.ViewModels; using HardwareShopContracts.ViewModels;
using HardwareShopDatabaseImplement.Implements.Worker;
using HardwareShopDatabaseImplement.Models.Worker; using HardwareShopDatabaseImplement.Models.Worker;
using System.Reflection.PortableExecutable;
namespace HardwareShopContracts.BusinessLogicsContracts namespace HardwareShopContracts.BusinessLogicsContracts
{ {
public class WorkerReportLogic : IWorkerReportLogic public class WorkerReportLogic : IWorkerReportLogic
{ {
private readonly IPurchaseStorage _purchaseStorage; private readonly IPurchaseStorage _purchaseStorage;
private readonly AbstractSaveToExcel _saveToExcel; private readonly IBuildStorage _buildStorage;
private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToExcel _saveToExcel;
public WorkerReportLogic(IPurchaseStorage purchaseStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord) private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToWord _saveToPdf;
public WorkerReportLogic(IPurchaseStorage purchaseStorage, IBuildStorage buildStorage, AbstractSaveToWord saveToPdf, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord)
{ {
_purchaseStorage = purchaseStorage; _purchaseStorage = purchaseStorage;
_saveToExcel = saveToExcel; _buildStorage = buildStorage;
_saveToWord = saveToWord; _saveToExcel = saveToExcel;
} _saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
/// <summary> /// <summary>
/// Получение списка компонент с указанием, в каких покупках используются /// Получение списка компонент с указанием, в каких покупках используются
@ -38,7 +46,7 @@ namespace HardwareShopContracts.BusinessLogicsContracts
{ {
var purchase = _purchaseStorage.GetElement(new() { Id = p.Id })!; var purchase = _purchaseStorage.GetElement(new() { Id = p.Id })!;
var record = new ReportPurchaseComponentViewModel var record = new ReportPurchaseComponentViewModel
{ {
Id = purchase.Id, Id = purchase.Id,
Builds = new List<(string Build, int count, List<(string Component, int count)>)>(), Builds = new List<(string Build, int count, List<(string Component, int count)>)>(),
@ -68,43 +76,44 @@ namespace HardwareShopContracts.BusinessLogicsContracts
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public List<ReportPurchaseViewModel> GetPurchase(ReportBindingModel model, UserBindingModel userModel) public List<ReportPurchaseViewModel> GetPurchase(ReportBindingModel model)
{ {
var list = new List<ReportPurchaseViewModel>(); var list = new List<ReportPurchaseViewModel>();
var purchases = _purchaseStorage.GetFilteredList(new PurchaseSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo, UserId = userModel.Id }); var purchases = _purchaseStorage.GetFilteredList(new PurchaseSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo, UserId = model.UserId });
foreach (var p in purchases) foreach (var p in purchases)
{ {
var purchase = _purchaseStorage.GetElement(new() { Id = p.Id })!; var purchase = _purchaseStorage.GetElement(new() { Id = p.Id })!;
var record = new ReportPurchaseViewModel List<string> commentList = new List<string>();
{ List<string> componentList = new List<string>();
Id = purchase.Id,
Builds = new List<(string Build, int count, List<string>, List<(string Component, int count)>)>(),
};
foreach (var build in purchase.PurchaseBuilds) foreach (var build in purchase.PurchaseBuilds)
{ {
List<string> commentList = new List<string>();
foreach (var comment in build.Value.Item1.BuildComments) foreach (var comment in build.Value.Item1.BuildComments)
{ {
commentList.Add(new(comment.Value.Text)); commentList.Add(new(comment.Value.Text));
} }
List<(string Component, int count)> componentList = new List<(string Component, int count)>();
foreach (var component in build.Value.Item1.BuildComponents) foreach (var component in build.Value.Item1.BuildComponents)
{ {
componentList.Add(new(component.Value.Item1.ComponentName, component.Value.Item2)); componentList.Add(component.Value.Item1.ComponentName);
} }
record.Builds.Add(new(build.Value.Item1.BuildName, build.Value.Item2, commentList, componentList));
} }
var record = new ReportPurchaseViewModel
{
Id = purchase.Id,
PurchaseDate = (DateTime)p.DatePurchase,
PurchaseSum = p.Sum,
Comments = commentList,
Components = componentList.Distinct().ToList()
};
list.Add(record); list.Add(record);
} }
return list; return list;
} }
/// <summary> /// <summary>
/// Сохранение компонент с указаеним покупок в файл-Word /// Сохранение компонент с указаеним покупок в файл-Word
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
public byte[] SavePurchasesToWordFile(ReportBindingModel model, List<PurchaseViewModel> purchases) public byte[] SavePurchasesToWordFile(ReportBindingModel model, List<PurchaseViewModel> purchases)
{ {
_saveToWord.CreateBuildPurchaseReport(new WordInfo _saveToWord.CreateBuildPurchaseReport(new WordInfo
@ -114,35 +123,35 @@ namespace HardwareShopContracts.BusinessLogicsContracts
PurchaseComponent = GetPurchaseComponent(purchases) PurchaseComponent = GetPurchaseComponent(purchases)
}); });
byte[] file = File.ReadAllBytes(model.FileName); byte[] file = File.ReadAllBytes(model.FileName);
File.Delete(model.FileName); File.Delete(model.FileName);
return file; return file;
} }
/// <summary> /// <summary>
/// Сохранение компонент с указаеним покупок в файл-Excel /// Сохранение компонент с указаеним покупок в файл-Excel
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
public byte[] SavePurchasesToExcelFile(ReportBindingModel model, List<PurchaseViewModel> purchases) public byte[] SavePurchasesToExcelFile(ReportBindingModel model, List<PurchaseViewModel> purchases)
{ {
_saveToExcel.CreatePurchaseComponentReport(new ExcelInfo _saveToExcel.CreatePurchaseComponentReport(new ExcelInfo
{ {
FileName = model.FileName, FileName = model.FileName,
Title = "Список Компонентов", Title = "Список Компонентов",
PurchaseComponent = GetPurchaseComponent(purchases) PurchaseComponent = GetPurchaseComponent(purchases)
}); });
byte[] file = File.ReadAllBytes(model.FileName); byte[] file = File.ReadAllBytes(model.FileName);
File.Delete(model.FileName); File.Delete(model.FileName);
return file; return file;
} }
/// <summary> /// <summary>
/// Сохранение отчёта по покупкам в файл-Pdf /// Сохранение отчёта по покупкам в файл-Pdf
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
public void SaveOrdersToPdfFile(ReportBindingModel model) public byte[] SendByMailPurchaseReport(ReportBindingModel model)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
} }

View File

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

View File

@ -0,0 +1,96 @@
using HardwareShopBusinessLogic.OfficePackage.HelperEnums;
using HardwareShopBusinessLogic.OfficePackage.HelperModels;
namespace HardwareShopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
//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> { "2cm", "3cm", "6cm", "3cm", "3cm" });
// CreateRow(new PdfRowParameters
// {
// Texts = new List<string> { "Номер", "Дата заказа", "Блюдо", "Сумма", "Статус" },
// Style = "NormalTitle",
// ParagraphAlignment = PdfParagraphAlignmentType.Center
// });
// foreach (var order in info.Orders)
// {
// CreateRow(new PdfRowParameters
// {
// Texts = new List<string> { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.DishName, order.Sum.ToString(), order.OrderStatus },
// Style = "Normal",
// ParagraphAlignment = PdfParagraphAlignmentType.Left
// });
// }
// CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Rigth });
// SavePdf(info);
//}
//public void CreateOrdersGroupedByDateDoc(PdfInfo info)
//{
// CreatePdf(info);
// CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
// CreateTable(new List<string> { "3cm", "3cm", "3cm" });
// CreateRow(new PdfRowParameters
// {
// Texts = new List<string> { "Дата заказов", "Количество заказов", "Сумма" },
// Style = "NormalTitle",
// ParagraphAlignment = PdfParagraphAlignmentType.Center
// });
// foreach (var order in info.OrdersGroupedByDate)
// {
// CreateRow(new PdfRowParameters
// {
// Texts = new List<string> { order.DateCreate.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() },
// Style = "Normal",
// ParagraphAlignment = PdfParagraphAlignmentType.Left
// });
// }
// SavePdf(info);
//}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfo info);
/// <summary>
/// Создание параграфа с текстом
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// <summary>
/// Создание таблицы
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateTable(List<string> columns);
/// <summary>
/// Создание и заполнение строки
/// </summary>
/// <param name="rowParameters"></param>
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,11 @@
namespace HardwareShopBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left,
Rigth
}
}

View File

@ -0,0 +1,20 @@

using HardwareShopContracts.ViewModels;
namespace HardwareShopBusinessLogic.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<ReportComponentsViewModel> ReportComponents { get; set; } = new();
public List<ReportPurchaseViewModel> ReportPurchases { get; set; } = new();
}
}

View File

@ -0,0 +1,13 @@
using HardwareShopBusinessLogic.OfficePackage.HelperEnums;
namespace HardwareShopBusinessLogic.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,13 @@
using HardwareShopBusinessLogic.OfficePackage.HelperEnums;
namespace HardwareShopBusinessLogic.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,114 @@
using HardwareShopBusinessLogic.OfficePackage.HelperEnums;
using HardwareShopBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
namespace HardwareShopBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
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.Rigth => 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

@ -7,5 +7,7 @@
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
public int UserId { get; set; }
} }
} }

View File

@ -17,7 +17,7 @@ namespace HardwareShopContracts.BusinessLogicsContracts
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
List<ReportPurchaseViewModel> GetPurchase(ReportBindingModel model, UserBindingModel userModel); List<ReportPurchaseViewModel> GetPurchase(ReportBindingModel model);
/// <summary> /// <summary>
/// Сохранение компонент с указаеним покупок в файл-Word /// Сохранение компонент с указаеним покупок в файл-Word
@ -31,10 +31,10 @@ namespace HardwareShopContracts.BusinessLogicsContracts
/// <param name="model"></param> /// <param name="model"></param>
byte[] SavePurchasesToExcelFile(ReportBindingModel model, List<PurchaseViewModel> purchases); byte[] SavePurchasesToExcelFile(ReportBindingModel model, List<PurchaseViewModel> purchases);
/// <summary> /// <summary>
/// Сохранение отчёта по покупкам в файл-Pdf /// Сохранение отчёта по покупкам в файл-Pdf
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
void SaveOrdersToPdfFile(ReportBindingModel model); byte[] SendByMailPurchaseReport(ReportBindingModel model);
} }
} }

View File

@ -4,6 +4,8 @@
{ {
public int? Id { get; set; } public int? Id { get; set; }
public int? PurchaseId { get; set; }
public string? BuildName { get; set; } = string.Empty; public string? BuildName { get; set; } = string.Empty;
public int? UserId { get; set; } public int? UserId { get; set; }

View File

@ -4,6 +4,12 @@
{ {
public int Id { get; set; } public int Id { get; set; }
public List<(string Build, int count, List<string>, List<(string Component, int count)>)> Builds { get; set; } = new(); public DateTime PurchaseDate { get; set; }
public double PurchaseSum { get; set; }
public List<string> Comments { get; set; } = new();
public List<string> Components { get; set; } = new();
} }
} }

View File

@ -84,7 +84,10 @@ namespace HardwareShopDatabaseImplement.Implements.Worker
.ThenInclude(x => x.Build) .ThenInclude(x => x.Build)
.ThenInclude(x => x.Components) .ThenInclude(x => x.Components)
.ThenInclude(x => x.Component) .ThenInclude(x => x.Component)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) .Include(x => x.Builds)
.ThenInclude(x => x.Build)
.ThenInclude(x => x.Comments)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel; ?.GetViewModel;
} }

View File

@ -1,5 +1,7 @@
using HardwareShopContracts.BindingModels; using DocumentFormat.OpenXml.Drawing;
using HardwareShopContracts.BindingModels;
using HardwareShopContracts.BusinessLogicsContracts; using HardwareShopContracts.BusinessLogicsContracts;
using HardwareShopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace HardwareShopRestApi.Controllers namespace HardwareShopRestApi.Controllers
@ -71,6 +73,22 @@ namespace HardwareShopRestApi.Controllers
throw; throw;
} }
} }
[HttpPost]
public List<ReportPurchaseViewModel>? GetPurchaseReportData(ReportBindingModel model)
{
try
{
var report = _reportWorkerLogic.GetPurchase(model);
return report;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения данных для отчёта");
throw;
}
}
} }
} }

View File

@ -345,10 +345,9 @@ namespace HardwareShopWorkerApp.Controllers
byte[]? file = APIClient.PostRequestWithResult<PurchaseBindingModel, byte[]>($"api/report/buildpurchasereport?format={format}", purchaseModel); byte[]? file = APIClient.PostRequestWithResult<PurchaseBindingModel, byte[]>($"api/report/buildpurchasereport?format={format}", purchaseModel);
var array = file!.Select(b => (int)b).ToArray(); var array = file!.Select(b => (int)b).ToArray();
return array; return array;
} }
[HttpGet] [HttpGet]
public GoodViewModel? GetPurchase(int Id) public GoodViewModel? GetPurchase(int Id)
{ {
@ -464,12 +463,6 @@ namespace HardwareShopWorkerApp.Controllers
return result; return result;
} }
[HttpGet]
public IActionResult WorkerReport()
{
return View();
}
[HttpGet] [HttpGet]
public IActionResult Builds() public IActionResult Builds()
{ {
@ -539,5 +532,26 @@ namespace HardwareShopWorkerApp.Controllers
APIClient.GetRequest<bool>($"api/build/UpdateLinkPurchase?updateBuildId={updateBuildId}&updatePurchaseId={updatePurchaseId}&count={count}"); APIClient.GetRequest<bool>($"api/build/UpdateLinkPurchase?updateBuildId={updateBuildId}&updatePurchaseId={updatePurchaseId}&count={count}");
Response.Redirect($"LinkPurchase?buildId={updateBuildId}"); Response.Redirect($"LinkPurchase?buildId={updateBuildId}");
} }
}
public IActionResult WorkerReport()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public List<ReportPurchaseViewModel>? WorkerReport([FromBody] ReportBindingModel reportModel)
{
if (APIClient.User == null)
{
return new();
}
reportModel.UserId = APIClient.User.Id;
List<ReportPurchaseViewModel>? list = APIClient.PostRequestWithResult<ReportBindingModel, List<ReportPurchaseViewModel>>("api/report/getpurchasereportdata", reportModel);
return list;
}
}
} }

View File

@ -3,13 +3,198 @@
Layout = "~/Views/Shared/_LayoutWorker.cshtml"; Layout = "~/Views/Shared/_LayoutWorker.cshtml";
} }
<form method="post" class="d-flex flex-column align-items-center"> <h4 class="fw-bold">Отчет по покупкам</h4>
<div class="col-sm-3">
<label class="form-label">С</label> <div id="error-div-shell" class="error-div-shell">
<input type="date" class="form-control" name="dateFrom"> <div>
<label class="form-label">По</label> <p id="error-p" class="error-p mb-2"></p>
<input type="date" class="form-control" name="dateTo">
</div> </div>
<button type="submit" class="btn btn-primary mt-3 px-4">Вывод на страницу</button> </div>
<button type="submit" class="btn btn-primary mt-3 px-4">Отправить на почту</button>
</form> <div class="d-flex flex-wrap gap-1 align-items-end mb-2">
<div class="mb-2">
<p class="mb-0">Дата начала:</p>
<input id="date-from-input" class="form-control" type="date" />
</div>
<div class="mb-2">
<p class="mb-0">Дата конца:</p>
<input id="date-to-input" class="form-control" type="date" />
</div>
<button id="generate-button" class="button-primary text-button mb-2">
Показать
</button>
<button id="send-by-mail-button" class="button-primary text-button mb-2">
На почту
</button>
</div>
<p class="mb-0">
<span>За период с&nbsp;</span>
<span id="date-from-span" class="fw-bold">...</span>
<span>&nbsp;по&nbsp;</span>
<span id="date-to-span" class="fw-bold">...</span>
</p>
<div class="table-shell mb-2 border">
<table class="table mb-0">
<thead class="table-head">
<tr>
<th>Номер покупки</th>
<th>Дата покупки</th>
<th>Сумма покупки</th>
<th>Комментарии</th>
<th>Комплектующие</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
@section Scripts
{
<script>
const generateButton = document.getElementById("generate-button");
const sendByMailButton = document.getElementById("send-by-mail-button");
const dateFromInput = document.getElementById("date-from-input");
const dateToInput = document.getElementById("date-to-input");
const dateFromSpan = document.getElementById("date-from-span");
const dateToSpan = document.getElementById("date-to-span");
const tbody = document.getElementById("tbody");
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");
// [Event listeners]
generateButton.addEventListener("click", () => {
const dateFrom = new Date(dateFromInput.value);
const dateTo = new Date(dateToInput.value);
const reportModel = {
"DateFrom": dateFrom,
"DateTo": dateTo
};
if (!validate(reportModel)) {
return;
}
$.ajax({
url: "/home/WorkerReport",
type: "POST",
contentType: "application/json",
data: JSON.stringify(reportModel)
}).done((reportData) => {
dateFromSpan.innerHTML = reportModel["DateFrom"].toLocaleDateString();
dateToSpan.innerHTML = reportModel["DateTo"].toLocaleDateString();
renderTable(reportData);
});
});
//sendByMailButton.addEventListener("click", () => {
// const dateFrom = new Date(dateFromInput.value);
// const dateTo = new Date(dateToInput.value);
// const reportModel = {
// "DateFrom": dateFrom,
// "DateTo": dateTo
// };
// if (!validate(reportModel)) {
// return;
// }
// $.ajax({
// url: "/home/sendbymailepurchasereport",
// type: "POST",
// contentType: "application/json",
// data: JSON.stringify(reportModel)
// }).done(() => {
// });
//});
dateFromInput.addEventListener("input", () => {
errorDivShell.style.gridTemplateRows = "0fr";
});
dateToInput.addEventListener("input", () => {
errorDivShell.style.gridTemplateRows = "0fr";
});
// ![Event listeners]
// [HTML gen]
const renderTable = function (reportData) {
tbody.innerHTML = "";
reportData.forEach((record) => {
console.log(record);
const comments = record.comments;
const components = record.components;
const recordHeight = Math.max(comments.length + 1, components.length + 1);
for (let i = 0; i < recordHeight; i++) {
let cellsData = ["", "", "", "", ""];
if (i === 0) {
cellsData[0] = record.id;
cellsData[1] = record.purchaseDate;
cellsData[2] = record.purchaseSum;
createTableRow(cellsData);
continue;
}
let k = i - 1;
if (k < comments.length) {
cellsData[3] = comments[k];
}
if (k < components.length) {
cellsData[4] = components[k];
}
createTableRow(cellsData);
}
});
}
const createTableRow = function (cellsData) {
const tr = document.createElement('tr');
tr.classList.add("table-row");
tr.appendChild(createTableCell(cellsData[0])); // Purchase
tr.appendChild(createTableCell(cellsData[1])); // DatePurchase
tr.appendChild(createTableCell(cellsData[2])); // purchaseSum
tr.appendChild(createTableCell(cellsData[3])); // Comments
tr.appendChild(createTableCell(cellsData[4])); // Copmponent
tbody.appendChild(tr);
}
const createTableCell = function (cellText) {
const td = document.createElement('td');
td.innerHTML = cellText;
return td;
}
// ![HTML gen]
// [Other]
const validate = function (reportModel) {
if (isNaN(reportModel["DateFrom"])) {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Выберите начальную дату";
return false;
}
if (isNaN(reportModel["DateTo"])) {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Выберите конечную дату";
return false;
}
if (reportModel["DateFrom"] >= reportModel["DateTo"]) {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Начальная дата должна быть меньше конечной";
return false;
}
return true;
}
const getDate = function (iso) {
const year = iso.substring(0, 4);
const month = iso.substring(5, 7);
const day = iso.substring(8, 10);
const date = `${day}.${month}.${year}`;
return date;
}
// ![Other]
</script>
}