From 79ed7aa78b1c3457dfc1d4fa7f56b6aeea32d33f Mon Sep 17 00:00:00 2001 From: ENDORFIT Date: Wed, 18 Dec 2024 23:57:16 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=963?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FormClientCostRatioReport.Designer.cs | 107 ++++++ .../Forms/FormClientCostRatioReport.cs | 63 ++++ .../Forms/FormClientCostRatioReport.resx | 120 +++++++ .../Forms/FormClientsReport.Designer.cs | 164 +++++++++ .../Scripts/Forms/FormClientsReport.cs | 73 ++++ .../Scripts/Forms/FormClientsReport.resx | 120 +++++++ .../Forms/FormDirectoryReport.Designer.cs | 112 ++++++ .../Scripts/Forms/FormDirectoryReport.cs | 53 +++ .../Scripts/Forms/FormDirectoryReport.resx | 120 +++++++ .../Scripts/Forms/FormOptika.Designer.cs | 31 ++ ProjectOptika/Scripts/Forms/FormOptika.cs | 39 +++ ProjectOptika/Scripts/Reports/ChartReport.cs | 51 +++ ProjectOptika/Scripts/Reports/DocReport.cs | 105 ++++++ ProjectOptika/Scripts/Reports/ExcelBuilder.cs | 318 ++++++++++++++++++ ProjectOptika/Scripts/Reports/PdfBuilder.cs | 83 +++++ ProjectOptika/Scripts/Reports/TableReport.cs | 89 +++++ ProjectOptika/Scripts/Reports/WordBuilder.cs | 94 ++++++ 17 files changed, 1742 insertions(+) create mode 100644 ProjectOptika/Scripts/Forms/FormClientCostRatioReport.Designer.cs create mode 100644 ProjectOptika/Scripts/Forms/FormClientCostRatioReport.cs create mode 100644 ProjectOptika/Scripts/Forms/FormClientCostRatioReport.resx create mode 100644 ProjectOptika/Scripts/Forms/FormClientsReport.Designer.cs create mode 100644 ProjectOptika/Scripts/Forms/FormClientsReport.cs create mode 100644 ProjectOptika/Scripts/Forms/FormClientsReport.resx create mode 100644 ProjectOptika/Scripts/Forms/FormDirectoryReport.Designer.cs create mode 100644 ProjectOptika/Scripts/Forms/FormDirectoryReport.cs create mode 100644 ProjectOptika/Scripts/Forms/FormDirectoryReport.resx create mode 100644 ProjectOptika/Scripts/Reports/ChartReport.cs create mode 100644 ProjectOptika/Scripts/Reports/DocReport.cs create mode 100644 ProjectOptika/Scripts/Reports/ExcelBuilder.cs create mode 100644 ProjectOptika/Scripts/Reports/PdfBuilder.cs create mode 100644 ProjectOptika/Scripts/Reports/TableReport.cs create mode 100644 ProjectOptika/Scripts/Reports/WordBuilder.cs diff --git a/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.Designer.cs b/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.Designer.cs new file mode 100644 index 0000000..e717a5c --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.Designer.cs @@ -0,0 +1,107 @@ +namespace ProjectOptika.Scripts.Forms +{ + partial class FormClientCostRatioReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonSelectFileName = new Button(); + labelFileName = new Label(); + buttonBuild = new Button(); + dateTimePickerStartDate = new DateTimePicker(); + labelStartDate = new Label(); + SuspendLayout(); + // + // buttonSelectFileName + // + buttonSelectFileName.Location = new Point(12, 12); + buttonSelectFileName.Name = "buttonSelectFileName"; + buttonSelectFileName.Size = new Size(94, 29); + buttonSelectFileName.TabIndex = 0; + buttonSelectFileName.Text = "Выбрать"; + buttonSelectFileName.UseVisualStyleBackColor = true; + buttonSelectFileName.Click += ButtonSelectFileName_Click; + // + // labelFileName + // + labelFileName.AutoSize = true; + labelFileName.Location = new Point(134, 16); + labelFileName.Name = "labelFileName"; + labelFileName.Size = new Size(45, 20); + labelFileName.TabIndex = 1; + labelFileName.Text = "Файл"; + // + // buttonBuild + // + buttonBuild.Location = new Point(93, 122); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(129, 29); + buttonBuild.TabIndex = 16; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += ButtonCreate_Click; + // + // dateTimePickerStartDate + // + dateTimePickerStartDate.Location = new Point(148, 68); + dateTimePickerStartDate.Name = "dateTimePickerStartDate"; + dateTimePickerStartDate.Size = new Size(178, 27); + dateTimePickerStartDate.TabIndex = 18; + // + // labelStartDate + // + labelStartDate.AutoSize = true; + labelStartDate.Location = new Point(12, 68); + labelStartDate.Name = "labelStartDate"; + labelStartDate.Size = new Size(44, 20); + labelStartDate.TabIndex = 17; + labelStartDate.Text = "Дата:"; + // + // FormClientCostRatioReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(357, 172); + Controls.Add(dateTimePickerStartDate); + Controls.Add(labelStartDate); + Controls.Add(buttonBuild); + Controls.Add(labelFileName); + Controls.Add(buttonSelectFileName); + Name = "FormClientCostRatioReport"; + Text = "Сформировать учет стоимостей клиентов"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSelectFileName; + private Label labelFileName; + private Button buttonBuild; + private DateTimePicker dateTimePickerStartDate; + private Label labelStartDate; + } +} \ No newline at end of file diff --git a/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.cs b/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.cs new file mode 100644 index 0000000..dcb7eee --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.cs @@ -0,0 +1,63 @@ +using ProjectOptika.Scripts.Reports; +using ProjectOptika.Scripts.Repositories; +using Unity; + +namespace ProjectOptika.Scripts.Forms +{ + public partial class FormClientCostRatioReport : Form + { + private string _fileName = string.Empty; + private readonly IUnityContainer _container; + + public FormClientCostRatioReport(IAccessoriesRepository accessoriesRepository, IUnityContainer container) + { + InitializeComponent(); + + _container = container ?? + throw new ArgumentNullException(nameof(container)); + } + + private void ButtonSelectFileName_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Pdf Files | *.pdf" + }; + if (sfd.ShowDialog() == DialogResult.OK) + { + _fileName = sfd.FileName; + labelFileName.Text = Path.GetFileName(_fileName); + } + } + + private void ButtonCreate_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if + (_container.Resolve().CreateChart(_fileName, dateTimePickerStartDate.Value)) + { + MessageBox.Show("Документ сформирован", + "Формирование документа", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.resx b/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormClientCostRatioReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectOptika/Scripts/Forms/FormClientsReport.Designer.cs b/ProjectOptika/Scripts/Forms/FormClientsReport.Designer.cs new file mode 100644 index 0000000..a63f864 --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormClientsReport.Designer.cs @@ -0,0 +1,164 @@ +namespace ProjectOptika.Scripts.Forms +{ + partial class FormClientsReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + buttonSelectPathFile = new Button(); + textBoxFilePath = new TextBox(); + labelFilePath = new Label(); + comboBoxEmployees = new ComboBox(); + labelEmployees = new Label(); + labelStartDate = new Label(); + labelEndDate = new Label(); + dateTimePickerStartDate = new DateTimePicker(); + dateTimePickerEndDate = new DateTimePicker(); + buttonMakeReport = new Button(); + SuspendLayout(); + // + // buttonSelectPathFile + // + buttonSelectPathFile.Location = new Point(261, 14); + buttonSelectPathFile.Name = "buttonSelectPathFile"; + buttonSelectPathFile.Size = new Size(25, 29); + buttonSelectPathFile.TabIndex = 0; + buttonSelectPathFile.Text = "..."; + buttonSelectPathFile.UseVisualStyleBackColor = true; + buttonSelectPathFile.Click += ButtonSelectPathFile_Click; + // + // textBoxFilePath + // + textBoxFilePath.Location = new Point(130, 16); + textBoxFilePath.Name = "textBoxFilePath"; + textBoxFilePath.ReadOnly = true; + textBoxFilePath.Size = new Size(125, 27); + textBoxFilePath.TabIndex = 1; + // + // labelFilePath + // + labelFilePath.AutoSize = true; + labelFilePath.Location = new Point(12, 19); + labelFilePath.Name = "labelFilePath"; + labelFilePath.Size = new Size(112, 20); + labelFilePath.TabIndex = 2; + labelFilePath.Text = "Путь до файла:"; + // + // comboBoxEmployees + // + comboBoxEmployees.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxEmployees.FormattingEnabled = true; + comboBoxEmployees.Location = new Point(130, 78); + comboBoxEmployees.Name = "comboBoxEmployees"; + comboBoxEmployees.Size = new Size(156, 28); + comboBoxEmployees.TabIndex = 3; + // + // labelEmployees + // + labelEmployees.AutoSize = true; + labelEmployees.Location = new Point(12, 81); + labelEmployees.Name = "labelEmployees"; + labelEmployees.Size = new Size(82, 20); + labelEmployees.TabIndex = 4; + labelEmployees.Text = "Сотрудник"; + // + // labelStartDate + // + labelStartDate.AutoSize = true; + labelStartDate.Location = new Point(12, 144); + labelStartDate.Name = "labelStartDate"; + labelStartDate.Size = new Size(97, 20); + labelStartDate.TabIndex = 5; + labelStartDate.Text = "Дата начала:"; + // + // labelEndDate + // + labelEndDate.AutoSize = true; + labelEndDate.Location = new Point(12, 209); + labelEndDate.Name = "labelEndDate"; + labelEndDate.Size = new Size(90, 20); + labelEndDate.TabIndex = 6; + labelEndDate.Text = "Дата конца:"; + // + // dateTimePickerStartDate + // + dateTimePickerStartDate.Location = new Point(130, 144); + dateTimePickerStartDate.Name = "dateTimePickerStartDate"; + dateTimePickerStartDate.Size = new Size(156, 27); + dateTimePickerStartDate.TabIndex = 7; + // + // dateTimePickerEndDate + // + dateTimePickerEndDate.Location = new Point(130, 204); + dateTimePickerEndDate.Name = "dateTimePickerEndDate"; + dateTimePickerEndDate.Size = new Size(156, 27); + dateTimePickerEndDate.TabIndex = 8; + // + // buttonMakeReport + // + buttonMakeReport.Location = new Point(64, 265); + buttonMakeReport.Name = "buttonMakeReport"; + buttonMakeReport.Size = new Size(136, 29); + buttonMakeReport.TabIndex = 9; + buttonMakeReport.Text = "Сформировать"; + buttonMakeReport.UseVisualStyleBackColor = true; + buttonMakeReport.Click += ButtonMakeReport_Click; + // + // FormClientsReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(311, 323); + Controls.Add(buttonMakeReport); + Controls.Add(dateTimePickerEndDate); + Controls.Add(dateTimePickerStartDate); + Controls.Add(labelEndDate); + Controls.Add(labelStartDate); + Controls.Add(labelEmployees); + Controls.Add(comboBoxEmployees); + Controls.Add(labelFilePath); + Controls.Add(textBoxFilePath); + Controls.Add(buttonSelectPathFile); + Name = "FormClientsReport"; + Text = "Отчет по клиентам"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonSelectPathFile; + private TextBox textBoxFilePath; + private Label labelFilePath; + private ComboBox comboBoxEmployees; + private Label labelEmployees; + private Label labelStartDate; + private Label labelEndDate; + private DateTimePicker dateTimePickerStartDate; + private DateTimePicker dateTimePickerEndDate; + private Button buttonMakeReport; + } +} \ No newline at end of file diff --git a/ProjectOptika/Scripts/Forms/FormClientsReport.cs b/ProjectOptika/Scripts/Forms/FormClientsReport.cs new file mode 100644 index 0000000..5e3b2a6 --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormClientsReport.cs @@ -0,0 +1,73 @@ +using ProjectOptika.Scripts.Reports; +using ProjectOptika.Scripts.Repositories; +using Unity; + +namespace ProjectOptika.Scripts.Forms +{ + public partial class FormClientsReport : Form + { + private readonly IUnityContainer _container; + public FormClientsReport(IUnityContainer container, IEmployeeRepository employeeRepository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + + comboBoxEmployees.DataSource = employeeRepository.GetEmployees(); + comboBoxEmployees.DisplayMember = "Surname"; + comboBoxEmployees.ValueMember = "ID"; + } + + private void ButtonSelectPathFile_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Excel Files | *.xlsx" + }; + if (sfd.ShowDialog() != DialogResult.OK) + { + return; + } + textBoxFilePath.Text = sfd.FileName; + } + + private void ButtonMakeReport_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(textBoxFilePath.Text)) + { + throw new Exception("Отсутствует имя файла для отчета"); + } + if (comboBoxEmployees.SelectedIndex < 0) + { + throw new Exception("Не выбран доктор"); + } + if (dateTimePickerEndDate.Value <= dateTimePickerStartDate.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + if + (_container.Resolve().CreateTable(textBoxFilePath.Text, + (int)comboBoxEmployees.SelectedValue!, + dateTimePickerStartDate.Value, dateTimePickerEndDate.Value)) + { + MessageBox.Show("Документ сформирован", + "Формирование документа", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании очета", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/ProjectOptika/Scripts/Forms/FormClientsReport.resx b/ProjectOptika/Scripts/Forms/FormClientsReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormClientsReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectOptika/Scripts/Forms/FormDirectoryReport.Designer.cs b/ProjectOptika/Scripts/Forms/FormDirectoryReport.Designer.cs new file mode 100644 index 0000000..31ba57b --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormDirectoryReport.Designer.cs @@ -0,0 +1,112 @@ +namespace ProjectOptika.Scripts.Forms +{ + partial class FormDirectoryReport + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + checkBoxAccessories = new CheckBox(); + checkBoxEmplyees = new CheckBox(); + checkBoxSpecification = new CheckBox(); + checkBoxClients = new CheckBox(); + buttonBuild = new Button(); + SuspendLayout(); + // + // checkBoxAccessories + // + checkBoxAccessories.AutoSize = true; + checkBoxAccessories.Location = new Point(23, 26); + checkBoxAccessories.Name = "checkBoxAccessories"; + checkBoxAccessories.Size = new Size(112, 24); + checkBoxAccessories.TabIndex = 0; + checkBoxAccessories.Text = "Аксессуары"; + checkBoxAccessories.UseVisualStyleBackColor = true; + // + // checkBoxEmplyees + // + checkBoxEmplyees.AutoSize = true; + checkBoxEmplyees.Location = new Point(23, 78); + checkBoxEmplyees.Name = "checkBoxEmplyees"; + checkBoxEmplyees.Size = new Size(113, 24); + checkBoxEmplyees.TabIndex = 1; + checkBoxEmplyees.Text = "Сотрудники"; + checkBoxEmplyees.UseVisualStyleBackColor = true; + // + // checkBoxSpecification + // + checkBoxSpecification.AutoSize = true; + checkBoxSpecification.Location = new Point(23, 126); + checkBoxSpecification.Name = "checkBoxSpecification"; + checkBoxSpecification.Size = new Size(142, 24); + checkBoxSpecification.TabIndex = 2; + checkBoxSpecification.Text = "Характеристики"; + checkBoxSpecification.UseVisualStyleBackColor = true; + // + // checkBoxClients + // + checkBoxClients.AutoSize = true; + checkBoxClients.Location = new Point(23, 174); + checkBoxClients.Name = "checkBoxClients"; + checkBoxClients.Size = new Size(91, 24); + checkBoxClients.TabIndex = 3; + checkBoxClients.Text = "Клиенты"; + checkBoxClients.UseVisualStyleBackColor = true; + // + // buttonBuild + // + buttonBuild.Location = new Point(88, 223); + buttonBuild.Name = "buttonBuild"; + buttonBuild.Size = new Size(129, 29); + buttonBuild.TabIndex = 4; + buttonBuild.Text = "Сформировать"; + buttonBuild.UseVisualStyleBackColor = true; + buttonBuild.Click += ButtonBuild_Click; + // + // FormDirectoryReport + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(308, 276); + Controls.Add(buttonBuild); + Controls.Add(checkBoxClients); + Controls.Add(checkBoxSpecification); + Controls.Add(checkBoxEmplyees); + Controls.Add(checkBoxAccessories); + Name = "FormDirectoryReport"; + Text = "Документ со справочниками"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox checkBoxAccessories; + private CheckBox checkBoxEmplyees; + private CheckBox checkBoxSpecification; + private CheckBox checkBoxClients; + private Button buttonBuild; + } +} \ No newline at end of file diff --git a/ProjectOptika/Scripts/Forms/FormDirectoryReport.cs b/ProjectOptika/Scripts/Forms/FormDirectoryReport.cs new file mode 100644 index 0000000..25367a6 --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormDirectoryReport.cs @@ -0,0 +1,53 @@ +using ProjectOptika.Scripts.Reports; +using Unity; + +namespace ProjectOptika.Scripts.Forms +{ + public partial class FormDirectoryReport : Form + { + private readonly IUnityContainer _container; + public FormDirectoryReport(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? + throw new ArgumentNullException(nameof(container)); + + } + + private void ButtonBuild_Click(object sender, EventArgs e) + { + try + { + if (!checkBoxAccessories.Checked && + !checkBoxClients.Checked && !checkBoxEmplyees.Checked && !checkBoxSpecification.Checked) + { + throw new Exception("Не выбран ни один справочник для выгрузки"); + } + var sfd = new SaveFileDialog() + { + Filter = "Docx Files | *.docx" + }; + if (sfd.ShowDialog() != DialogResult.OK) + { + throw new Exception("Не выбран файла для отчета"); + } + if + (_container.Resolve().CreateDoc(sfd.FileName, checkBoxAccessories.Checked, + checkBoxSpecification.Checked, checkBoxEmplyees.Checked, checkBoxClients.Checked)) + { + MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + } +} diff --git a/ProjectOptika/Scripts/Forms/FormDirectoryReport.resx b/ProjectOptika/Scripts/Forms/FormDirectoryReport.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/ProjectOptika/Scripts/Forms/FormDirectoryReport.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ProjectOptika/Scripts/Forms/FormOptika.Designer.cs b/ProjectOptika/Scripts/Forms/FormOptika.Designer.cs index 221e767..dd9278b 100644 --- a/ProjectOptika/Scripts/Forms/FormOptika.Designer.cs +++ b/ProjectOptika/Scripts/Forms/FormOptika.Designer.cs @@ -37,6 +37,9 @@ операцииToolStripMenuItem = new ToolStripMenuItem(); заказToolStripMenuItem = new ToolStripMenuItem(); отчетToolStripMenuItem = new ToolStripMenuItem(); + directoryReportToolStripMenuItem = new ToolStripMenuItem(); + productRatioToolStripMenuItem = new ToolStripMenuItem(); + clientsReportToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); SuspendLayout(); // @@ -101,10 +104,35 @@ // // отчетToolStripMenuItem // + отчетToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, productRatioToolStripMenuItem, clientsReportToolStripMenuItem }); отчетToolStripMenuItem.Name = "отчетToolStripMenuItem"; отчетToolStripMenuItem.Size = new Size(73, 24); отчетToolStripMenuItem.Text = "Отчеты"; // + // directoryReportToolStripMenuItem + // + directoryReportToolStripMenuItem.Name = "directoryReportToolStripMenuItem"; + directoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + directoryReportToolStripMenuItem.Size = new Size(350, 26); + directoryReportToolStripMenuItem.Text = "Документ со справочниками"; + directoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click; + // + // productRatioToolStripMenuItem + // + productRatioToolStripMenuItem.Name = "productRatioToolStripMenuItem"; + productRatioToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + productRatioToolStripMenuItem.Size = new Size(350, 26); + productRatioToolStripMenuItem.Text = "Сформировать учет оплат"; + productRatioToolStripMenuItem.Click += ProductRatioToolStripMenuItem_Click; + // + // clientsReportToolStripMenuItem + // + clientsReportToolStripMenuItem.Name = "clientsReportToolStripMenuItem"; + clientsReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + clientsReportToolStripMenuItem.Size = new Size(350, 26); + clientsReportToolStripMenuItem.Text = "Отчет по клиентам"; + clientsReportToolStripMenuItem.Click += ClientsReportToolStripMenuItem_Click; + // // FormOptika // AutoScaleDimensions = new SizeF(8F, 20F); @@ -134,5 +162,8 @@ private ToolStripMenuItem характеристикиToolStripMenuItem; private ToolStripMenuItem сотрудникToolStripMenuItem; private ToolStripMenuItem клиентToolStripMenuItem; + private ToolStripMenuItem directoryReportToolStripMenuItem; + private ToolStripMenuItem productRatioToolStripMenuItem; + private ToolStripMenuItem clientsReportToolStripMenuItem; } } diff --git a/ProjectOptika/Scripts/Forms/FormOptika.cs b/ProjectOptika/Scripts/Forms/FormOptika.cs index c501912..42e0132 100644 --- a/ProjectOptika/Scripts/Forms/FormOptika.cs +++ b/ProjectOptika/Scripts/Forms/FormOptika.cs @@ -74,5 +74,44 @@ namespace ProjectOptika MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } + + private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ProductRatioToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ClientsReportToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, " ", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } } diff --git a/ProjectOptika/Scripts/Reports/ChartReport.cs b/ProjectOptika/Scripts/Reports/ChartReport.cs new file mode 100644 index 0000000..9c7c825 --- /dev/null +++ b/ProjectOptika/Scripts/Reports/ChartReport.cs @@ -0,0 +1,51 @@ +using Microsoft.Extensions.Logging; +using ProjectOptika.Scripts.Repositories; + +namespace ProjectOptika.Scripts.Reports +{ + internal class ChartReport + { + private readonly IOrderRepository _orderRepository; + private readonly ILogger _logger; + public ChartReport(IOrderRepository orderRepository, + ILogger logger) + { + _orderRepository = orderRepository ?? + throw new ArgumentNullException(nameof(orderRepository)); + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + new PdfBuilder(filePath) + .AddHeader("Учет оплат клиентов") + .AddPieChart($"Оплаты клиентов", GetData(dateTime)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + private List<(string Caption, double Value)> GetData(DateTime dateTime) + { + var orders = _orderRepository.GetOrders() + .Where(x => x.OrderDate.Date == dateTime.Date) + .ToList(); + + var totalCosts = orders.Count; + + return orders + .GroupBy(x => x.ClientID, (key, group) => new { + ClientID = key, + Count = group.Sum(x => x.TotalCost) + }) + .Select(x => (x.ClientID.ToString(), (double)x.Count / totalCosts * 100)) + .ToList(); + } + } +} diff --git a/ProjectOptika/Scripts/Reports/DocReport.cs b/ProjectOptika/Scripts/Reports/DocReport.cs new file mode 100644 index 0000000..185f608 --- /dev/null +++ b/ProjectOptika/Scripts/Reports/DocReport.cs @@ -0,0 +1,105 @@ +using Microsoft.Extensions.Logging; +using ProjectOptika.Scripts.Repositories; + +namespace ProjectOptika.Scripts.Reports +{ + internal class DocReport + { + private readonly IAccessoriesRepository _accessoriesRepository; + private readonly IClientRepositiory _clientRepositiory; + private readonly IEmployeeRepository _employeeRepository; + private readonly ISpecificationsRepository _specificationsRepository; + private readonly ILogger _logger; + public DocReport(IAccessoriesRepository accessoriesRepository, IClientRepositiory clientRepositiory, IEmployeeRepository employeeRepository, ISpecificationsRepository specificationsRepository, + ILogger logger) + { + _accessoriesRepository = accessoriesRepository ?? + throw new ArgumentNullException(nameof(accessoriesRepository)); + + _clientRepositiory = clientRepositiory ?? + throw new ArgumentNullException(nameof(clientRepositiory)); + + _employeeRepository = employeeRepository ?? + throw new ArgumentNullException(nameof(employeeRepository)); + + _specificationsRepository = specificationsRepository ?? + throw new ArgumentNullException(nameof(specificationsRepository)); + + _logger = logger ?? + throw new ArgumentNullException(nameof(logger)); + } + public bool CreateDoc(string filePath, bool includeAccessories, bool includeSpecification, + bool includeEmployees, bool includeClients) + { + try + { + var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками"); + if (includeAccessories) + { + builder.AddParagraph("Аксессуары") + .AddTable([2400, 2400, 2400, 1200, 1200, 1200, 2400], + GetAccessories()); + } + if (includeSpecification) + { + builder.AddParagraph("Характеристики") + .AddTable([1200, 1200, 2400, 1200, 1200, 2400], GetSpecification()); + } + if (includeEmployees) + { + builder.AddParagraph("Сотрудники") + .AddTable([2400, 2400, 2400, 2400], GetEmploeyees()); + } + if (includeClients) + { + builder.AddParagraph("Клиент") + .AddTable([2400, 2400, 2400, 2400, 2400], GetClients()); + } + builder.Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + private List GetAccessories() + { + return [ + ["Название", "Бренд", "Стоимость", "Наличие в магазине", "Наличие на складе", "Дата доставки", "Тип"], + .. _accessoriesRepository.GetAccessories() + .Select(x => new string[] { x.Name, x.Brand, x.Cost.ToString(), x.StockAvailability.ToString(), x.AvailabilityStore.ToString(), x.DeliveryDate.ToString(), x.CategoryName.ToString() }), + ]; + } + private List GetSpecification() + { + return [ + ["ID аксессуара", "Материал", "Астигматизм", "Диоптрийность", "Страна изготовителя", "Время доставки"], + .. _specificationsRepository + .GetSpecifications() + .Select(x => new string[] { x.AccessoriesID.ToString(), x.Material, x.Astigmatism, x.Dioptericity, x.OriginCountry, x.TimeProduction.ToString()}), + ]; + } + private List GetEmploeyees() + { + return [ + ["Имя", "Отчество", "Фамилия", "Должность"], + .. _employeeRepository + .GetEmployees() + .Select(x => new string[] { x.FirstName, x.SecondName, x.Surname, x.PositionEmployee.ToString() }), + ]; + } + + private List GetClients() + { + return [ + ["Имя", "Отчество", "Фамилия", "Номер телефона", "Тип клиента"], + .. _clientRepositiory + .GetClients() + .Select(x => new string[] { x.FirstName, x.SecondName, x.Surname, x.PhoneNumber, x.ClientType.ToString() }), + ]; + } + + } +} diff --git a/ProjectOptika/Scripts/Reports/ExcelBuilder.cs b/ProjectOptika/Scripts/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..034c96f --- /dev/null +++ b/ProjectOptika/Scripts/Reports/ExcelBuilder.cs @@ -0,0 +1,318 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; + + +namespace ProjectOptika.Scripts.Reports +{ + internal class ExcelBuilder + { + private readonly string _filePath; + private readonly SheetData _sheetData; + private readonly MergeCells _mergeCells; + private readonly Columns _columns; + private uint _rowIndex = 0; + + public ExcelBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _sheetData = new SheetData(); + _mergeCells = new MergeCells(); + _columns = new Columns(); + _rowIndex = 1; + } + + public ExcelBuilder AddHeader(string header, int startIndex, int count) + { + CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithBorders); + for (int i = startIndex + 1; i < startIndex + count; ++i) + { + CreateCell(i, _rowIndex, "", StyleIndex.BoldTextWithBorders); + } + _mergeCells.Append(new MergeCell() + { + Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}") + }); + _rowIndex++; + return this; + } + + public ExcelBuilder AddParagraph(string text, int columnIndex) + { + CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder); + return this; + } + + public ExcelBuilder AddTable(int[] columnsWidths, List data) + { + if (columnsWidths == null || columnsWidths.Length == 0) + { + throw new ArgumentNullException(nameof(columnsWidths)); + } + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + if (data.Any(x => x.Length != columnsWidths.Length)) + { + throw new InvalidOperationException("widths.Length != data.Length"); + } + + uint counter = 1; + int coef = 2; + _columns.Append(columnsWidths.Select(x => new Column + { + Min = counter, + Max = counter++, + Width = x * coef, + CustomWidth = true + })); + + for (var j = 0; j < data.First().Length; ++j) + { + CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorders); + } + _rowIndex++; + + for (var i = 1; i < data.Count - 1; ++i) + { + for (var j = 0; j < data[i].Length; ++j) + { + CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorders); + } + _rowIndex++; + } + + for (var j = 0; j < data.Last().Length; ++j) + { + CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorders); + } + _rowIndex++; + + return this; + } + + public void Build() + { + using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook); + var workbookpart = spreadsheetDocument.AddWorkbookPart(); + GenerateStyle(workbookpart); + workbookpart.Workbook = new Workbook(); + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(); + + if (_columns.HasChildren) + { + worksheetPart.Worksheet.Append(_columns); + } + + worksheetPart.Worksheet.Append(_sheetData); + + var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист 1" + }; + sheets.Append(sheet); + + if (_mergeCells.HasChildren) + { + worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements().First()); + } + } + + private static void GenerateStyle(WorkbookPart workbookPart) + { + var workbookStylesPart = workbookPart.AddNewPart(); + workbookStylesPart.Stylesheet = new Stylesheet(); + + var fonts = new Fonts() + { + Count = 2, + KnownFonts = BooleanValue.FromBoolean(true) + }; + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new EnumValue(FontSchemeValues.Minor) + } + }); + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + FontScheme = new FontScheme() + { + Val = new EnumValue(FontSchemeValues.Minor) + }, + Bold = new Bold() + }); + + workbookStylesPart.Stylesheet.Append(fonts); + + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill() + { + PatternType = new EnumValue(PatternValues.None) + } + }); + workbookStylesPart.Stylesheet.Append(fills); + + var borders = new Borders() { Count = 2 }; + borders.Append(new Border + { + LeftBorder = new LeftBorder(), + RightBorder = new RightBorder(), + TopBorder = new TopBorder(), + BottomBorder = new BottomBorder(), + DiagonalBorder = new DiagonalBorder() + }); + borders.Append(new Border + { + LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }, + RightBorder = new RightBorder() { Style = BorderStyleValues.Thin }, + TopBorder = new TopBorder() { Style = BorderStyleValues.Thin }, + BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }, + DiagonalBorder = new DiagonalBorder() + }); + workbookStylesPart.Stylesheet.Append(borders); + + var cellFormats = new CellFormats() { Count = 4 }; + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 0, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 0, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + cellFormats.Append(new CellFormat + { + NumberFormatId = 0, + FormatId = 0, + FontId = 1, + BorderId = 1, + FillId = 0, + Alignment = new Alignment() + { + Horizontal = HorizontalAlignmentValues.Left, + Vertical = VerticalAlignmentValues.Center, + WrapText = true + } + }); + workbookStylesPart.Stylesheet.Append(cellFormats); + } + + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + SimpleTextWithBorders = 1, + BoldTextWithoutBorders = 2, + BoldTextWithBorders = 3 + } + + private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex) + { + var columnName = GetExcelColumnName(columnIndex); + var cellReference = columnName + rowIndex; + var row = _sheetData.Elements().FirstOrDefault(r => r.RowIndex == rowIndex); + if (row == null) + { + row = new Row() { RowIndex = rowIndex }; + _sheetData.Append(row); + } + + var newCell = row.Elements() + .FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex); + if (newCell == null) + { + Cell? refCell = null; + foreach (Cell cell in row.Elements()) + { + if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length) + { + if (string.Compare(cell.CellReference.Value, cellReference, true) > 0) + { + refCell = cell; + break; + } + } + } + newCell = new Cell() { CellReference = cellReference }; + row.InsertBefore(newCell, refCell); + } + + newCell.CellValue = new CellValue(text); + newCell.DataType = CellValues.String; + newCell.StyleIndex = (uint)styleIndex; + } + + private static string GetExcelColumnName(int columnNumber) + { + columnNumber += 1; + int dividend = columnNumber; + string columnName = string.Empty; + int modulo; + + while (dividend > 0) + { + modulo = (dividend - 1) % 26; + columnName = Convert.ToChar(65 + modulo).ToString() + columnName; + dividend = (dividend - modulo) / 26; + } + + return columnName; + } + } +} diff --git a/ProjectOptika/Scripts/Reports/PdfBuilder.cs b/ProjectOptika/Scripts/Reports/PdfBuilder.cs new file mode 100644 index 0000000..e08a7db --- /dev/null +++ b/ProjectOptika/Scripts/Reports/PdfBuilder.cs @@ -0,0 +1,83 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.Rendering; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MigraDoc.DocumentObjectModel.Shapes.Charts; + +namespace ProjectOptika.Scripts.Reports +{ + internal class PdfBuilder + { + private readonly string _filePath; + private readonly Document _document; + + public PdfBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _document = new Document(); + DefineStyles(); + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + + public PdfBuilder AddHeader(string header) + { + _document.AddSection().AddParagraph(header, "NormalBold"); + return this; + } + + public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data) + { + if (data == null || data.Count == 0) + { + return this; + } + + var chart = new Chart(ChartType.Pie2D); + var series = chart.SeriesCollection.AddSeries(); + series.Add(data.Select(x => x.Value).ToArray()); + var xseries = chart.XValues.AddXSeries(); + xseries.Add(data.Select(x => x.Caption).ToArray()); + chart.DataLabel.Type = DataLabelType.Percent; + chart.DataLabel.Position = DataLabelPosition.OutsideEnd; + chart.Width = Unit.FromCentimeter(16); + chart.Height = Unit.FromCentimeter(12); + chart.TopArea.AddParagraph(title); + chart.XAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.MajorTickMark = TickMarkType.Outside; + chart.YAxis.HasMajorGridlines = true; + chart.PlotArea.LineFormat.Width = 1; + chart.PlotArea.LineFormat.Visible = true; + chart.TopArea.AddLegend(); + _document.LastSection.Add(chart); + return this; + } + + public void Build() + { + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(_filePath); + } + + private void DefineStyles() + { + // Создаем стиль для заголовка (жирный) + var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal"); + headerStyle.Font.Bold = true; + } + } +} diff --git a/ProjectOptika/Scripts/Reports/TableReport.cs b/ProjectOptika/Scripts/Reports/TableReport.cs new file mode 100644 index 0000000..1fcbd92 --- /dev/null +++ b/ProjectOptika/Scripts/Reports/TableReport.cs @@ -0,0 +1,89 @@ +using Microsoft.Extensions.Logging; +using ProjectOptika.Scripts.Repositories; + +namespace ProjectOptika.Scripts.Reports +{ + internal class TableReport + { + private readonly IOrderRepository _orderRepository; + private readonly IEmployeeRepository _employeeRepository; + private readonly IClientRepositiory _clientRepositiory; + + private readonly ILogger _logger; + + internal static readonly string[] item = ["Дата", "Сотрудник", "Общее количество клиентов"]; + + public TableReport(IOrderRepository orderRepository, IClientRepositiory clientRepositiory, IEmployeeRepository employeeRepository, ILogger logger) + { + _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); + _clientRepositiory = clientRepositiory ?? throw new ArgumentNullException(nameof(clientRepositiory)); + _employeeRepository = employeeRepository ?? throw new ArgumentNullException(nameof(employeeRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateTable(string filePath, int emplyeeID, DateTime startDate, DateTime endDate) + { + try + { + new ExcelBuilder(filePath) + .AddHeader("Сводка по заказам", 0, 4) + .AddParagraph("за период", 0) + .AddTable([15, 20, 25], GetData(emplyeeID, startDate, endDate)) + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при формировании документа"); + return false; + } + } + + private List GetData(int emplyeeID, DateTime startDate, DateTime endDate) + { + var orders = _orderRepository.GetOrders(startDate, endDate); + var employees = _employeeRepository.GetEmployees(); + var employeesNames = _employeeRepository.GetEmployees().ToDictionary(d => d.ID, d => d.Surname); + var clientsNames = _clientRepositiory.GetClients().ToList(); + + var data = orders + .Join(employees, r => r.EmployeeID, p => p.ID, (r, p) => new + { + Date = r.OrderDate, + EmployeeID = p.ID, + ClientID = r.ClientID, + TotalCost = r.TotalCost + }) + .Where(x => x.EmployeeID == emplyeeID) + .OrderBy(x => x.Date) + .GroupBy(x => x.Date) + .Select(g => new + { + Date = g.Key, + Totals = g.Count() + }); + + var result = new List { item }; + Random r = new Random(); + foreach (var entry in data) + { + result.Add(new string[] + { + entry.Date.ToString("dd.MM.yyyy"), + employeesNames.ContainsKey(emplyeeID) ? employeesNames[emplyeeID] : string.Empty, + entry.Totals.ToString(), + }); + } + + var totalPatients = data.Sum(x => x.Totals); + result.Add(new string[] + { + "Всего", + "", + totalPatients.ToString() + }); + + return result; + } + } +} diff --git a/ProjectOptika/Scripts/Reports/WordBuilder.cs b/ProjectOptika/Scripts/Reports/WordBuilder.cs new file mode 100644 index 0000000..b751ee3 --- /dev/null +++ b/ProjectOptika/Scripts/Reports/WordBuilder.cs @@ -0,0 +1,94 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using DocumentFormat.OpenXml; + +namespace ProjectOptika.Scripts.Reports +{ + internal class WordBuilder + { + private readonly string _filePath; + private readonly Document _document; + private readonly Body _body; + public WordBuilder(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + _filePath = filePath; + _document = new Document(); + _body = _document.AppendChild(new Body()); + } + public WordBuilder AddHeader(string header) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + // прописать настройки под жирный текст + run.RunProperties = new RunProperties(new Bold()); + run.AppendChild(new Text(header)); + return this; + } + public WordBuilder AddParagraph(string text) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new Text(text)); + return this; + } + public WordBuilder AddTable(int[] widths, List data) + { + if (widths == null || widths.Length == 0) + { + throw new ArgumentNullException(nameof(widths)); + } + + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + + if (data.Any(x => x.Length != widths.Length)) + { + throw new InvalidOperationException("widths.Length != data.Length"); + } + + var table = new Table(); + table.AppendChild(new TableProperties( + new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 12 } + ) + )); + + // Заголовок + var tr = new TableRow(); + for (var j = 0; j < widths.Length; ++j) + { + tr.Append(new TableCell( + new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }), + new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j]))))); + } + table.Append(tr); + + // Данные + table.Append(data.Skip(1).Select(x => + new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y)))))))); + _body.Append(table); + return this; + } + public void Build() + { + using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document); + var mainPart = wordDocument.AddMainDocumentPart(); + mainPart.Document = _document; + } + } +}