report complete

This commit is contained in:
Denis 2023-06-22 02:38:03 +04:00
parent 76816dd5d3
commit ac028b54ee
16 changed files with 581 additions and 195 deletions

View File

@ -211,37 +211,41 @@ namespace CanteenBusinessLogic.BusinessLogics
Cooks = GetCooksPCView(model)
});
}
public void saveCooksToExcel(ReportBindingModel model)
public byte[] saveCooksToExcel(ReportBindingModel model)
{
saveToExcel.CreateCooksReport(new ExcelInfo()
byte[] report = saveToExcel.CreateCooksReport(new ExcelInfo()
{
Title = "Список поваров:",
Cooks = GetCooksByLunches(model)
});
return report;
}
public void saveOrdersToExcel(ReportBindingModel model)
public byte[] saveOrdersToExcel(ReportBindingModel model)
{
saveToExcel.CreateOrdersReport(new ExcelInfo()
byte[] report = saveToExcel.CreateOrdersReport(new ExcelInfo()
{
Title = "Список заказов:",
Orders = GetOrdersByProducts(model)
});
return report;
}
public void saveCooksToWord(ReportBindingModel model)
public byte[] saveCooksToWord(ReportBindingModel model)
{
saveToWord.CreateCooksDoc(new WordInfo()
byte[] report = saveToWord.CreateCooksDoc(new WordInfo()
{
Title = "Список поваров",
Cooks = GetCooksByLunches(model)
});
return report;
}
public void saveOrdersToWord(ReportBindingModel model)
public byte[] saveOrdersToWord(ReportBindingModel model)
{
saveToWord.CreateOrdersDoc(new WordInfo()
byte[] report = saveToWord.CreateOrdersDoc(new WordInfo()
{
Title = "Список заказов",
Orders = GetOrdersByProducts(model)
});
return report;
}
}
}

View File

@ -11,7 +11,7 @@ namespace CanteenBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateCooksReport(ExcelInfo info)
public byte[] CreateCooksReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
@ -75,10 +75,10 @@ namespace CanteenBusinessLogic.OfficePackage
rowIndex++;
}
}
SaveExcel(info);
return GetFile();
}
public void CreateOrdersReport(ExcelInfo info)
public byte[] CreateOrdersReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
@ -141,11 +141,12 @@ namespace CanteenBusinessLogic.OfficePackage
rowIndex++;
}
}
SaveExcel(info);
return GetFile();
}
protected abstract void CreateExcel(ExcelInfo info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfo info);
protected abstract void SaveExcel();
protected abstract byte[] GetFile();
}
}

View File

@ -11,7 +11,7 @@ namespace CanteenBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateCooksDoc(WordInfo info)
public byte[] CreateCooksDoc(WordInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
@ -72,9 +72,9 @@ namespace CanteenBusinessLogic.OfficePackage
}
}
SaveWord(info);
return GetFile();
}
public void CreateOrdersDoc(WordInfo info)
public byte[] CreateOrdersDoc(WordInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
@ -136,10 +136,11 @@ namespace CanteenBusinessLogic.OfficePackage
}
}
SaveWord(info);
return GetFile();
}
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info);
protected abstract void SaveWord();
protected abstract byte[] GetFile();
}
}

View File

@ -15,6 +15,7 @@ namespace CanteenBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private readonly string tempFileName = "temp.docx";
private SpreadsheetDocument spreadsheetDocument;
private SharedStringTablePart shareStringPart;
private Worksheet worksheet;
@ -192,7 +193,7 @@ namespace CanteenBusinessLogic.OfficePackage.Implements
}
protected override void CreateExcel(ExcelInfo info)
{
spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
spreadsheetDocument = SpreadsheetDocument.Create(tempFileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
@ -289,10 +290,17 @@ namespace CanteenBusinessLogic.OfficePackage.Implements
};
mergeCells.Append(mergeCell);
}
protected override void SaveExcel(ExcelInfo info)
protected override void SaveExcel()
{
spreadsheetDocument.WorkbookPart.Workbook.Save();
spreadsheetDocument.Close();
}
protected override byte[] GetFile()
{
SaveExcel();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
}
}

