diff --git a/Bank/BankBusinessLogic/BusinessLogic/Client/ClientLogic.cs b/Bank/BankBusinessLogic/BusinessLogic/Client/ClientLogic.cs index 9b3cced..5628782 100644 --- a/Bank/BankBusinessLogic/BusinessLogic/Client/ClientLogic.cs +++ b/Bank/BankBusinessLogic/BusinessLogic/Client/ClientLogic.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BankBusinessLogic.BusinessLogic.Client @@ -36,7 +37,7 @@ namespace BankBusinessLogic.BusinessLogic.Client _logger.LogInformation("ReadElement. Name:{Name}.Surname:{Surname}.Patronymic:{Patronymic}.Id:{Id}", model.Name, model.Surname, model.Patronymic, model.Id); var element = _clientStorage.GetElement(model); - + if (element == null) { _logger.LogWarning("Read element not found"); @@ -69,7 +70,7 @@ namespace BankBusinessLogic.BusinessLogic.Client public bool Create(ClientBindingModel model) { CheckModel(model); - + if (_clientStorage.Insert(model) == null) { _logger.LogWarning("Insert operation failed"); @@ -83,7 +84,7 @@ namespace BankBusinessLogic.BusinessLogic.Client public bool Update(ClientBindingModel model) { CheckModel(model); - + if (_clientStorage.Update(model) == null) { _logger.LogWarning("Update operation failed"); @@ -97,9 +98,9 @@ namespace BankBusinessLogic.BusinessLogic.Client public bool Delete(ClientBindingModel model) { CheckModel(model, false); - + _logger.LogInformation("Delete. Id:{Id}", model.Id); - + if (_clientStorage.Delete(model) == null) { _logger.LogWarning("Delete operation failed"); @@ -159,6 +160,17 @@ namespace BankBusinessLogic.BusinessLogic.Client throw new ArgumentNullException("Нет моб.телефона пользователя", nameof(model.MobilePhone)); } + if (!Regex.IsMatch(model.Email, @"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$", RegexOptions.IgnoreCase)) + { + throw new ArgumentException("Некорректная почта", nameof(model.Email)); + } + + if (!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase) + && model.Password.Length < 10 && model.Password.Length > 50) + { + throw new ArgumentException("Необходимо придумать другой пароль", nameof(model.Password)); + } + _logger.LogInformation("Client. Name:{Name}.Surname:{Surname}.Patronymic:{Patronymic}.Email:{Email}.Password:{Password}.Mobeliphone:{MobilePhone}.Id:{Id}", model.Name, model.Surname, model.Patronymic, model.Email, model.Password, model.MobilePhone, model.Id); diff --git a/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToExcel.cs index c228a49..2faec2e 100644 --- a/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToExcel.cs +++ b/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -11,16 +11,620 @@ namespace BankBusinessLogic.OfficePackage { public abstract class AbstractSaveToExcel { - /// Создание excel-файла - protected abstract void CreateExcel(ExcelInfo info); + // Создание отчета. Описание методов ниже + public void CreateReport(ExcelInfo info, OfficeOperationEnum operationEnum) + { + if (operationEnum == OfficeOperationEnum.Между_cчетами) + { + CreateMoneyTransferExcel(info); + } - /// Добавляем новую ячейку в лист - protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); + if (operationEnum == OfficeOperationEnum.Пополнение_карт) + { + CreateCreditingExcel(info); + } - /// Объединение ячеек - protected abstract void MergeCells(ExcelMergeParameters excelParams); + if (operationEnum == OfficeOperationEnum.Cнятие_с_карты) + { + CreateDebitingExcel(info); + } - /// Сохранение файла - protected abstract void SaveExcel(ExcelInfo info); - } + if (operationEnum == OfficeOperationEnum.Для_кассира) + { + CreateCashierExcel(info); + } + } + + private void CreateMoneyTransferExcel(ExcelInfo info) + { + CreateExcel(info); + + // Вставляет заголовок + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + // Соединяет 3 ячейки для заголовка + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "C1" + }); + + // Номер строчки в докуметне + uint rowIndex = 2; + + foreach (var mt in info.MoneyTransfer) + { + // Вставляет номер перевода + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Перевод №" + mt.Id, + StyleInfo = ExcelStyleInfoType.Text + }); + + rowIndex++; + + // Строчка с номером счёта отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Номер счёта отправителя: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = mt.AccountSenderNumber, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + + // Строчка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Номер счёта получателя: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = mt.AccountPayeeNumber, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + + // Вставляет слово "Сумма перевода" + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Сумма перевода: ", + StyleInfo = ExcelStyleInfoType.Text + }); + + // Подсчитывает общее кол-во сумму + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = mt.Sum.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + rowIndex++; + + // Вставляет слово "Сумма перевода" + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Дата операции: ", + StyleInfo = ExcelStyleInfoType.Text + }); + + // Подсчитывает общее кол-во переводов + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = mt.DateTransfer.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + rowIndex++; + } + + rowIndex++; + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Суммарный объём переводов: ", + StyleInfo = ExcelStyleInfoType.Text + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A" + rowIndex.ToString(), + CellToName = "B" + rowIndex.ToString() + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = info.MoneyTransfer.Sum(x => x.Sum).ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + SaveExcel(info); + } + + private void CreateCreditingExcel(ExcelInfo info) + { + CreateExcel(info); + + // Вставляет заголовок операции + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + // Соединяет 3 ячейки для заголовка + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "E2" + }); + + // Номер строчки в докуметне + uint rowIndex = 3; + + foreach (var cr in info.Crediting) + { + // Вставляет номер перевода + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Пополнение №" + cr.Id, + StyleInfo = ExcelStyleInfoType.Text + }); + + rowIndex++; + + // Строчка с номером счёта отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Номер карты: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = cr.CardNumber, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + + // Строчка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Сумма пополнения: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = cr.Sum.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + rowIndex++; + + // Формирование списка поступления по каждой карте + var dict = new Dictionary(); + + foreach (var elem in info.Crediting) + { + if (dict.ContainsKey(elem.CardNumber)) + { + dict[elem.CardNumber] += elem.Sum; + } + else + { + dict[elem.CardNumber] = elem.Sum; + } + } + + foreach (var elem in dict) + { + // Cтрочка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Сумма пополнения на карту №" + elem.Key + ":", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = elem.Value.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + rowIndex++; + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Суммарный объём пополнений: ", + StyleInfo = ExcelStyleInfoType.Text + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A" + rowIndex.ToString(), + CellToName = "B" + rowIndex.ToString() + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = info.Crediting.Sum(x => x.Sum).ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + SaveExcel(info); + } + + private void CreateDebitingExcel(ExcelInfo info) + { + CreateExcel(info); + + // Вставляет заголовок + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + // Соединяет 3 ячейки для заголовка + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "E2" + }); + + // Номер строчки в докуметне + uint rowIndex = 3; + + foreach (var cr in info.Debiting) + { + // Вставляет номер перевода + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Снятие №" + cr.Id, + StyleInfo = ExcelStyleInfoType.Text + }); + + rowIndex++; + + // Строчка с номером счёта отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Номер карты: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = cr.CardNumber, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + + // Строчка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Сумма снятия: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = cr.Sum.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + rowIndex++; + + // Формирование списка поступления по каждой карте + var dict = new Dictionary(); + + foreach (var elem in info.Debiting) + { + if (dict.ContainsKey(elem.CardNumber)) + { + dict[elem.CardNumber] += elem.Sum; + } + else + { + dict[elem.CardNumber] = elem.Sum; + } + } + + foreach (var elem in dict) + { + // Строчка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Сумма снятия с карты №" + elem.Key + ":", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = elem.Value.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + rowIndex++; + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Суммарный объём снятий: ", + StyleInfo = ExcelStyleInfoType.Text + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A" + rowIndex.ToString(), + CellToName = "B" + rowIndex.ToString() + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = info.Debiting.Sum(x => x.Sum).ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + SaveExcel(info); + } + + private void CreateCashierExcel(ExcelInfo info) + { + CreateExcel(info); + + // Вставляет заголовок + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + // Соединяет 3 ячейки для заголовка + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "E2" + }); + + // Номер строчки в докуметне + uint rowIndex = 3; + + foreach (var cr in info.Debiting) + { + // Вставляет номер перевода + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Заявка №" + cr.Id, + StyleInfo = ExcelStyleInfoType.Text + }); + + rowIndex++; + + // Строчка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Сумма заявки: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка суммы заявки + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = cr.Sum.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + + // Строчка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Статус: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + // Вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = cr.Status.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + + //строчка с номером счёта получателя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = "Дата: ", + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + //вставка номера отправителя + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = cr.DateDebit == null ? "В обработке" : cr.DateDebit.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + rowIndex++; + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Суммарный объём открытых заявок на снятие: ", + StyleInfo = ExcelStyleInfoType.Text + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A" + rowIndex.ToString(), + CellToName = "C" + rowIndex.ToString() + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "D", + RowIndex = rowIndex, + Text = info.Debiting.Where(x => x.Status == StatusCard.Открыта).Sum(x => x.Sum).ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + rowIndex += 2; + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Суммарный объём закртытых заявок на снятие: ", + StyleInfo = ExcelStyleInfoType.Text + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A" + rowIndex.ToString(), + CellToName = "C" + rowIndex.ToString() + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "D", + RowIndex = rowIndex, + Text = info.Debiting.Where(x => x.Status == StatusCard.Закрыта).Sum(x => x.Sum).ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + SaveExcel(info); + } + + // Создание excel-файла + protected abstract void CreateExcel(ExcelInfo info); + + // Добавляем новую ячейку в лист + protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); + + // Объединение ячеек + protected abstract void MergeCells(ExcelMergeParameters excelParams); + + // Сохранение файла + protected abstract void SaveExcel(ExcelInfo info); + } } diff --git a/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToPdf.cs index d18e0c1..05f9c8d 100644 --- a/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToPdf.cs +++ b/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -1,4 +1,5 @@ -using BankBusinessLogic.OfficePackage.HelperModels; +using BankBusinessLogic.OfficePackage.HelperEnums; +using BankBusinessLogic.OfficePackage.HelperModels; using System; using System.Collections.Generic; using System.Linq; @@ -9,19 +10,178 @@ namespace BankBusinessLogic.OfficePackage { public abstract class AbstractSaveToPdf { - /// Создание pdf-файла - protected abstract void CreatePdf(PdfInfo info); + // Публичный метод создания документа. Описание методов ниже + public void CreateDoc(PdfInfo info) + { + if (info.ForClient) + { + CreateDocClient(info); + } + else + { + CreateDocCashier(info); + } + } - /// Создание параграфа с текстом - protected abstract void CreateParagraph(PdfParagraph paragraph); + // Отчёт для клиента - /// Создание таблицы - protected abstract void CreateTable(List columns); + public void CreateDocClient(PdfInfo info) + { + CreatePdf(info); - /// Создание и заполнение строки - protected abstract void CreateRow(PdfRowParameters rowParameters); + CreateParagraph(new PdfParagraph + { + Text = info.Title + $"\nот {DateTime.Now.ToShortDateString()}", - /// Сохранение файла - protected abstract void SavePdf(PdfInfo info); - } + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + CreateParagraph(new PdfParagraph + { + Text = $"Расчётный период: с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + // Параграф с отчётом на пополнения + CreateParagraph(new PdfParagraph { Text = "Отчёт по пополнениям", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "3cm", "3cm", "5cm", "5cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер операции", "Номер карты", "Сумма", "Дата операции" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var report in info.ReportCrediting) + { + CreateRow(new PdfRowParameters + { + Texts = new List { report.OperationId.ToString(), report.CardNumber, report.SumOperation.ToString(), report.DateComplite.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + + // Подсчёт суммы операций на пополнение + CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма поступлений за период: {info.ReportCrediting.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + // Отчёт с отчётом на снятие + CreateParagraph(new PdfParagraph { Text = "Отчёт по снятиям", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "3cm", "3cm", "5cm", "5cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер операции", "Номер карты", "Сумма", "Дата операции" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var report in info.ReportDebiting) + { + CreateRow(new PdfRowParameters + { + Texts = new List { report.OperationId.ToString(), report.CardNumber, report.SumOperation.ToString(), report.DateComplite.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + + // Подсчёт суммы операций на пополнение + CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма снятий за период: {info.ReportDebiting.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + SavePdf(info); + } + + //=== Отчёты для кассира ===// + + // Создание отчёта для кассира + public void CreateDocCashier(PdfInfo info) + { + CreatePdf(info); + + CreateParagraph(new PdfParagraph + { + Text = info.Title + $"\nот {DateTime.Now.ToShortDateString()}\nФИО клиента: {info.FullClientName}", + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + CreateParagraph(new PdfParagraph + { + Text = $"Расчётный период: с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + // Параграф с отчётом по выдаче наличных с карт + CreateParagraph(new PdfParagraph { Text = "Отчёт по выдаче наличных со счёта", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "3.5cm", "3.5cm", "5cm", "5cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер операции", "Номер счёта", "Сумма операции", "Дата операции" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var report in info.ReportCashWithdrawal) + { + CreateRow(new PdfRowParameters + { + Texts = new List { report.OperationId.ToString(), report.AccountPayeeNumber, report.SumOperation.ToString(), report.DateComplite.ToShortDateString(), }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + + CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма снятий за период: {info.ReportCashWithdrawal.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + // Параграф с отчётом по переводу денег со счёта на счёт + CreateParagraph(new PdfParagraph { Text = "Отчёт по денежным переводам между счетами", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "3cm", "3cm", "3cm", "4cm", "4cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер операции", "Номер счёта отправителя", "Номер счёта получателя", "Сумма операции", "Дата операции" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var report in info.ReportMoneyTransfer) + { + CreateRow(new PdfRowParameters + { + Texts = new List { report.OperationId.ToString(), report.AccountSenderNumber, report.AccountPayeeNumber, report.SumOperation.ToString(), report.DateComplite.ToShortDateString(), }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + + CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма переводов за период: {info.ReportMoneyTransfer.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + SavePdf(info); + } + + /// Создание pdf-файла + protected abstract void CreatePdf(PdfInfo info); + + /// Создание параграфа с текстом + protected abstract void CreateParagraph(PdfParagraph paragraph); + + /// Создание таблицы + protected abstract void CreateTable(List columns); + + /// Создание и заполнение строки + protected abstract void CreateRow(PdfRowParameters rowParameters); + + /// Сохранение файла + protected abstract void SavePdf(PdfInfo info); + } } diff --git a/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToWord.cs index f7b7e4a..7deb086 100644 --- a/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToWord.cs +++ b/Bank/BankBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -1,4 +1,6 @@ -using BankBusinessLogic.OfficePackage.HelperModels; +using BankBusinessLogic.OfficePackage.HelperEnums; +using BankBusinessLogic.OfficePackage.HelperModels; +using BankDataModels.Enums; using System; using System.Collections.Generic; using System.Linq; @@ -7,18 +9,345 @@ using System.Threading.Tasks; namespace BankBusinessLogic.OfficePackage { - public abstract class AbstractSaveToWord - { - /// Создание doc-файла - protected abstract void CreateWord(WordInfo info); + public abstract class AbstractSaveToWord + { + //метод создания документа + public void CreateDoc(WordInfo info, OfficeOperationEnum operationEnum) + { + if (operationEnum == OfficeOperationEnum.Между_cчетами) + { + CreateMoneyTransferWord(info); + } - /// Создание абзаца с текстом - protected abstract void CreateParagraph(WordParagraph paragraph); + if (operationEnum == OfficeOperationEnum.Пополнение_карт) + { + CreateCreditingWord(info); + } - ///Создание таблицы - protected abstract void CreateTable(WordParagraph paragraph); + if (operationEnum == OfficeOperationEnum.Cнятие_с_карты) + { + CreateDebitingWord(info); + } - /// Сохранение файла - protected abstract void SaveWord(WordInfo info); - } + if (operationEnum == OfficeOperationEnum.Для_кассира) + { + CreateCashierWord(info); + } + } + + private void CreateMoneyTransferWord(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + foreach (var transfer in info.MoneyTransfer) + { + List> rowList = new() + { + new() + { + new("Номер счёта отправителя", new WordTextProperties { Bold = true, Size = "20" } ), + new("Номер счёта получателя", new WordTextProperties { Bold = true, Size = "20" } ), + new("Сумма операции", new WordTextProperties { Bold = true, Size = "20" } ), + new("Дата перевода", new WordTextProperties { Bold = true, Size = "20" } ) + } + }; + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Перевод №" + transfer.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + List<(string, WordTextProperties)> cellList = new() + { + new(transfer.AccountSenderNumber, new WordTextProperties { Size = "20" }), + new(transfer.AccountPayeeNumber, new WordTextProperties { Size = "20" }), + new(transfer.Sum.ToString(), new WordTextProperties { Size = "20"}), + new(transfer.DateTransfer.ToString(), new WordTextProperties { Size = "20"}), + }; + + rowList.Add(cellList); + + CreateTable(new WordParagraph + { + RowTexts = rowList, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + } + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Суммарный объём переводов: " + info.MoneyTransfer.Sum(x => x.Sum).ToString(), + new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + + SaveWord(info); + } + + private void CreateCreditingWord(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + foreach (var crediting in info.Crediting) + { + List> rowList = new() + { + new() + { + new("Номер карты", new WordTextProperties { Bold = true, Size = "24" } ), + new("Сумма пополнения", new WordTextProperties { Bold = true, Size = "24" } ), + new("Дата выполнения", new WordTextProperties { Bold = true, Size = "24" } ) + } + }; + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Пополнение №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + List<(string, WordTextProperties)> cellList = new() + { + new(crediting.CardNumber, new WordTextProperties { Size = "24" }), + new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }), + new(crediting.DateCredit == null ? "В обработке" : crediting.DateCredit.ToString(), new WordTextProperties { Size = "24" }) + }; + + rowList.Add(cellList); + + CreateTable(new WordParagraph + { + RowTexts = rowList, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + } + + //формирование списка поступления по каждой карте + var dict = new Dictionary(); + + foreach (var elem in info.Crediting) + { + if (dict.ContainsKey(elem.CardNumber)) + { + dict[elem.CardNumber] += elem.Sum; + } + else + { + dict[elem.CardNumber] = elem.Sum; + } + } + + foreach (var elem in dict) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Суммарное пополнение на карту №" + elem.Key + ": " + elem.Value.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + private void CreateDebitingWord(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + foreach (var crediting in info.Debiting) + { + List> rowList = new() + { + new() + { + new("Номер карты", new WordTextProperties { Bold = true, Size = "24" } ), + new("Сумма снятия", new WordTextProperties { Bold = true, Size = "24" } ), + new("Дата выполнения", new WordTextProperties { Bold = true, Size = "24" } ) + } + }; + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Снятие №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + List<(string, WordTextProperties)> cellList = new() + { + new(crediting.CardNumber, new WordTextProperties { Size = "24" }), + new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }), + new(crediting.DateDebit == null ? "В обработке" : crediting.DateDebit.ToString(), new WordTextProperties { Size = "24" }) + }; + + rowList.Add(cellList); + + CreateTable(new WordParagraph + { + RowTexts = rowList, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + } + + //формирование списка поступления по каждой карте + var dict = new Dictionary(); + + foreach (var elem in info.Debiting) + { + if (dict.ContainsKey(elem.CardNumber)) + { + dict[elem.CardNumber] += elem.Sum; + } + else + { + dict[elem.CardNumber] = elem.Sum; + } + } + + foreach (var elem in dict) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Суммарное снятие с карты №" + elem.Key + ": " + elem.Value.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + private void CreateCashierWord(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + foreach (var crediting in info.Debiting) + { + List> rowList = new() + { + new() + { + new("Сумма заявки", new WordTextProperties { Bold = true, Size = "24" } ), + new("Дата открытия", new WordTextProperties { Bold = true, Size = "24" } ), + new("Статус", new WordTextProperties { Bold = true, Size = "24" } ) + } + }; + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Заявка №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + List<(string, WordTextProperties)> cellList = new() + { + new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }), + new(crediting.DateDebit.ToString(), new WordTextProperties { Size = "24" }), + new(crediting.Status.ToString(), new WordTextProperties { Size = "24" }) + }; + + rowList.Add(cellList); + + CreateTable(new WordParagraph + { + RowTexts = rowList, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + } + + SaveWord(info); + } + + /// Создание doc-файла + protected abstract void CreateWord(WordInfo info); + + /// Создание абзаца с текстом + protected abstract void CreateParagraph(WordParagraph paragraph); + + /// Создание таблицы + protected abstract void CreateTable(WordParagraph paragraph); + + /// Сохранение файла + protected abstract void SaveWord(WordInfo info); + } } diff --git a/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToExcel.cs index fac7f89..32c8d01 100644 --- a/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToExcel.cs +++ b/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -1,4 +1,9 @@ -using DocumentFormat.OpenXml.Packaging; +using BankBusinessLogic.OfficePackage.HelperEnums; +using BankBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; @@ -9,7 +14,7 @@ using System.Threading.Tasks; namespace BankBusinessLogic.OfficePackage.Implements { // Реализация создания Excel-документа от абстрактного класса - public class SaveToExcel + public class SaveToExcel : AbstractSaveToExcel { private SpreadsheetDocument? _spreadsheetDocument; @@ -17,5 +22,374 @@ namespace BankBusinessLogic.OfficePackage.Implements private Worksheet? _worksheet; - } + // Настройка стилей для файла + private static void CreateStyles(WorkbookPart workbookpart) + { + var sp = workbookpart.AddNewPart(); + sp.Stylesheet = new Stylesheet(); + + // Настройка шрифта простого текста + var fonts = new Fonts() { Count = 2U, KnownFonts = true }; + + var fontUsual = new Font(); + fontUsual.Append(new FontSize() { Val = 12D }); + fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontUsual.Append(new FontName() { Val = "Times New Roman" }); + fontUsual.Append(new FontFamilyNumbering() { Val = 2 }); + fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + // Настройка шрифта заголока + var fontTitle = new Font(); + fontTitle.Append(new Bold()); + fontTitle.Append(new FontSize() { Val = 14D }); + fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontTitle.Append(new FontName() { Val = "Times New Roman" }); + fontTitle.Append(new FontFamilyNumbering() { Val = 2 }); + fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + // Добавление созданных шрифтов + fonts.Append(fontUsual); + fonts.Append(fontTitle); + + // Создание заливки + var fills = new Fills() { Count = 2U }; + + var fill1 = new Fill(); + fill1.Append(new PatternFill() + { + PatternType = PatternValues.None + }); + + var fill2 = new Fill(); + fill2.Append(new PatternFill() + { + PatternType = PatternValues.Gray125 + }); + + fills.Append(fill1); + fills.Append(fill2); + + // Стиль границ ячейки - незакрашенный (для заголовка) и закрашенный + var borders = new Borders() { Count = 2U }; + + var borderNoBorder = new Border(); + borderNoBorder.Append(new LeftBorder()); + borderNoBorder.Append(new RightBorder()); + borderNoBorder.Append(new TopBorder()); + borderNoBorder.Append(new BottomBorder()); + borderNoBorder.Append(new DiagonalBorder()); + + var borderThin = new Border(); + + var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }; + leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var rightBorder = new RightBorder() + { + Style = BorderStyleValues.Thin + }; + + rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var topBorder = new TopBorder() { Style = BorderStyleValues.Thin }; + topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var bottomBorder = new BottomBorder() + { + Style = BorderStyleValues.Thin + }; + + bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + borderThin.Append(leftBorder); + borderThin.Append(rightBorder); + borderThin.Append(topBorder); + borderThin.Append(bottomBorder); + borderThin.Append(new DiagonalBorder()); + + borders.Append(borderNoBorder); + borders.Append(borderThin); + + // Формирование CellFormat из комбинаций шрифтов, заливок и т. д. + var cellStyleFormats = new CellStyleFormats() { Count = 1U }; + + var cellFormatStyle = new CellFormat() + { + NumberFormatId = 0U, + FontId = 0U, + FillId = 0U, + BorderId = 0U + }; + + cellStyleFormats.Append(cellFormatStyle); + + var cellFormats = new CellFormats() { Count = 3U }; + + var cellFormatFont = new CellFormat() + { + NumberFormatId = 0U, + FontId = 0U, + FillId = 0U, + BorderId = 0U, + FormatId = 0U, + ApplyFont = true + }; + + var cellFormatFontAndBorder = new CellFormat() + { + NumberFormatId = 0U, + FontId = 0U, + FillId = 0U, + BorderId = 1U, + FormatId = 0U, + ApplyFont = true, + ApplyBorder = true + }; + + var cellFormatTitle = new CellFormat() + { + NumberFormatId = 0U, + FontId = 1U, + FillId = 0U, + BorderId = 0U, + FormatId = 0U, + Alignment = new Alignment() + { + Vertical = VerticalAlignmentValues.Center, + WrapText = true, + Horizontal = HorizontalAlignmentValues.Center + }, + ApplyFont = true + }; + + // В итоге создали 3 стиля + cellFormats.Append(cellFormatFont); + cellFormats.Append(cellFormatFontAndBorder); + cellFormats.Append(cellFormatTitle); + + var cellStyles = new CellStyles() { Count = 1U }; + + cellStyles.Append(new CellStyle() + { + Name = "Normal", + FormatId = 0U, + BuiltinId = 0U + }); + + var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U }; + + var tableStyles = new TableStyles() + { + Count = 0U, + DefaultTableStyle = "TableStyleMedium2", + DefaultPivotStyle = "PivotStyleLight16" + }; + + var stylesheetExtensionList = new StylesheetExtensionList(); + var stylesheetExtension1 = new StylesheetExtension() + { + Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" + }; + + stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); + stylesheetExtension1.Append(new SlicerStyles() + { + DefaultSlicerStyle = "SlicerStyleLight1" + }); + + var stylesheetExtension2 = new StylesheetExtension() + { + Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" + }; + + stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); + + stylesheetExtension2.Append(new TimelineStyles() + { + DefaultTimelineStyle = "TimeSlicerStyleLight1" + }); + + stylesheetExtensionList.Append(stylesheetExtension1); + stylesheetExtensionList.Append(stylesheetExtension2); + + sp.Stylesheet.Append(fonts); + sp.Stylesheet.Append(fills); + sp.Stylesheet.Append(borders); + sp.Stylesheet.Append(cellStyleFormats); + sp.Stylesheet.Append(cellFormats); + sp.Stylesheet.Append(cellStyles); + sp.Stylesheet.Append(differentialFormats); + sp.Stylesheet.Append(tableStyles); + sp.Stylesheet.Append(stylesheetExtensionList); + } + + // Получение номера стиля (одного из 3-х нами созданных) из типа + private static uint GetStyleValue(ExcelStyleInfoType styleInfo) + { + return styleInfo switch + { + ExcelStyleInfoType.Title => 2U, + ExcelStyleInfoType.TextWithBorder => 1U, + ExcelStyleInfoType.Text => 0U, + _ => 0U, + }; + } + + protected override void CreateExcel(ExcelInfo info) + { + // Создаём документ Excel + _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); + + // Создаем книгу (в ней хранятся листы) + var workbookpart = _spreadsheetDocument.AddWorkbookPart(); + + workbookpart.Workbook = new Workbook(); + + CreateStyles(workbookpart); + + // Получаем/создаем хранилище текстов для книги + _shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType().Any() + ? _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() + : _spreadsheetDocument.WorkbookPart.AddNewPart(); + + // Создаем SharedStringTable, если его нет + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } + + // Создаем лист в книгу + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(new SheetData()); + + // Добавляем лист в книгу + var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); + + var sheet = new Sheet() + { + Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист" + }; + + sheets.Append(sheet); + + _worksheet = worksheetPart.Worksheet; + } + + // Метод вставки в лист книги + protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) + { + if (_worksheet == null || _shareStringPart == null) + { + return; + } + + var sheetData = _worksheet.GetFirstChild(); + + if (sheetData == null) + { + return; + } + + // Ищем строку, либо добавляем ее + Row row; + + if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) + { + row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); + } + else + { + row = new Row() { RowIndex = excelParams.RowIndex }; + sheetData.Append(row); + } + + // Ищем нужную ячейку + Cell cell; + + if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) + { + cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); + } + else + { + // Все ячейки должны быть последовательно друг за другом расположены + // Нужно определить, после какой вставлять + Cell? refCell = null; + + foreach (Cell rowCell in row.Elements()) + { + if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0) + { + refCell = rowCell; + break; + } + } + + var newCell = new Cell() + { + CellReference = excelParams.CellReference + }; + + row.InsertBefore(newCell, refCell); + cell = newCell; + } + + // Вставляем новый текст + _shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text))); + _shareStringPart.SharedStringTable.Save(); + + cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements().Count() - 1).ToString()); + cell.DataType = new EnumValue(CellValues.SharedString); + cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); + } + + // Метод объединения ячеек + protected override void MergeCells(ExcelMergeParameters excelParams) + { + if (_worksheet == null) + { + return; + } + + MergeCells mergeCells; + + if (_worksheet.Elements().Any()) + { + mergeCells = _worksheet.Elements().First(); + } + else + { + mergeCells = new MergeCells(); + + if (_worksheet.Elements().Any()) + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + else + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + } + + var mergeCell = new MergeCell() + { + Reference = new StringValue(excelParams.Merge) + }; + + mergeCells.Append(mergeCell); + } + + protected override void SaveExcel(ExcelInfo info) + { + if (_spreadsheetDocument == null) + { + return; + } + + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Dispose(); + } + } } diff --git a/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToPdf.cs index dc26547..ee6aab1 100644 --- a/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToPdf.cs +++ b/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -1,4 +1,6 @@ -using MigraDoc.DocumentObjectModel; +using BankBusinessLogic.OfficePackage.HelperEnums; +using BankBusinessLogic.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.Tables; using MigraDoc.Rendering; using System; @@ -10,12 +12,120 @@ using System.Threading.Tasks; namespace BankBusinessLogic.OfficePackage.Implements { // Реализация создания Pdf-документа от абстрактного класса - public class SaveToPdf + public class SaveToPdf : AbstractSaveToPdf { private Document? _document; private Section? _section; private Table? _table; - } + + // Преобразование необходимого типа выравнивания в соотвествующее выравнивание в MigraDoc + private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) + { + return type switch + { + PdfParagraphAlignmentType.Center => ParagraphAlignment.Center, + PdfParagraphAlignmentType.Left => ParagraphAlignment.Left, + PdfParagraphAlignmentType.Right => ParagraphAlignment.Right, + _ => ParagraphAlignment.Justify, + }; + } + + // Создание стилей для документа + 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 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); + } + } } diff --git a/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToWord.cs b/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToWord.cs index 8af5380..d4b4566 100644 --- a/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToWord.cs +++ b/Bank/BankBusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -1,4 +1,7 @@ -using DocumentFormat.OpenXml.Packaging; +using BankBusinessLogic.OfficePackage.HelperEnums; +using BankBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; @@ -9,11 +12,219 @@ using System.Threading.Tasks; namespace BankBusinessLogic.OfficePackage.Implements { // Реализация создания Word-документа от абстрактного класса - public class SaveToWord + public class SaveToWord : AbstractSaveToWord { private WordprocessingDocument? _wordDocument; private Body? _docBody; - } + // Получение типа выравнивания + private static JustificationValues GetJustificationValues(WordJustificationType type) + { + // Выравнивание слева будет в том случае, если передаётся неизвестный тип выравнивания + return type switch + { + WordJustificationType.Both => JustificationValues.Both, + WordJustificationType.Center => JustificationValues.Center, + _ => JustificationValues.Left, + }; + } + + // Настройки страницы + private static SectionProperties CreateSectionProperties() + { + var properties = new SectionProperties(); + + // Прописываем портретную ориентацию + var pageSize = new PageSize + { + Orient = PageOrientationValues.Portrait + }; + + properties.AppendChild(pageSize); + + return properties; + } + + // Задание форматирования для абзаца + private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) + { + if (paragraphProperties == null) + { + return null; + } + + var properties = new ParagraphProperties(); + + // Вытаскиваем выравнивание текста + properties.AppendChild(new Justification() + { + Val = GetJustificationValues(paragraphProperties.JustificationType) + }); + + properties.AppendChild(new SpacingBetweenLines + { + LineRule = LineSpacingRuleValues.Auto + }); + + properties.AppendChild(new Indentation()); + + var paragraphMarkRunProperties = new ParagraphMarkRunProperties(); + + if (!string.IsNullOrEmpty(paragraphProperties.Size)) + { + paragraphMarkRunProperties.AppendChild(new FontSize + { + Val = paragraphProperties.Size + }); + } + + properties.AppendChild(paragraphMarkRunProperties); + + return properties; + } + + protected override void CreateWord(WordInfo info) + { + // Создаём документ word + _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); + + // Вытаскиваем главную часть из вордовского документа + MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); + + mainPart.Document = new Document(); + + //Ггенерируем тело основной части документа + _docBody = mainPart.Document.AppendChild(new Body()); + } + + protected override void CreateParagraph(WordParagraph paragraph) + { + // Проверка на то, был ли вызван WordprocessingDocument.Create (создался ли документ) и есть ли вообще параграф для вставки + if (_docBody == null || paragraph == null) + { + return; + } + + var docParagraph = new Paragraph(); + + // Добавляем свойства параграфа + docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + + // Вставляем блоки текста (их называют Run) + foreach (var run in paragraph.Texts) + { + var docRun = new Run(); + var properties = new RunProperties(); + + //Ззадание свойств текста - размер и жирность + properties.AppendChild(new FontSize { Val = run.Item2.Size }); + + if (run.Item2.Bold) + { + properties.AppendChild(new Bold()); + } + + docRun.AppendChild(properties); + + docRun.AppendChild(new Text + { + Text = run.Item1, + Space = SpaceProcessingModeValues.Preserve + }); + + docParagraph.AppendChild(docRun); + } + + _docBody.AppendChild(docParagraph); + } + + // Метод, отвечающий за создание таблицы + protected override void CreateTable(WordParagraph paragraph) + { + if (_docBody == null || paragraph == null) + { + return; + } + + Table table = new Table(); + + var tableProp = new TableProperties(); + + tableProp.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed }); + tableProp.AppendChild(new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 } + )); + tableProp.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto }); + + table.AppendChild(tableProp); + + TableGrid tableGrid = new TableGrid(); + + for (int j = 0; j < paragraph.RowTexts[0].Count; ++j) + { + tableGrid.AppendChild(new GridColumn() { Width = "2500" }); + } + + table.AppendChild(tableGrid); + + for (int i = 0; i < paragraph.RowTexts.Count; ++i) + { + TableRow docRow = new TableRow(); + + for (int j = 0; j < paragraph.RowTexts[i].Count; ++j) + { + var docParagraph = new Paragraph(); + + docParagraph.AppendChild(CreateParagraphProperties(paragraph.RowTexts[i][j].Item2)); + + var docRun = new Run(); + + var properties = new RunProperties(); + + properties.AppendChild(new FontSize { Val = paragraph.RowTexts[i][j].Item2.Size }); + + if (paragraph.RowTexts[i][j].Item2.Bold) + { + properties.AppendChild(new Bold()); + } + + docRun.AppendChild(properties); + + docRun.AppendChild(new Text { Text = paragraph.RowTexts[i][j].Item1, Space = SpaceProcessingModeValues.Preserve }); + + docParagraph.AppendChild(docRun); + TableCell docCell = new TableCell(); + docCell.AppendChild(docParagraph); + docRow.AppendChild(docCell); + } + + table.AppendChild(docRow); + } + + _docBody.AppendChild(table); + } + + // Метод сохранения документа + protected override void SaveWord(WordInfo info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + + // Вставляем информацию по секциям (смотри, что является входным параметром) + _docBody.AppendChild(CreateSectionProperties()); + + // Сохраняем документ + _wordDocument.MainDocumentPart!.Document.Save(); + + _wordDocument.Dispose(); + } + } } diff --git a/Bank/BankContracts/BankContracts.csproj b/Bank/BankContracts/BankContracts.csproj index e6bb86f..9d9c8a3 100644 --- a/Bank/BankContracts/BankContracts.csproj +++ b/Bank/BankContracts/BankContracts.csproj @@ -7,14 +7,13 @@ - + + + - - - - + diff --git a/Bank/BankContracts/ViewModels/Cashier/Diagram/CashierDiagramElementsViewModel.cs b/Bank/BankContracts/ViewModels/Cashier/Diagram/CashierDiagramElementsViewModel.cs new file mode 100644 index 0000000..96ad2ea --- /dev/null +++ b/Bank/BankContracts/ViewModels/Cashier/Diagram/CashierDiagramElementsViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Cashier.Diagram +{ + public class CashierDiagramElementsViewModel + { + public string Name { get; set; } = "Column"; + + public int Value { get; set; } = 0; + } +} diff --git a/Bank/BankContracts/ViewModels/Cashier/Diagram/CashierDiagramViewModel.cs b/Bank/BankContracts/ViewModels/Cashier/Diagram/CashierDiagramViewModel.cs new file mode 100644 index 0000000..0ca2528 --- /dev/null +++ b/Bank/BankContracts/ViewModels/Cashier/Diagram/CashierDiagramViewModel.cs @@ -0,0 +1,16 @@ +using BankContracts.ViewModels.Client.Diagram; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Cashier.Diagram +{ + public class CashierDiagramViewModel + { + public string DiagramName { get; set; } = "Diagram Name"; + + public List Elements { get; set; } = new(); + } +} diff --git a/Bank/BankContracts/ViewModels/Client/Diagram/ClientDiagramElementsViewModel.cs b/Bank/BankContracts/ViewModels/Client/Diagram/ClientDiagramElementsViewModel.cs new file mode 100644 index 0000000..0fd1eba --- /dev/null +++ b/Bank/BankContracts/ViewModels/Client/Diagram/ClientDiagramElementsViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Client.Diagram +{ + public class ClientDiagramElementsViewModel + { + public string Name { get; set; } = "Column"; + + public int Value { get; set; } = 0; + } +} diff --git a/Bank/BankContracts/ViewModels/Client/Diagram/ClientDiagramViewModel.cs b/Bank/BankContracts/ViewModels/Client/Diagram/ClientDiagramViewModel.cs new file mode 100644 index 0000000..3f48785 --- /dev/null +++ b/Bank/BankContracts/ViewModels/Client/Diagram/ClientDiagramViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Client.Diagram +{ + public class ClientDiagramViewModel + { + public string DiagramName { get; set; } = "Diagram Name"; + + public List Elements { get; set; } = new(); + } +} diff --git a/Bank/BankContracts/ViewModels/Client/ViewModels/DebitingViewModel.cs b/Bank/BankContracts/ViewModels/Client/ViewModels/DebitingViewModel.cs index 63a6aec..6a02181 100644 --- a/Bank/BankContracts/ViewModels/Client/ViewModels/DebitingViewModel.cs +++ b/Bank/BankContracts/ViewModels/Client/ViewModels/DebitingViewModel.cs @@ -1,4 +1,5 @@ -using BankDataModels.Models.Client; +using BankDataModels.Enums; +using BankDataModels.Models.Client; using System; using System.Collections.Generic; using System.ComponentModel; @@ -25,5 +26,8 @@ namespace BankContracts.ViewModels.Client.ViewModels [DisplayName("Дата открытия заявки")] public DateTime DateDebit { get; set; } = DateTime.Now; + + [DisplayName("Статус заявки")] + public StatusCard Status { get; set; } } } diff --git a/Bank/BankContracts/ViewModels/Reports/Cashier/ReportCashierAccountsViewModel.cs b/Bank/BankContracts/ViewModels/Reports/Cashier/ReportCashierAccountsViewModel.cs new file mode 100644 index 0000000..b3093fb --- /dev/null +++ b/Bank/BankContracts/ViewModels/Reports/Cashier/ReportCashierAccountsViewModel.cs @@ -0,0 +1,24 @@ +using BankDataModels.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Reports.Cashier +{ + public class ReportCashierAccountsViewModel + { + public int Sum { get; set; } + + public string AccountSenderNumber { get; set; } = "---"; + + public string AccountPayeeNumber { get; set; } = "---"; + + public DateTime DateOperation { get; set; } = DateTime.Now; + + public string CashierSurname { get; set; } = string.Empty; + + public TypeOperationEnum typeOperation { get; set; } + } +} diff --git a/Bank/BankContracts/ViewModels/Reports/Client/CheckboxViewModel.cs b/Bank/BankContracts/ViewModels/Reports/Client/CheckboxViewModel.cs new file mode 100644 index 0000000..d869b3d --- /dev/null +++ b/Bank/BankContracts/ViewModels/Reports/Client/CheckboxViewModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Reports.Client +{ + public class CheckboxViewModel + { + public int Id { get; set; } + + public string LabelName { get; set; } + + public bool IsChecked { get; set; } + } +} diff --git a/Bank/BankContracts/ViewModels/Reports/Client/ReportClientCardsViewModel.cs b/Bank/BankContracts/ViewModels/Reports/Client/ReportClientCardsViewModel.cs new file mode 100644 index 0000000..b46ac91 --- /dev/null +++ b/Bank/BankContracts/ViewModels/Reports/Client/ReportClientCardsViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Reports.Client +{ + public class ReportClientCardsViewModel + { + public List? Cards { get; set; } = new(); + + public List? Operations { get; set; } = new(); + } +} diff --git a/Bank/BankContracts/ViewModels/Reports/FileViewModel.cs b/Bank/BankContracts/ViewModels/Reports/FileViewModel.cs new file mode 100644 index 0000000..8200e54 --- /dev/null +++ b/Bank/BankContracts/ViewModels/Reports/FileViewModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankContracts.ViewModels.Reports +{ + public class FileViewModel + { + public byte[] Bytes { get; set; } = Array.Empty(); + + public int[] Test { get; set; } = Array.Empty(); + + public string StringBytes { get; set; } = string.Empty; + } +} diff --git a/Bank/BankDataModels/Enums/TypeOperationEnum.cs b/Bank/BankDataModels/Enums/TypeOperationEnum.cs new file mode 100644 index 0000000..f0086e1 --- /dev/null +++ b/Bank/BankDataModels/Enums/TypeOperationEnum.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BankDataModels.Enums +{ + public enum TypeOperationEnum + { + Снятие = 1, + + Пополнение = 2, + + Переыод = 3 + } +}