Emp docx report

This commit is contained in:
Илья Федотов 2024-07-29 21:12:31 +04:00
parent 20ce7a36f9
commit 1fd9aaf8c1
11 changed files with 181 additions and 80 deletions

View File

@ -1,7 +1,9 @@
using ElectronicsShopBusinessLogic.OfficePackage;
using DocumentFormat.OpenXml.Office.CustomUI;
using ElectronicsShopBusinessLogic.OfficePackage;
using ElectronicsShopBusinessLogic.OfficePackage.HelperModels;
using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.BusinessLogicContracts;
using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.StorageContracts;
using ElectronicsShopContracts.ViewModels;
using System;
@ -15,36 +17,83 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
public class ReportEmployeeLogic : IReportEmployeeLogic
{
private readonly IProductStorage _productStorage;
private readonly IPaymeantStorage _paymeantStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToWordEmployee _saveToWord;
private readonly AbstractSaveToExcelEmployee _saveToExcel;
public ReportEmployeeLogic(AbstractSaveToExcelEmployee abstractSaveToExcelEmployee, AbstractSaveToWordEmployee abstractSaveToWordEmployee, IProductStorage productStorage) {
public ReportEmployeeLogic(AbstractSaveToExcelEmployee abstractSaveToExcelEmployee, AbstractSaveToWordEmployee abstractSaveToWordEmployee,
IProductStorage productStorage, IPaymeantStorage paymeantStorage, IOrderStorage orderStorage) {
_productStorage = productStorage;
_saveToExcel = abstractSaveToExcelEmployee;
_paymeantStorage = paymeantStorage;
_orderStorage = orderStorage;
_saveToExcel = abstractSaveToExcelEmployee;
_saveToWord = abstractSaveToWordEmployee;
}
public List<ReportProductsViewModel> GetProduct(ReportProductBindingModel model)
public List<ReportProductInPaymeantsViewModel> GetProducts(ReportProductBindingModel model)
{
throw new NotImplementedException();
}
var paymeants = _paymeantStorage.GetFillteredList(new PaymeantSearchModel {
DateFrom = model.DateFrom,
DateTo = model.DateTo,
});
List<PaymeantProduct> paymeantProductList = new();
foreach (var paymeant in paymeants) {
var order = _orderStorage.GetElement(new OrderSearchModel { ID = paymeant.OrderID }) ?? throw new Exception("Ошибка получения данных");
foreach (var product in order.ProductList) {
paymeantProductList.Add(new(paymeant.ID, product.Key, product.Value.Item2));
}
}
paymeantProductList.OrderBy(x => x.ProductID);
List<ReportProductInPaymeantsViewModel> ansProductsList = new();
List<string> productNames = new();
foreach (var pp in paymeantProductList) {
var product = _productStorage.GetElement(new ProductSearchModel { ID = pp.ProductID})
?? throw new Exception("Ошибка получения данных");
if (productNames.Contains(product.ProductName) == false) {
productNames.Add(product.ProductName);
// создаем запись
var record = new ReportProductInPaymeantsViewModel {
ProductName = product.ProductName,
Values = new(),
Total = 0
};
ansProductsList.Add(record);
}
// Ищем запись и вносим изменения
int index = ansProductsList.IndexOf(ansProductsList.First(x => x.ProductName == product.ProductName));
var paymeant = _paymeantStorage.GetElement(new PaymeantSearchModel { ID = pp.PaymeantID })
?? throw new Exception("Ошибка получения данных");
ansProductsList[index].Values.Add(new(pp.PaymeantID, pp.Count, paymeant.PayOption.ToString(), product.Price * pp.Count));
ansProductsList[index].Total++;
}
return ansProductsList;
}
public void SaveProductsToExcelFile(ReportProductBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfoEmployee
{
FileName = model.FileName,
Title = "Список продуктов",
Products = _productStorage.GetFullList(),
});
}
public void SaveProductsToWordFile(ReportProductBindingModel model)
public byte[]? SaveProductsToWordFile(ReportProductBindingModel model)
{
_saveToWord.CreateDoc(new WordInfoEmployee
{
FileName = model.FileName,
Title = "Список продуктов",
ListProduct = _productStorage.GetFullList()
var document = _saveToWord.CreateDoc(new WordInfoEmployee {
Title = "Список оплат электротоваров",
ListProduct = GetProducts(model)
});
return document;
}
}
}
}