View File

@ -13,6 +13,7 @@ namespace CanteenBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private readonly string tempFileName = "temp.docx";
private WordprocessingDocument wordDocument;
private Body docBody;
private static JustificationValues GetJustificationValues(WordJustificationType type)
@ -54,7 +55,7 @@ namespace CanteenBusinessLogic.OfficePackage.Implements
}
protected override void CreateWord(WordInfo info)
{
wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
wordDocument = WordprocessingDocument.Create(tempFileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
docBody = mainPart.Document.AppendChild(new Body());
@ -85,11 +86,18 @@ namespace CanteenBusinessLogic.OfficePackage.Implements
docBody.AppendChild(docParagraph);
}
}
protected override void SaveWord(WordInfo info)
protected override void SaveWord()
{
docBody.AppendChild(CreateSectionProperties());
wordDocument.MainDocumentPart.Document.Save();
wordDocument.Close();
}
protected override byte[] GetFile()
{
SaveWord();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
}
}

View File

@ -10,10 +10,11 @@ namespace CanteenContracts.BindingModels
public class ReportBindingModel
{
public string? FileName { get; set; }
public string? FileType { get; set; }
public DateTime? DateAfter { get; set; }
public DateTime? DateBefore { get; set; }
public int UserId { get; set; }
public List<int>? LunchId { get; set; }
public List<int>? ProductId { get; set; }
public int[]? LunchId { get; set; }
public int[]? ProductId { get; set; }
}
}

View File

@ -12,12 +12,13 @@ namespace CanteenContracts.BusinessLogicsContracts
public interface IReportLogic
{
public List<ReportCookView> GetCooksByLunches(ReportBindingModel model);
List<ReportLunchesPCView> GetLunchesPCView(ReportBindingModel model);
public List<ReportLunchesPCView> GetLunchesPCView(ReportBindingModel model);
public List<ReportCooksPCView> GetCooksPCView(ReportBindingModel model);
void saveLunchesToPdfFile(ReportBindingModel model);
void saveCooksToPdfFile(ReportBindingModel model);
void saveCooksToWord(ReportBindingModel model);
void saveCooksToExcel(ReportBindingModel model);
public void saveOrdersToExcel(ReportBindingModel model);
public void saveOrdersToWord(ReportBindingModel model);
byte[] saveCooksToWord(ReportBindingModel model);
byte[] saveCooksToExcel(ReportBindingModel model);
public byte[] saveOrdersToExcel(ReportBindingModel model);
public byte[] saveOrdersToWord(ReportBindingModel model);
}
}

View File

@ -43,5 +43,24 @@ namespace CanteenManagerApp
throw new Exception(result);
}
}
public static O? PostRequestWithResult<I, O>(string requestUrl, I model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
var temp = JsonConvert.DeserializeObject<O>(result);
return temp;
}
else
{
return default;
}
}
}
}

View File

@ -487,36 +487,23 @@ namespace CanteenManagerApp.Controllers
return View(new ReportBindingModel());
}
[HttpPost]
public void ReportPdf(ReportBindingModel model)
public List<ReportCooksPCView> ReportPdf([FromBody] ReportBindingModel model)
{
model.UserId = APIClient.Manager.Id;
APIClient.PostRequest("api/main/SaveCooksToPDF", model);
Response.Redirect("Index");
List<ReportCooksPCView> lunches = APIClient.PostRequestWithResult<ReportBindingModel, List<ReportCooksPCView>>("api/main/getCooksForPdf", model);
return lunches;
}
[HttpPost]
public int[]? SaveReport([FromBody] ReportBindingModel model)
{
model.UserId = APIClient.Manager.Id;
byte[] file = APIClient.PostRequestWithResult<ReportBindingModel, byte[]>("api/main/SaveOrdersToFile", model);
return file!.Select(b => (int)b).ToArray();
}
[HttpPost]
public void ReportXsl(ReportBindingModel model)
public void ReportEmail([FromBody] ReportBindingModel model)
{
model.UserId = APIClient.Manager.Id;
APIClient.PostRequest("api/main/SaveOrdersToXSL", model);
Response.Redirect("Index");
}
[HttpPost]
public void ReportWord(ReportBindingModel model)
{
model.UserId = APIClient.Manager.Id;
APIClient.PostRequest("api/main/SaveOrdersToWORD", model);
Response.Redirect("Index");
}
[HttpPost]
public void ReportEmail(ReportBindingModel model)
{
if (APIClient.Manager == null)
{
throw new Exception("Доступ возможен только авторизованным пользователям");
}
model.UserId = APIClient.Manager.Id;
APIClient.PostRequest($"api/manager/SendEmail", new MailSendInfoBindingModel
{
@ -524,7 +511,6 @@ namespace CanteenManagerApp.Controllers
Subject = "Отчет",
report = model
});
Response.Redirect("Report");
}
}

View File