View File

@ -10,7 +10,7 @@ namespace ElectronicsShopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWordEmployee
{
public void CreateDoc(WordInfoEmployee info)
public byte[]? CreateDoc(WordInfoEmployee info)
{
CreateWord(info);
@ -24,51 +24,46 @@ namespace ElectronicsShopBusinessLogic.OfficePackage
}
});
foreach (var product in info.ListProduct)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{ (product.ProductName, new WordTextProperties { Size = "24", Bold=true})},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{ (product.ProductName, new WordTextProperties { Size = "20", Bold=false})},
TextProperties = new WordTextProperties
{
foreach (var data in info.ListProduct) {
CreateParagraph(new WordParagraph {
Texts = new List<(string, WordTextProperties)> { (data.ProductName, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties {
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
foreach (var paymeant in data.Values) {
CreateParagraph(new WordParagraph {
Texts = new List<(string, WordTextProperties)> { ($"Оплата №:{paymeant.PaymeantID} статус:{paymeant.PaymeantStatus}",
new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties {
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
CreateParagraph(new WordParagraph {
Texts = new List<(string, WordTextProperties)> { ($"Итого:{data.Total}",
new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties {
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
var document = SaveWord(info);
return document;
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
// Создание doc-файла
protected abstract void CreateWord(WordInfoEmployee info);
/// <summary>
/// Создание абзаца с текстом
/// </summary>
/// <param name="paragraph"></param>
/// <returns></returns>
// Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveWord(WordInfoEmployee info);
// Сохранение файла
protected abstract byte[]? SaveWord(WordInfoEmployee info);
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicsShopBusinessLogic.OfficePackage.HelperModels {
public class PaymeantProduct {
public int PaymeantID { get; set; }
public int ProductID { get; set; }
// количество товара в оплате
public int Count { get; set; }
public PaymeantProduct(int paymeantID, int productID, int count) {
PaymeantID = paymeantID;
ProductID = productID;
Count = count;
}
}
}

View File

@ -5,10 +5,8 @@ namespace ElectronicsShopBusinessLogic.OfficePackage.HelperModels
{
public class WordInfoEmployee
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ProductViewModel> ListProduct { get; set; } = new();
public List<ReportProductInPaymeantsViewModel> ListProduct { get; set; } = new();
}
}

View File

@ -12,12 +12,10 @@ namespace ElectronicsShopBusinessLogic.OfficePackage.Implements
private Body? _docBody;
/// <summary>
/// Получение типа выравнивания
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static JustificationValues GetJustificationValues(WordJustificationType type)
private MemoryStream _mem = new MemoryStream();
// Получение типа выравнивания
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
@ -27,10 +25,7 @@ namespace ElectronicsShopBusinessLogic.OfficePackage.Implements
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
// Настройки страницы
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
@ -45,11 +40,7 @@ namespace ElectronicsShopBusinessLogic.OfficePackage.Implements
return properties;
}
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
// Задание форматирования для абзаца
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
@ -83,7 +74,7 @@ namespace ElectronicsShopBusinessLogic.OfficePackage.Implements
protected override void CreateWord(WordInfoEmployee info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
_wordDocument = WordprocessingDocument.Create(_mem, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
@ -119,17 +110,19 @@ namespace ElectronicsShopBusinessLogic.OfficePackage.Implements
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfoEmployee info)
protected override byte[]? SaveWord(WordInfoEmployee info)
{
if (_docBody == null || _wordDocument == null)
{
return;
return null;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
return _mem.ToArray();
}
}
}
}

View File

@ -8,8 +8,7 @@ namespace ElectronicsShopContracts.BindingModels
{
public class ReportProductBindingModel
{
public string FileName { get; set; } = string.Empty;
public List<int>? Product { get; set; }
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
}
}

View File

@ -10,8 +10,8 @@ namespace ElectronicsShopContracts.BusinessLogicContracts
{
public interface IReportEmployeeLogic
{
List<ReportProductsViewModel> GetProduct(ReportProductBindingModel model);
void SaveProductsToWordFile(ReportProductBindingModel model);
List<ReportProductInPaymeantsViewModel> GetProducts(ReportProductBindingModel model);
byte[]? SaveProductsToWordFile(ReportProductBindingModel model);
void SaveProductsToExcelFile(ReportProductBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicsShopContracts.ViewModels {
public class ReportProductInPaymeantsViewModel {
public string ProductName { get; set; } = string.Empty;
public List<(int PaymeantID, int ProducCount, string PaymeantStatus, double ProductSum)> Values = new();
// Итоговое количество оплат
public int Total { get; set; }
}
}

View File

@ -1,3 +1,4 @@
using DocumentFormat.OpenXml.Spreadsheet;
using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.ViewModels;
@ -340,5 +341,16 @@ namespace ElectronicsShopEmployeeApp.Controllers {
(DateTime, DateTime, List<PaymeantViewModel>?) tuple = (DateTime.Parse(_datefrom), DateTime.Parse(_dateto), reports);
return View(tuple);
}
[HttpGet]
public IActionResult CreateWordReport(string DateFrom, string DateTo) {
var fileMemStream = APIEmployee.GetRequset<byte[]>($"api/Employee/CreateDocxReport?from={DateFrom}&to={DateTo}");
if (fileMemStream == null) {
throw new Exception("Îøèáêà ñîçäàíèÿ îò÷åòà");
}
return File(fileMemStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Report.docx");
}
}
}

View File

@ -25,7 +25,8 @@
</div>
<div class="row">
<div class="col-8">
<a class="btn btn-primary btn-sm" asp-action="CreateWordReport" style="background-color:#335a95;">Экспорт отчета в .xlsx</a>
<a class="btn btn-primary btn-sm" asp-action="CreateWordReport" asp-route-DateFrom="@Model.Item1"
asp-route-DateTo="@Model.Item2" style="background-color:#335a95;">Экспорт отчета в .xlsx</a>
<a class="btn btn-primary btn-sm" asp-action="CreateExcelReport" style="background-color:#04713A;">Экспорт отчета в .docx</a>
<a class="btn btn-primary btn-sm" asp-action="CreatePdfReport" asp-route-DateFrom="@Model.Item1"
asp-route-DateTo="@Model.Item2" style="background-color:#ad0d09;">отправить на Email отчет в .pdf</a>

View File

@ -16,12 +16,15 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly IEmployeeLogic _logic;
private readonly ICostItemLogic _costItem;
private readonly IProductLogic _productLogic;
private readonly IReportEmployeeLogic _reportEmployeeLogic;
public EmployeeController(ILogger<EmployeeController> logger, IEmployeeLogic logic, ICostItemLogic costItem, IProductLogic productLogic) {
public EmployeeController(ILogger<EmployeeController> logger, IEmployeeLogic logic, ICostItemLogic costItem, IProductLogic productLogic,
IReportEmployeeLogic reportEmployeeLogic) {
_logger = logger;
_logic = logic;
_costItem = costItem;
_productLogic = productLogic;
_reportEmployeeLogic = reportEmployeeLogic;
}
[HttpGet]
@ -147,5 +150,20 @@ namespace ElectronicsShopRestAPI.Controllers {
throw;
}
}
[HttpGet]
public byte[]? CreateDocxReport(string from, string to) {
try {
var document = _reportEmployeeLogic.SaveProductsToWordFile(new ReportProductBindingModel {
DateFrom = DateTime.Parse(from),
DateTo = DateTime.Parse(to)
});
return document;
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка создания файла");
throw;
}
}
}
}