@ -1,42 +1,123 @@
@using CanteenContracts.BindingModels;
@model ReportBindingModel
@{
@{
ViewBag.Title = "Report";
}
<body>
<h2>Отчеты</h2>
@using (Html.BeginForm("Report", "Home", FormMethod.Post))
{
<div class="row">
<h4>Pdf</h4>
<div class="col-md-6">
<div class="form-group">
@Html.LabelFor(m => m.DateAfter, "От")
@Html.TextBoxFor(m => m.DateAfter, new { type = "date", @class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
@Html.LabelFor(m => m.DateBefore, "До")
@Html.TextBoxFor(m => m.DateBefore, new { type = "date", @class = "form-control" })
</div>
</div>
</div>
<div class="form-group mt-2">
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportPdf", "Home")">Сохранить в pdf</button>
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportEmail", "Home")">Отправить pdf по почте</button>
</div>
<div class="mt-3">
<h4>Word, Excel</h4>
<div class="form-group mb-2">
@Html.LabelFor(m => m.ProductId, "Выбранные продукты")
@Html.DropDownListFor(m => m.ProductId, new SelectList(ViewBag.ProductList, "Id", "ProductName"), new { @class = "form-control", multiple = "multiple" })
</div>
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportXsl", "Home")">Сохранить в excel</button>
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportWord", "Home")">Сохранить в word</button>
</div>
<label for="ProductId">Выбранные продукты</label>
<select id="ProductId" name="LunchId" class="form-control" multiple>
@foreach (var item in ViewBag.ProductList)
{
<option value="@item.Id">@item.ProductName</option>
}
</select>
</div>
<button type="button" class="btn btn-primary" id="excel-button">Сохранить в excel</button>
<button type="button" class="btn btn-primary" id="word-button">Сохранить в word</button>
</div>
<div class="row">
<h4>Pdf</h4>
<div class="col-md-6">
<div class="form-group">
<label for="DateAfter">От</label>
<input type="date" id="DateAfter" name="DateAfter" class="form-control" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="DateBefore">До</label>
<input type="date" id="DateBefore" name="DateBefore" class="form-control" />
</div>
</div>
</div>
<div class="form-group mt-2">
<button type="button" id="show-button">Показать</button>
<button type="button" class="btn btn-primary" id="email-button">Отправить pdf по почте</button>
</div>
<table id="cooks-table" class="table table-striped">
<thead>
<tr>
<th>Id повара</th>
<th>ФИО повара</th>
<th>Id обеда</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="~/js/site.js"></script>
<script>
$(document).ready(function() {
$('#show-button').click(function() {
var model = {
"DateBefore": document.getElementById("DateBefore").value,
"DateAfter": document.getElementById("DateAfter").value
};
var jsonData = JSON.stringify(model);
$.ajax({
url: `/home/ReportPdf`,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(model),
success: function(data) {
var tableBody = $('#cooks-table tbody');
tableBody.empty();
$.each(data, function(index, cook) {
var rowCook = $('<tr></tr>');
var dateCell = $('<td></td>').text(cook.cookId);
rowCook.append(dateCell);
var lunchIdCell = $('<td></td>').text(cook.fio);
rowCook.append(lunchIdCell);
tableBody.append(rowCook);
$.each(cook.lunches, function(index, lunch) {
var rowLunch = $('<tr></tr>');
var orderCell = $('<td></td>').text(lunch.id);
rowLunch.append($('<td></td>').text(""));
rowLunch.append($('<td></td>').text(""));
rowLunch.append(orderCell);
tableBody.append(rowLunch);
});
});
},
error: function() {
console.log('Произошла ошибка при получении данных');
}
});
});
$('#email-button').click(function() {
var model = {
"DateBefore": document.getElementById("DateBefore").value,
"DateAfter": document.getElementById("DateAfter").value
};
var jsonData = JSON.stringify(model);
console.log(model);
$.ajax({
url: `/home/ReportEmail`,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(model)
});
});
});
</script>
</body>

View File

@ -1,4 +1,71 @@
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
const wordButton = document.getElementById("word-button");
const excelButton = document.getElementById("excel-button");
const productIdSelect = document.getElementById("ProductId");
const wordMIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const excelMIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Write your JavaScript code.
if (wordButton) {
wordButton.addEventListener("click", () => {
saveList("docx");
console.log("сохранить в docx")
});
}
if (excelButton) {
excelButton.addEventListener("click", () => {
saveList("xlsx");
});
}
const saveList = async function (fileType) {
let productIdSelect = document.getElementById("ProductId");
if (!productIdSelect) {
console.log("Element with id 'ProductId' not found.");
return;
}
let listModel = {
"ProductId": Array.from(productIdSelect.selectedOptions).map(option => option.value),
"FileType": fileType
};
$.ajax({
url: `/home/SaveReport`,
type: 'POST',
contentType: 'application/json',
headers: { "Content-Type": "application/json" },
data: JSON.stringify(listModel)
}).done((file) => {
let byteArray = new Uint8Array(file);
saveFile(byteArray, fileType);
});
};
const saveFile = async function (bytes, fileType) {
if (window.showSaveFilePicker) {
let type;
if (fileType == "docx") {
type = {
description: "Microsoft Word (OpenXML)",
accept: { [wordMIME]: [".docx"] }
};
} else if (fileType == "xlsx") {
type = {
description: "Microsoft Excel (OpenXML)",
accept: { [excelMIME]: [".xlsx"] }
};
}
const opts = {
suggestedName: `equipment-purchase-list.${fileType}`,
types: [type],
};
try {
const handle = await showSaveFilePicker(opts);
const writable = await handle.createWritable();
await writable.write(bytes);
await writable.close();
} catch (error) {
console.error("Error saving file:", error);
}
}
};

View File

@ -37,11 +37,11 @@ namespace CanteenRestApi.Controllers
}
[HttpPost]
public void SaveLunchesToPDF(ReportBindingModel model)
public List<ReportLunchesPCView> getLunchesForPdf(ReportBindingModel model)
{
try
{
_reportLogic.saveLunchesToPdfFile(new ReportBindingModel()
return _reportLogic.GetLunchesPCView(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
@ -55,11 +55,11 @@ namespace CanteenRestApi.Controllers
}
}
[HttpPost]
public void SaveCooksToPDF(ReportBindingModel model)
public List<ReportCooksPCView> getCooksForPdf(ReportBindingModel model)
{
try
{
_reportLogic.saveCooksToPdfFile(new ReportBindingModel()
return _reportLogic.GetCooksPCView(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
@ -74,11 +74,14 @@ namespace CanteenRestApi.Controllers
}
[HttpPost]
public void SaveCooksToXSL(ReportBindingModel model)
public byte[] SaveCooksToFile(ReportBindingModel model)
{
byte[] report = Array.Empty<byte>();
try
{
_reportLogic.saveCooksToExcel(new ReportBindingModel()
if (model.FileType.Equals("xlsx"))
{
report = _reportLogic.saveCooksToExcel(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
@ -86,19 +89,9 @@ namespace CanteenRestApi.Controllers
LunchId = model.LunchId
});
}
catch (Exception ex)
else if (model.FileType.Equals("docx"))
{
_logger.LogError(ex, "Error during loading list of bouquets");
throw;
}
}
[HttpPost]
public void SaveCooksToWORD(ReportBindingModel model)
{
try
{
_reportLogic.saveCooksToWord(new ReportBindingModel()
report = _reportLogic.saveCooksToWord(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
@ -106,50 +99,91 @@ namespace CanteenRestApi.Controllers
LunchId = model.LunchId
});
}
return report;
}
catch (Exception ex)
{
return report;
_logger.LogError(ex, "Error during loading list of bouquets");
throw;
}
}
[HttpPost]
public void SaveOrdersToXSL(ReportBindingModel model)
{
try
{
_reportLogic.saveOrdersToExcel(new ReportBindingModel()
{
UserId = model.UserId,
ProductId = model.ProductId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during loading list of bouquets");
throw;
}
}
//[HttpPost]
//public void SaveCooksToWORD(ReportBindingModel model)
//{
// byte[] report = Array.Empty<byte>();
// try
// {
// _reportLogic.saveCooksToWord(new ReportBindingModel()
// {
// DateAfter = model.DateAfter,
// DateBefore = model.DateBefore,
// UserId = model.UserId,
// LunchId = model.LunchId
// });
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Error during loading list of bouquets");
// throw;
// }
//}
[HttpPost]
public void SaveOrdersToWORD(ReportBindingModel model)
public byte[] SaveOrdersToFile(ReportBindingModel model)
{
byte[] report = Array.Empty<byte>();
try
{
_reportLogic.saveOrdersToWord(new ReportBindingModel()
if (model.FileType.Equals("xlsx"))
{
report = _reportLogic.saveOrdersToExcel(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
UserId = model.UserId,
ProductId = model.ProductId
});
}
else if (model.FileType.Equals("docx"))
{
report = _reportLogic.saveOrdersToWord(new ReportBindingModel()
{
DateAfter = model.DateAfter,
DateBefore = model.DateBefore,
UserId = model.UserId,
ProductId = model.ProductId
});
}
return report;
}
catch (Exception ex)
{
return report;
_logger.LogError(ex, "Error during loading list of bouquets");
throw;
}
}
//[HttpPost]
//public void SaveOrdersToWORD(ReportBindingModel model)
//{
// try
// {
// _reportLogic.saveOrdersToWord(new ReportBindingModel()
// {
// UserId = model.UserId,
// ProductId = model.ProductId
// });
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Error during loading list of bouquets");
// throw;
// }
//}
[HttpGet]
public List<TablewareViewModel>? GetTablewareList(int visitorId)
{

View File

@ -40,5 +40,24 @@ namespace CanteenVisitorApp
throw new Exception(result);
}
}
public static O? PostRequestWithResult<I, O>(string requestUrl, I model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
var temp = JsonConvert.DeserializeObject<O>(result);
return temp;
}
else
{
return default;
}
}
}
}

View File

@ -1,5 +1,6 @@
using CanteenContracts.BindingModels;
using CanteenContracts.View;
using CanteenContracts.ViewModels;
using CanteenVisitorApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
@ -541,31 +542,23 @@ namespace CanteenVisitorApp.Controllers
return View(new ReportBindingModel());
}
[HttpPost]
public void ReportPdf(ReportBindingModel model)
public List<ReportLunchesPCView> ReportPdf([FromBody] ReportBindingModel model)
{
model.UserId = APIClient.Visitor.Id;
APIClient.PostRequest("api/main/SaveLunchesToPDF", model);
Response.Redirect("Index");
List<ReportLunchesPCView> lunches = APIClient.PostRequestWithResult<ReportBindingModel, List<ReportLunchesPCView>>("api/main/getLunchesForPdf", model);
return lunches;
}
[HttpPost]
public void ReportXsl(ReportBindingModel model)
public int[]? SaveReport([FromBody] ReportBindingModel model)
{
model.UserId = APIClient.Visitor.Id;
APIClient.PostRequest("api/main/SaveCooksToXSL", model);
Response.Redirect("Index");
byte[] file = APIClient.PostRequestWithResult<ReportBindingModel, byte[]>("api/main/SaveCooksToFile", model);
return file!.Select(b => (int)b).ToArray();
}
[HttpPost]
public void ReportWord(ReportBindingModel model)
{
model.UserId = APIClient.Visitor.Id;
APIClient.PostRequest("api/main/SaveCooksToWORD", model);
Response.Redirect("Index");
}
[HttpPost]
public void ReportEmail(ReportBindingModel model)
public void ReportEmail([FromBody] ReportBindingModel model)
{
model.UserId = APIClient.Visitor.Id;
APIClient.PostRequest($"api/visitor/SendEmail", new MailSendInfoBindingModel

View File

@ -1,42 +1,138 @@
@using CanteenContracts.BindingModels;
@model ReportBindingModel
@{
@{
ViewBag.Title = "Report";
}
<body>
<h2>Отчеты</h2>
@using (Html.BeginForm("Report", "Home", FormMethod.Post))
{
<div class="row">
<h4>Pdf</h4>
<div class="col-md-6">
<div class="form-group">
@Html.LabelFor(m => m.DateAfter, "От")
@Html.TextBoxFor(m => m.DateAfter, new { type = "date", @class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
@Html.LabelFor(m => m.DateBefore, "До")
@Html.TextBoxFor(m => m.DateBefore, new { type = "date", @class = "form-control" })
</div>
</div>
</div>
<div class="form-group mt-2">
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportPdf", "Home")">Сохранить в pdf</button>
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportEmail", "Home")">Отправить pdf по почте</button>
</div>
<div class="mt-3">
<h4>Word, Excel</h4>
<div class="form-group mb-2">
@Html.LabelFor(m => m.LunchId, "Выбранные обеды")
@Html.DropDownListFor(m => m.LunchId, new SelectList(ViewBag.LunchList, "Id", "LunchName"), new { @class = "form-control", multiple = "multiple" })
</div>
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportXsl", "Home")">Сохранить в excel</button>
<button type="submit" class="btn btn-primary" formaction="@Url.Action("ReportWord", "Home")">Сохранить в word</button>
</div>
<label for="LunchId">Выбранные обеды</label>
<select id="LunchId" name="LunchId" class="form-control" multiple>
@foreach (var item in ViewBag.LunchList)
{
<option value="@item.Id">@item.LunchName</option>
}
</select>
</div>
<button type="button" class="btn btn-primary" id="excel-button">Сохранить в excel</button>
<button type="button" class="btn btn-primary" id="word-button">Сохранить в word</button>
</div>
<div class="row">
<h4>Pdf</h4>
<div class="col-md-6">
<div class="form-group">
<label for="DateAfter">От</label>
<input type="date" id="DateAfter" name="DateAfter" class="form-control" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="DateBefore">До</label>
<input type="date" id="DateBefore" name="DateBefore" class="form-control" />
</div>
</div>
</div>
<div class="form-group mt-2">
<button type="button" id="show-button">Показать</button>
<button type="button" class="btn btn-primary" id="email-button">Отправить pdf по почте</button>
</div>
<table id="cooks-table" class="table table-striped">
<thead>
<tr>
<th>Дата обеда</th>
<th>Сумма обеда</th>
<th>Id заказа</th>
<th>ФИО повара</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="~/js/site.js"></script>
<script>
$(document).ready(function() {
$('#show-button').click(function() {
var model = {
"DateBefore": document.getElementById("DateBefore").value,
"DateAfter": document.getElementById("DateAfter").value
};
//console.log(model);
var jsonData = JSON.stringify(model);
// Отправка AJAX-запроса на сервер
$.ajax({
url: `/home/ReportPdf`,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(model),
success: function(data) {
var tableBody = $('#cooks-table tbody');
tableBody.empty();
$.each(data, function(index, lunch) {
var rowLunch = $('<tr></tr>');
var dateCell = $('<td></td>').text(lunch.dateCreate);
rowLunch.append(dateCell);
var lunchIdCell = $('<td></td>').text(lunch.sum);
rowLunch.append(lunchIdCell);
tableBody.append(rowLunch);
$.each(lunch.orders, function(index, order) {
var rowOrder = $('<tr></tr>');
var orderCell = $('<td></td>').text(order.id);
rowOrder.append($('<td></td>').text(""));
rowOrder.append($('<td></td>').text(""));
rowOrder.append(orderCell);
tableBody.append(rowOrder);
$.each(order.orderCooks, function(index, cook) {
var rowCook = $('<tr></tr>');
var cookCell = $('<td></td>').text(cook.fio);
rowCook.append($('<td></td>').text(""));
rowCook.append($('<td></td>').text(""));
rowCook.append($('<td></td>').text(""));
rowCook.append(cookCell);
tableBody.append(rowCook);
});
});
});
},
error: function() {
console.log('Произошла ошибка при получении данных');
}
});
});
$('#email-button').click(function() {
var model = {
"DateBefore": document.getElementById("DateBefore").value,
"DateAfter": document.getElementById("DateAfter").value
};
var jsonData = JSON.stringify(model);
console.log(model);
$.ajax({
url: `/home/ReportEmail`,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(model)
});
});
});
</script>
</body>

View File

@ -1,4 +1,71 @@
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
const wordButton = document.getElementById("word-button");
const excelButton = document.getElementById("excel-button");
const lunchIdSelect = document.getElementById("LunchId");
const wordMIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const excelMIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Write your JavaScript code.
if (wordButton) {
wordButton.addEventListener("click", () => {
saveList("docx");
console.log("сохранить в docx")
});
}
if (excelButton) {
excelButton.addEventListener("click", () => {
saveList("xlsx");
});
}
const saveList = async function (fileType) {
let lunchIdSelect = document.getElementById("LunchId");
if (!lunchIdSelect) {
console.log("Element with id 'LunchId' not found.");
return;
}
let listModel = {
"LunchId": Array.from(lunchIdSelect.selectedOptions).map(option => option.value),
"FileType": fileType
};
$.ajax({
url: `/home/SaveReport`,
type: 'POST',
contentType: 'application/json',
headers: { "Content-Type": "application/json" },
data: JSON.stringify(listModel)
}).done((file) => {
let byteArray = new Uint8Array(file);
saveFile(byteArray, fileType);
});
};
const saveFile = async function (bytes, fileType) {
if (window.showSaveFilePicker) {
let type;
if (fileType == "docx") {
type = {
description: "Microsoft Word (OpenXML)",
accept: { [wordMIME]: [".docx"] }
};
} else if (fileType == "xlsx") {
type = {
description: "Microsoft Excel (OpenXML)",
accept: { [excelMIME]: [".xlsx"] }
};
}
const opts = {
suggestedName: `equipment-purchase-list.${fileType}`,
types: [type],
};
try {
const handle = await showSaveFilePicker(opts);
const writable = await handle.createWritable();
await writable.write(bytes);
await writable.close();
} catch (error) {
console.error("Error saving file:", error);
}
}
};