From df70bb6e56d8b6c3e75508d170f4482495bc7bfe Mon Sep 17 00:00:00 2001 From: DelphyAlmond Date: Sat, 21 Dec 2024 20:20:04 +0400 Subject: [PATCH] 4(3/1). Only Docx & Pdf reports done, Excel remains --- .../AdditionalForms/FullReportsF.Designer.cs | 104 +++++++ .../LDBproj/AdditionalForms/FullReportsF.cs | 49 +++ ...erRegistrations.resx => FullReportsF.resx} | 0 .../OrderRegistrations.Designer.cs | 112 ------- .../AdditionalForms/OrderRegistrations.cs | 83 ----- .../AdditionalForms/RegOrder.Designer.cs | 200 ------------ .../LDBproj/AdditionalForms/RegOrder.cs | 66 ---- .../AdditionalForms/UpdReportF.Designer.cs | 107 +++++++ .../LDBproj/AdditionalForms/UpdReportF.cs | 55 ++++ .../{RegOrder.resx => UpdReportF.resx} | 6 - .../LDBproj/DBScript/TextCommands.txt | 201 ------------ .../LDBproj/Entities/TemprOrderReg.cs | 20 ++ LibraryDBproject/LDBproj/LDBproject.csproj | 3 + LibraryDBproject/LDBproj/MainForm.Designer.cs | 36 ++- LibraryDBproject/LDBproj/MainForm.cs | 41 ++- .../LDBproj/Reports/ChartReport.cs | 56 ++++ LibraryDBproject/LDBproj/Reports/DocReport.cs | 75 +++++ .../LDBproj/Reports/ExcelBuilder.cs | 285 ++++++++++++++++++ .../LDBproj/Reports/PdfBuilder.cs | 88 ++++++ .../LDBproj/Reports/WordBuilder.cs | 99 ++++++ .../Repositories/Implementations/OrderR.cs | 1 - 21 files changed, 1016 insertions(+), 671 deletions(-) create mode 100644 LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.Designer.cs create mode 100644 LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.cs rename LibraryDBproject/LDBproj/AdditionalForms/{OrderRegistrations.resx => FullReportsF.resx} (100%) delete mode 100644 LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.Designer.cs delete mode 100644 LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.cs delete mode 100644 LibraryDBproject/LDBproj/AdditionalForms/RegOrder.Designer.cs delete mode 100644 LibraryDBproject/LDBproj/AdditionalForms/RegOrder.cs create mode 100644 LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.Designer.cs create mode 100644 LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.cs rename LibraryDBproject/LDBproj/AdditionalForms/{RegOrder.resx => UpdReportF.resx} (93%) delete mode 100644 LibraryDBproject/LDBproj/DBScript/TextCommands.txt create mode 100644 LibraryDBproject/LDBproj/Entities/TemprOrderReg.cs create mode 100644 LibraryDBproject/LDBproj/Reports/ChartReport.cs create mode 100644 LibraryDBproject/LDBproj/Reports/DocReport.cs create mode 100644 LibraryDBproject/LDBproj/Reports/ExcelBuilder.cs create mode 100644 LibraryDBproject/LDBproj/Reports/PdfBuilder.cs create mode 100644 LibraryDBproject/LDBproj/Reports/WordBuilder.cs diff --git a/LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.Designer.cs b/LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.Designer.cs new file mode 100644 index 0000000..f661676 --- /dev/null +++ b/LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.Designer.cs @@ -0,0 +1,104 @@ +namespace LDBproject.AdditionalForms +{ + partial class FullReportsF + { + /// + /// 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() + { + BookChBox = new CheckBox(); + EmployeeChBox = new CheckBox(); + ReadersChBox = new CheckBox(); + ConfBuildBtn = new Button(); + SuspendLayout(); + // + // BookChBox + // + BookChBox.AutoSize = true; + BookChBox.ForeColor = Color.GreenYellow; + BookChBox.Location = new Point(58, 36); + BookChBox.Name = "BookChBox"; + BookChBox.Size = new Size(87, 29); + BookChBox.TabIndex = 0; + BookChBox.Text = "Books"; + BookChBox.UseVisualStyleBackColor = true; + // + // EmployeeChBox + // + EmployeeChBox.AutoSize = true; + EmployeeChBox.ForeColor = Color.GreenYellow; + EmployeeChBox.Location = new Point(239, 36); + EmployeeChBox.Name = "EmployeeChBox"; + EmployeeChBox.Size = new Size(113, 29); + EmployeeChBox.TabIndex = 1; + EmployeeChBox.Text = "Librarians"; + EmployeeChBox.UseVisualStyleBackColor = true; + // + // ReadersChBox + // + ReadersChBox.AutoSize = true; + ReadersChBox.ForeColor = Color.GreenYellow; + ReadersChBox.Location = new Point(455, 36); + ReadersChBox.Name = "ReadersChBox"; + ReadersChBox.Size = new Size(100, 29); + ReadersChBox.TabIndex = 2; + ReadersChBox.Text = "Readers"; + ReadersChBox.UseVisualStyleBackColor = true; + // + // ConfBuildBtn + // + ConfBuildBtn.ForeColor = Color.DarkSlateBlue; + ConfBuildBtn.Location = new Point(58, 86); + ConfBuildBtn.Name = "ConfBuildBtn"; + ConfBuildBtn.Size = new Size(497, 34); + ConfBuildBtn.TabIndex = 3; + ConfBuildBtn.Text = "Make report"; + ConfBuildBtn.UseVisualStyleBackColor = true; + ConfBuildBtn.Click += ConfBuildBtn_Click; + // + // ReportF + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + BackColor = Color.DarkSlateBlue; + ClientSize = new Size(610, 158); + Controls.Add(ConfBuildBtn); + Controls.Add(ReadersChBox); + Controls.Add(EmployeeChBox); + Controls.Add(BookChBox); + Name = "ReportF"; + Text = "ReportF"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private CheckBox BookChBox; + private CheckBox EmployeeChBox; + private CheckBox ReadersChBox; + private Button ConfBuildBtn; + } +} \ No newline at end of file diff --git a/LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.cs b/LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.cs new file mode 100644 index 0000000..38ca6fe --- /dev/null +++ b/LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.cs @@ -0,0 +1,49 @@ +using LDBproject.Reports; +using Unity; +namespace LDBproject.AdditionalForms; + +public partial class FullReportsF : Form +{ + + private readonly IUnityContainer _container; + + public FullReportsF(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + + private void ConfBuildBtn_Click(object sender, EventArgs e) + { + try + { + if (!BookChBox.Checked && !EmployeeChBox.Checked && !ReadersChBox.Checked) + { + throw new Exception("There are no options chosen [!]"); + } + + var sfd = new SaveFileDialog() + { + Filter = "Docx Files | *.docx" + }; + + if (sfd.ShowDialog() != DialogResult.OK) + { + throw new Exception("No file chosen [!]"); + } + + if (_container.Resolve().CreateDoc(sfd.FileName, BookChBox.Checked, EmployeeChBox.Checked, ReadersChBox.Checked)) + { + MessageBox.Show("The document was formed : Report done", "Process result", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("< ERROR : see logs >", "Document creation", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "< ERROR : while creating report >", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } +} diff --git a/LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.resx b/LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.resx similarity index 100% rename from LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.resx rename to LibraryDBproject/LDBproj/AdditionalForms/FullReportsF.resx diff --git a/LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.Designer.cs b/LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.Designer.cs deleted file mode 100644 index 1463d2f..0000000 --- a/LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.Designer.cs +++ /dev/null @@ -1,112 +0,0 @@ -namespace LDBproject.AdditionalForms -{ - partial class OrderRegistrations - { - /// - /// 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() - { - panel1 = new Panel(); - DelBtn = new Button(); - AddBtn = new Button(); - DataGV = new DataGridView(); - panel1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)DataGV).BeginInit(); - SuspendLayout(); - // - // panel1 - // - panel1.BackColor = Color.Transparent; - panel1.Controls.Add(DelBtn); - panel1.Controls.Add(AddBtn); - panel1.Dock = DockStyle.Right; - panel1.Location = new Point(430, 0); - panel1.Name = "panel1"; - panel1.Size = new Size(246, 364); - panel1.TabIndex = 4; - // - // DelBtn - // - DelBtn.BackColor = Color.DarkSlateBlue; - DelBtn.BackgroundImage = Properties.Resources.DelImg; - DelBtn.BackgroundImageLayout = ImageLayout.Stretch; - DelBtn.ForeColor = Color.Transparent; - DelBtn.Location = new Point(129, 34); - DelBtn.Name = "DelBtn"; - DelBtn.Size = new Size(78, 71); - DelBtn.TabIndex = 6; - DelBtn.UseVisualStyleBackColor = false; - DelBtn.Click += DelBtn_Click; - // - // AddBtn - // - AddBtn.BackColor = Color.DarkSlateBlue; - AddBtn.BackgroundImage = Properties.Resources.AddImg; - AddBtn.BackgroundImageLayout = ImageLayout.Stretch; - AddBtn.ForeColor = Color.Transparent; - AddBtn.Location = new Point(24, 34); - AddBtn.Name = "AddBtn"; - AddBtn.Size = new Size(78, 71); - AddBtn.TabIndex = 4; - AddBtn.UseVisualStyleBackColor = false; - AddBtn.Click += AddBtn_Click; - // - // DataGV - // - DataGV.BackgroundColor = Color.DarkSlateBlue; - DataGV.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - DataGV.GridColor = Color.GreenYellow; - DataGV.Location = new Point(28, 86); - DataGV.Name = "DataGV"; - DataGV.RowHeadersWidth = 62; - DataGV.Size = new Size(357, 245); - DataGV.TabIndex = 5; - // - // OrderRegistrations - // - AutoScaleDimensions = new SizeF(10F, 25F); - AutoScaleMode = AutoScaleMode.Font; - BackgroundImage = Properties.Resources.RegistrationsFrameCover; - BackgroundImageLayout = ImageLayout.Stretch; - ClientSize = new Size(676, 364); - Controls.Add(DataGV); - Controls.Add(panel1); - DoubleBuffered = true; - Name = "OrderRegistrations"; - Text = "OrderRegistrations"; - Load += RegistrationsF_Load; - panel1.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)DataGV).EndInit(); - ResumeLayout(false); - } - - #endregion - - private Panel panel1; - private Button DelBtn; - private Button AddBtn; - private DataGridView DataGV; - } -} \ No newline at end of file diff --git a/LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.cs b/LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.cs deleted file mode 100644 index dc808c6..0000000 --- a/LibraryDBproject/LDBproj/AdditionalForms/OrderRegistrations.cs +++ /dev/null @@ -1,83 +0,0 @@ -using LDBproject.Repositories; -using Unity; - -namespace LDBproject.AdditionalForms; - -public partial class OrderRegistrations : Form -{ - private readonly IUnityContainer _container; - private readonly IOrderRep _regR; - - public OrderRegistrations(IUnityContainer container, IOrderRep regR) - { - InitializeComponent(); - _regR = regR ?? throw new ArgumentNullException(nameof(regR)); - _container = container ?? throw new ArgumentNullException(nameof(container)); - } - - private void RegistrationsF_Load(object sender, EventArgs e) - { - try - { - ReloadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "[ Error while saving ]", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void AddBtn_Click(object sender, EventArgs e) - { - try - { - _container.Resolve().ShowDialog(); - ReloadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "[ Error while adding element ]", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void DelBtn_Click(object sender, EventArgs e) - { - if (!GetIDFromRow(out var foundID)) - { - return; - } - - if (MessageBox.Show("Remove element?", "Deleting", MessageBoxButtons.YesNo) != DialogResult.Yes) - { - return; - } - - try - { - _regR.DeleteOrderinfo(foundID); - ReloadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "[ Error while removing element ]", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void ReloadList() => - DataGV.DataSource = _regR.GetOrdersInfo(); - - private bool GetIDFromRow(out int id) - { - id = 0; - if (DataGV.SelectedRows.Count < 1) - { - MessageBox.Show("[ Error : element doesn't exist ]", "", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - - id = Convert.ToInt32(DataGV.SelectedRows[0].Cells["OrderID"].Value); - return true; - } -} - - diff --git a/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.Designer.cs b/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.Designer.cs deleted file mode 100644 index 8e5b811..0000000 --- a/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.Designer.cs +++ /dev/null @@ -1,200 +0,0 @@ -namespace LDBproject.AdditionalForms -{ - partial class RegOrder - { - /// - /// 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() - { - LibrarianCBox = new ComboBox(); - LibLabel = new Label(); - DateLabel = new Label(); - BorrowDTPicker = new DateTimePicker(); - groupBox1 = new GroupBox(); - DataGV = new DataGridView(); - SaveBtn = new Button(); - BackBtn = new Button(); - ReaderLabel = new Label(); - CardCBox = new ComboBox(); - BookColumnCBox = new DataGridViewComboBoxColumn(); - NoteColumn = new DataGridViewTextBoxColumn(); - groupBox1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)DataGV).BeginInit(); - SuspendLayout(); - // - // LibrarianCBox - // - LibrarianCBox.FormattingEnabled = true; - LibrarianCBox.Location = new Point(155, 44); - LibrarianCBox.Margin = new Padding(4); - LibrarianCBox.Name = "LibrarianCBox"; - LibrarianCBox.Size = new Size(235, 40); - LibrarianCBox.TabIndex = 0; - // - // LibLabel - // - LibLabel.AutoSize = true; - LibLabel.Location = new Point(39, 47); - LibLabel.Margin = new Padding(4, 0, 4, 0); - LibLabel.Name = "LibLabel"; - LibLabel.Size = new Size(110, 32); - LibLabel.TabIndex = 1; - LibLabel.Text = "Librarian:"; - // - // DateLabel - // - DateLabel.AutoSize = true; - DateLabel.Location = new Point(39, 164); - DateLabel.Margin = new Padding(4, 0, 4, 0); - DateLabel.Name = "DateLabel"; - DateLabel.Size = new Size(148, 32); - DateLabel.TabIndex = 2; - DateLabel.Text = "Borrow date:"; - // - // BorrowDTPicker - // - BorrowDTPicker.Location = new Point(48, 209); - BorrowDTPicker.Margin = new Padding(4); - BorrowDTPicker.Name = "BorrowDTPicker"; - BorrowDTPicker.Size = new Size(342, 39); - BorrowDTPicker.TabIndex = 3; - // - // groupBox1 - // - groupBox1.Controls.Add(DataGV); - groupBox1.Location = new Point(434, 31); - groupBox1.Margin = new Padding(4); - groupBox1.Name = "groupBox1"; - groupBox1.Padding = new Padding(4); - groupBox1.Size = new Size(550, 340); - groupBox1.TabIndex = 4; - groupBox1.TabStop = false; - groupBox1.Text = "BookListGBox"; - // - // DataGV - // - DataGV.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - DataGV.Columns.AddRange(new DataGridViewColumn[] { BookColumnCBox, NoteColumn }); - DataGV.Location = new Point(8, 52); - DataGV.Margin = new Padding(4); - DataGV.Name = "DataGV"; - DataGV.RowHeadersWidth = 62; - DataGV.Size = new Size(534, 264); - DataGV.TabIndex = 0; - // - // SaveBtn - // - SaveBtn.Location = new Point(48, 276); - SaveBtn.Margin = new Padding(4); - SaveBtn.Name = "SaveBtn"; - SaveBtn.Size = new Size(343, 44); - SaveBtn.TabIndex = 5; - SaveBtn.Text = "Save and give out"; - SaveBtn.UseVisualStyleBackColor = true; - SaveBtn.Click += SaveBtn_Click; - // - // BackBtn - // - BackBtn.Location = new Point(48, 328); - BackBtn.Margin = new Padding(4); - BackBtn.Name = "BackBtn"; - BackBtn.Size = new Size(343, 44); - BackBtn.TabIndex = 6; - BackBtn.Text = "Go back"; - BackBtn.UseVisualStyleBackColor = true; - BackBtn.Click += BackBtn_Click; - // - // ReaderLabel - // - ReaderLabel.AutoSize = true; - ReaderLabel.Location = new Point(39, 90); - ReaderLabel.Margin = new Padding(4, 0, 4, 0); - ReaderLabel.Name = "ReaderLabel"; - ReaderLabel.Size = new Size(87, 64); - ReaderLabel.TabIndex = 7; - ReaderLabel.Text = "Reader\r\ncard:"; - // - // CardCBox - // - CardCBox.FormattingEnabled = true; - CardCBox.Location = new Point(155, 105); - CardCBox.Margin = new Padding(4); - CardCBox.Name = "CardCBox"; - CardCBox.Size = new Size(235, 40); - CardCBox.TabIndex = 8; - // - // BookColumnCBox - // - BookColumnCBox.HeaderText = "Book's title"; - BookColumnCBox.MinimumWidth = 8; - BookColumnCBox.Name = "BookColumnCBox"; - BookColumnCBox.Width = 150; - // - // NoteColumn - // - NoteColumn.HeaderText = "Note"; - NoteColumn.MinimumWidth = 8; - NoteColumn.Name = "NoteColumn"; - NoteColumn.Width = 150; - // - // RegOrder - // - AutoScaleDimensions = new SizeF(13F, 32F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1020, 402); - Controls.Add(CardCBox); - Controls.Add(ReaderLabel); - Controls.Add(BackBtn); - Controls.Add(SaveBtn); - Controls.Add(groupBox1); - Controls.Add(BorrowDTPicker); - Controls.Add(DateLabel); - Controls.Add(LibLabel); - Controls.Add(LibrarianCBox); - Margin = new Padding(4); - Name = "RegOrder"; - Text = "RegOrder"; - groupBox1.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)DataGV).EndInit(); - ResumeLayout(false); - PerformLayout(); - } - - #endregion - - private ComboBox LibrarianCBox; - private Label LibLabel; - private Label DateLabel; - private DateTimePicker BorrowDTPicker; - private GroupBox groupBox1; - private DataGridView DataGV; - private Button SaveBtn; - private Button BackBtn; - private Label ReaderLabel; - private ComboBox CardCBox; - private DataGridViewComboBoxColumn BookColumnCBox; - private DataGridViewTextBoxColumn NoteColumn; - } -} \ No newline at end of file diff --git a/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.cs b/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.cs deleted file mode 100644 index 9520304..0000000 --- a/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.cs +++ /dev/null @@ -1,66 +0,0 @@ -using LDBproject.Entities; -using LDBproject.Repositories; -using LDBproject.Repositories.Implementations; - -namespace LDBproject.AdditionalForms; - -public partial class RegOrder : Form -{ - private readonly IOrderRep _orderRepository; - - public RegOrder(IOrderRep orderRep, ICustomerCardsRep readerRep, - ILibrarianRep employeeRep, IBookRep bookRep) - { - InitializeComponent(); - _orderRepository = orderRep ?? throw new ArgumentNullException(nameof(orderRep)); - - LibrarianCBox.DataSource = employeeRep.GetCards(); - LibrarianCBox.DisplayMember = "FIO"; - LibrarianCBox.ValueMember = "CardID"; - - CardCBox.DataSource = readerRep.GetCards(); - CardCBox.DisplayMember = "FIO"; - CardCBox.ValueMember = "CardID"; - - BookColumnCBox.DataSource = bookRep.GetBookList(); - BookColumnCBox.DisplayMember = "Title"; - BookColumnCBox.ValueMember = "BookID"; - } - - private void SaveBtn_Click(object sender, EventArgs e) - { - try - { - if (DataGV.RowCount < 1 || LibrarianCBox.SelectedIndex < 0) - { - throw new Exception("[ Blanck space left ]"); - } - _orderRepository.CreateOrder(Order.NewOrder(0, (int)CardCBox.SelectedValue, (int)LibrarianCBox.SelectedValue, - CreateBookListFromDG(), BorrowDTPicker.Value)); - - Close(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Order Form [ Error while saving order ]", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private List CreateBookListFromDG() - { - List registrations = new List(); - foreach (DataGridViewRow row in DataGV.Rows) - { - if (row.Cells["BookColumnCBox"].Value != null) - { - var bookId = (int)row.Cells["BookColumnCBox"].Value; - var notes = row.Cells["NoteColumn"].Value?.ToString(); - registrations.Add(Registration.OrderReg(0, bookId, notes)); - } - } - return registrations; - } - - private void BackBtn_Click(object sender, EventArgs e) => Close(); -} diff --git a/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.Designer.cs b/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.Designer.cs new file mode 100644 index 0000000..29e7ad3 --- /dev/null +++ b/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.Designer.cs @@ -0,0 +1,107 @@ +namespace LDBproject.AdditionalForms +{ + partial class UpdReportF + { + /// + /// 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() + { + button1 = new Button(); + button2 = new Button(); + UpdDTP = new DateTimePicker(); + label = new Label(); + FileNamelabel = new Label(); + SuspendLayout(); + // + // button1 + // + button1.Location = new Point(41, 28); + button1.Name = "button1"; + button1.Size = new Size(453, 46); + button1.TabIndex = 0; + button1.Text = "Choose file path"; + button1.UseVisualStyleBackColor = true; + button1.Click += SelectFileNameBtn_Click; + // + // button2 + // + button2.Location = new Point(41, 247); + button2.Name = "button2"; + button2.Size = new Size(453, 46); + button2.TabIndex = 1; + button2.Text = "Ok"; + button2.UseVisualStyleBackColor = true; + button2.Click += CreateBtn_Click; + // + // UpdDTP + // + UpdDTP.Location = new Point(73, 190); + UpdDTP.Name = "UpdDTP"; + UpdDTP.Size = new Size(400, 39); + UpdDTP.TabIndex = 2; + // + // label + // + label.AutoSize = true; + label.Location = new Point(81, 141); + label.Name = "label"; + label.Size = new Size(383, 32); + label.TabIndex = 3; + label.Text = "Check how much updates was on :"; + // + // FileNamelabel + // + FileNamelabel.AutoSize = true; + FileNamelabel.Location = new Point(44, 79); + FileNamelabel.Name = "FileNamelabel"; + FileNamelabel.Size = new Size(120, 32); + FileNamelabel.TabIndex = 4; + FileNamelabel.Text = "/file path/"; + // + // UpdReport + // + AutoScaleDimensions = new SizeF(13F, 32F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(543, 330); + Controls.Add(FileNamelabel); + Controls.Add(label); + Controls.Add(UpdDTP); + Controls.Add(button2); + Controls.Add(button1); + Name = "UpdReport"; + Text = "UpdReport"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button button1; + private Button button2; + private DateTimePicker UpdDTP; + private Label label; + private Label FileNamelabel; + } +} \ No newline at end of file diff --git a/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.cs b/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.cs new file mode 100644 index 0000000..b135030 --- /dev/null +++ b/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.cs @@ -0,0 +1,55 @@ +using System.Windows.Forms; +using Unity; + +namespace LDBproject.AdditionalForms +{ + public partial class UpdReportF : Form + { + private string _fileName = string.Empty; + private readonly IUnityContainer _container; + public UpdReportF(IUnityContainer container) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + } + private void SelectFileNameBtn_Click(object sender, EventArgs e) + { + var sfd = new SaveFileDialog() + { + Filter = "Pdf Files | *.pdf" + }; + if (sfd.ShowDialog() == DialogResult.OK) + { + _fileName = sfd.FileName; + FileNamelabel.Text = Path.GetFileName(_fileName); + } + } + private void CreateBtn_Click(object sender, EventArgs e) + { + try + { + if (string.IsNullOrWhiteSpace(_fileName)) + { + throw new Exception("No file (path) chosen"); + } + if + (_container.Resolve().CreateChart(_fileName, UpdDTP.Value)) + { + MessageBox.Show("< PDF Document was formated >", "Creating chart report (pdf)", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + MessageBox.Show("< ERROR : see logs >", "Pdf. formating", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "< ERROR : while creating pdf document >", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.resx b/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.resx similarity index 93% rename from LibraryDBproject/LDBproj/AdditionalForms/RegOrder.resx rename to LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.resx index ef527f1..af32865 100644 --- a/LibraryDBproject/LDBproj/AdditionalForms/RegOrder.resx +++ b/LibraryDBproject/LDBproj/AdditionalForms/UpdReportF.resx @@ -117,10 +117,4 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - True - - - True - \ No newline at end of file diff --git a/LibraryDBproject/LDBproj/DBScript/TextCommands.txt b/LibraryDBproject/LDBproj/DBScript/TextCommands.txt deleted file mode 100644 index c0bc7f7..0000000 --- a/LibraryDBproject/LDBproj/DBScript/TextCommands.txt +++ /dev/null @@ -1,201 +0,0 @@ --- Insert data into Genres -INSERT INTO Genres (GenreName) VALUES -('None'), ('Adventure'), ('Fantasy'), ('Mystery'), ('Fiction'), ('Suspense'), ('Romance'), ('Crime'), ('Talent'), ('Realism'), ('Horror'), ('Historical'); - --- Insert data into Books (with updated GenreIDs and Status) -INSERT INTO Books (Title, Author, PublishYear, Status, GenreMask) VALUES -('The Hobbit', 'J.R.R. Tolkien', 1937, 3, 1024), -- On Stock, Fantasy -('Pride and Prejudice', 'Jane Austen', 1813, 3, 2 | 128), -- On Stock, Romance | Realism -('The Da Vinci Code', 'Dan Brown', 2003, 4, 4 | 16), -- Borrowed, Mystery | Suspense -('1984', 'George Orwell', 1949, 3, 8 | 128), -- On Stock, Fiction | Realism -('To Kill a Mockingbird', 'Harper Lee', 1960, 4, 8 | 128), -- Borrowed, Fiction | Realism -('The Great Gatsby', 'F. Scott Fitzgerald', 1925, 3, 2 | 128), -- On Stock, Romance | Realism -('The Time Traveler''s Wife', 'Audrey Niffenegger', 2003, 4, 2 | 1024), -- Borrowed, Romance | Fantasy -('The Secret Garden', 'Frances Hodgson Burnett', 1911, 2, 1), -- in IDassignment state, Adventure -('Gone Girl', 'Gillian Flynn', 2012, 1, 4 | 16 | 32), -- Ordered, Mystery | Suspense | Crime -('A Game of Thrones', 'George R.R. Martin', 1996, 3, 1 | 1024 | 8), -- On Stock, Adventure | Fantasy | Fiction -('Harry Potter and the Sorcerer''s Stone', 'J.K. Rowling', 1997, 3, 1 | 8 | 1024), -- On Stock, Adventure | Fiction | Fantasy -('The Martian', 'Andy Weir', 2011, 3, 1 | 8), -- On Stock, Adventure | Fiction -('Little Women', 'Louisa May Alcott', 1868, 5, 2), -- Debited, Romance -('The Seven Husbands of Evelyn Hugo', 'Taylor Jenkins Reid', 2017, 3, 2 | 128); -- On Stock, Romance | Realism --- ('Where the Crawdads Sing', 'Delia Owens', 2018, ); -- Fiction, Borrowed --- ('The Lord of the Rings', 'J.R.R. Tolkien', 1954, ), -- Fantasy, Unable --- ('The Nightingale', 'Kristin Hannah', 2015, ), -- Romance, Borrowed --- ('The Book Thief', 'Markus Zusak', 2005, ), -- Fiction, On Stock --- ('The Help', 'Kathryn Stockett', 2009, ), -- Fiction, Borrowed --- ('The Girl on the Train', 'Paula Hawkins', 2015, ), -- Suspense, On Stock --- ('The Girl with the Dragon Tattoo', 'Stieg Larsson', 2005, ), -- Suspense, On Stock --- ('The Catcher in the Rye', 'J.D. Salinger', 1951, ), -- Fiction, Unable --- ('The Hunger Games', 'Suzanne Collins', 2008, ), -- Suspense, Borrowed --- ('The Silent Patient', 'Alex Michaelides', 2019, ), -- Mystery, Unable --- ('And Then There Were None', 'Agatha Christie', 1939, ), -- Mystery, Unable - --- Insert data into LibrarianCards (reference existing GenreIDs) -INSERT INTO LibrarianCards (FIO, GenreMask) VALUES -('Carla R.E.', 4 | 16 | 32), -('Bonnet D.P.', 2 | 128), -('Gabriel W.T.', 1 | 1024 | 8); - --- Insert data into CustomerCards -INSERT INTO CustomerCards (FIO, AgeBirthday) VALUES -('Winsent G.P.', '2000-01-15'), -('Quincy P.R.', '2005-05-20'), -('Emily Y.N.', '2009-11-10'), -('Frank A.K.', '2007-07-25'), -('Marinett J.C.', '2004-03-01'), -('Alice B.T.', '2002-08-10'), -('Bob C.L.', '1998-03-25'), -('Charlie D.M.', '2011-06-18'), -('Diana E.S.', '1995-12-05'), -('Eve F.W.', '2007-09-30'); - - --- Insert more data into Orders -INSERT INTO Orders (CardID, LibrarianID, BorrowDate) VALUES -(6, 1, '2024-05-10 11:00:00'), -(1, 3, '2024-05-15 15:30:00'), -(9, 1, '2024-05-20 09:45:00'), -(3, 2, '2024-05-25 13:15:00'), -(4, 3, '2024-06-01 10:00:00'), -(5, 1, '2024-06-05 16:45:00'), -(10, 2, '2024-06-10 14:15:00'), -(1, 1, '2024-07-15 10:30:00'), -(10, 3, '2024-07-20 12:45:00'), -(7, 1, '2024-07-25 17:00:00'), -(2, 1, '2024-08-20 09:45:00'), -(8, 2, '2024-08-25 13:15:00'), -(4, 3, '2024-09-01 10:00:00'), -(5, 1, '2024-09-12 16:45:00'), -(8, 3, '2024-09-16 10:00:00'), -(6, 1, '2024-09-24 16:45:00'), -(9, 2, '2024-10-10 14:15:00'), -(1, 1, '2024-10-15 10:30:00'), -(7, 3, '2024-12-09 12:45:00'), -(3, 1, '2024-12-25 17:00:00'), -(4, 1, '2024-12-20 09:45:00'); - --- Insert more data into Registrations -INSERT INTO Registrations (OrderID, BookID, Note) VALUES -(1, 6, '07-10'), -(2, 10, '07-15'), -(3, 2, '07-20'), -(4, 7, '07-25'), -(5, 11, '08-07'), -(5, 9, '08-07'), -(6, 8, '08-10'), -(7, 4, '08-15'), -(7, 5, '08-15'), -(7, 6, '08-15'), -(7, 7, '08-15'), -(8, 11, '08-18'), -(9, 9, '08-27'), -(9, 3, '08-10'), -(10, 4, '08-15'), -(11, 8, '07-25'), -(12, 10, '08-01'), -(13, 12, '08-05'), -(14, 3, '08-10'), -(14, 4, '08-15'), -(14, 5, '08-20'), -(14, 1, '08-25'), -(15, 6, '08-25'), -(16, 7, '07-25'), -(17, 8, '08-01'), -(17, 9, '08-05'), -(18, 11, '08-10'), -(18, 4, '08-15'), -(18, 7, '07-25'), -(18, 1, '08-01'); - --- Insert more data into Updates – Multiple updates on the same day -INSERT INTO Updates (LastUpdate, UpdBoundary, Note, LibrarianID, CardID) VALUES -('2017-05-10', '2021-03-15', 'Card Received', 3, 1), -('2022-11-22', '2025-08-20', 'Renewed card', 2, 3), -('2016-02-01', '2020-01-10', 'Card Received', 2, 2), -('2020-09-18', '2024-12-05', 'Updated address', 1, 4), -('2018-07-05', '2024-06-25', 'Card Received', 3, 5), -('2023-10-26', '2024-04-15', 'Lost card, reissued', 1, 1), -('2023-10-26', '2024-05-10', 'Payment overdue', 2, 5), -('2024-01-15', '2024-07-15', 'Address change', 3, 2), -('2024-03-01', '2024-09-01', 'Renewed card', 1, 4), -('2024-03-01', '2024-09-01', 'Fee payment', 1, 3), -- Multiple updates on the same day -('2024-03-10', '2025-01-10', 'Card Received', 2, 6), -('2024-04-20', '2025-02-20', 'Renewal', 3, 1), -('2024-05-10', '2025-03-10', 'New Card issued', 1, 5); - --- Drop the table if it exists ----------------------------- -DROP TABLE IF EXISTS Updates; - -DROP TABLE IF EXISTS Registrations; -DROP TABLE IF EXISTS Orders; - -DROP TABLE IF EXISTS LibrarianCards; -DROP TABLE IF EXISTS CustomerCards; - -DROP TABLE IF EXISTS Books; -DROP TABLE IF EXISTS Genres; - --- Create the Genres table [ 1 ] -CREATE TABLE Genres ( - GenreID SERIAL PRIMARY KEY, - GenreName VARCHAR(255) NOT NULL UNIQUE -); - --- Create the Books table [ 2 ] -CREATE TABLE Books ( - BookID SERIAL PRIMARY KEY, - Title VARCHAR(255) NOT NULL, - Author VARCHAR(255) NOT NULL, - PublishYear INTEGER, - Status INTEGER CHECK (Status IN (0, 1, 2, 3, 4, 5)), - GenreMask INTEGER DEFAULT 0 - -- CountOnStock INTEGER CHECK (CountOnStock >= 0), - -- > GenreID INTEGER REFERENCES Genres(GenreID) -); - --- > ALTER TABLE Books DROP COLUMN GenreID; - --- Now, add the GenreMask column to the Books table --- [ ! ] ALTER TABLE Books ADD COLUMN GenreMask INTEGER DEFAULT 0; -- Using INTEGER to store bitmask - - --- Create the CustomerCards table [ 3 ] -CREATE TABLE CustomerCards ( - CardID SERIAL PRIMARY KEY, - FIO VARCHAR(255) NOT NULL, - AgeBirthday DATE -); - --- Create the LibrarianCards table [ 4 ] -CREATE TABLE LibrarianCards ( - CardID SERIAL PRIMARY KEY, - FIO VARCHAR(255) NOT NULL, - GenreMask INTEGER DEFAULT 0 - -- GenreID INTEGER REFERENCES Genres(GenreID) -); - --- Create the Orders table [ 5 ] -CREATE TABLE Orders ( - OrderID SERIAL PRIMARY KEY, - CardID INTEGER REFERENCES CustomerCards(CardID) NOT NULL, - LibrarianID INTEGER REFERENCES LibrarianCards(CardID) NOT NULL, - BorrowDate TIMESTAMP WITH TIME ZONE -); - --- Create the Registrations table [ 6 ] -CREATE TABLE Registrations ( - ID SERIAL PRIMARY KEY, - OrderID INTEGER REFERENCES Orders(OrderID) NOT NULL, - BookID INTEGER REFERENCES Books(BookID) NOT NULL, - Note TEXT -); - --- Create the Updates table [ 7 ] -CREATE TABLE Updates ( - ID SERIAL PRIMARY KEY, - LastUpdate DATE NOT NULL, - UpdBoundary DATE, - Note TEXT, - LibrarianID INTEGER REFERENCES LibrarianCards(CardID) NOT NULL, - CardID INTEGER REFERENCES CustomerCards(CardID) NOT NULL -); diff --git a/LibraryDBproject/LDBproj/Entities/TemprOrderReg.cs b/LibraryDBproject/LDBproj/Entities/TemprOrderReg.cs new file mode 100644 index 0000000..fcadf00 --- /dev/null +++ b/LibraryDBproject/LDBproj/Entities/TemprOrderReg.cs @@ -0,0 +1,20 @@ +namespace LDBproject.Entities; + +internal class TemprOrderReg +{ + // from Order class + public int OrderID { get; private set; } + + public int CardID { get; private set; } + + public int LibrarianID { get; private set; } + + public DateTime BorrowDate { get; private set; } + + // from Registration class + public int ID { get; private set; } + + public int BookID { get; private set; } + + public string Note { get; private set; } +} diff --git a/LibraryDBproject/LDBproj/LDBproject.csproj b/LibraryDBproject/LDBproj/LDBproject.csproj index 8508f1d..30fa452 100644 --- a/LibraryDBproject/LDBproj/LDBproject.csproj +++ b/LibraryDBproject/LDBproj/LDBproject.csproj @@ -10,11 +10,14 @@ + + + diff --git a/LibraryDBproject/LDBproj/MainForm.Designer.cs b/LibraryDBproject/LDBproj/MainForm.Designer.cs index eca7d93..e38a574 100644 --- a/LibraryDBproject/LDBproj/MainForm.Designer.cs +++ b/LibraryDBproject/LDBproj/MainForm.Designer.cs @@ -1,4 +1,6 @@ -namespace LDBproject +using LDBproject.AdditionalForms; + +namespace LDBproject { partial class MainForm { @@ -40,6 +42,11 @@ GiveOut = new ToolStripMenuItem(); Updating = new ToolStripMenuItem(); LogsTSMI = new ToolStripMenuItem(); + + ReportW = new ToolStripMenuItem(); + ReportP = new ToolStripMenuItem(); + ReportC = new ToolStripMenuItem(); + menuStrip1.SuspendLayout(); menuStrip2.SuspendLayout(); SuspendLayout(); @@ -133,10 +140,33 @@ // // LogsTSMI // + LogsTSMI.DropDownItems.AddRange(new ToolStripItem[] { ReportW, ReportP, ReportC }); LogsTSMI.ForeColor = Color.DarkSlateBlue; LogsTSMI.Name = "LogsTSMI"; LogsTSMI.Size = new Size(88, 29); LogsTSMI.Text = "Отчёты"; + + // Reports --- [ ! ] + ReportW.BackColor = Color.DarkSlateBlue; + ReportW.ForeColor = Color.GreenYellow; + ReportW.Name = "ReportW"; + ReportW.Size = new Size(273, 34); + ReportW.Text = "Сформировать документ"; + ReportW.Click += Report_Click; + + ReportP.BackColor = Color.DarkSlateBlue; + ReportP.ForeColor = Color.GreenYellow; + ReportP.Name = "ReportP"; + ReportP.Size = new Size(273, 34); + ReportP.Text = "Отчёт о заказах"; + ReportP.Click += OrderReport_Click; + + ReportC.BackColor = Color.DarkSlateBlue; + ReportC.ForeColor = Color.GreenYellow; + ReportC.Name = "ReportC"; + ReportC.Size = new Size(273, 34); + ReportC.Text = "Отчёт о билетах"; + ReportC.Click += UpdReport_Click; // // MainForm // @@ -172,5 +202,9 @@ private ToolStripMenuItem ReaderCard; private ToolStripMenuItem BookReg; private ToolStripMenuItem Updating; + + private ToolStripMenuItem ReportW; + private ToolStripMenuItem ReportP; + private ToolStripMenuItem ReportC; } } diff --git a/LibraryDBproject/LDBproj/MainForm.cs b/LibraryDBproject/LDBproj/MainForm.cs index 9aaeadd..06e1af7 100644 --- a/LibraryDBproject/LDBproj/MainForm.cs +++ b/LibraryDBproject/LDBproj/MainForm.cs @@ -57,7 +57,7 @@ public partial class MainForm : Form { try { - _container.Resolve().ShowDialog(); + _container.Resolve().ShowDialog(); } catch (Exception ex) { @@ -78,5 +78,44 @@ public partial class MainForm : Form MessageBoxButtons.OK, MessageBoxIcon.Error); } } + + private void Report_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "[ Download : ERROR ]", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void OrderReport_Click(object sender, EventArgs e) + { + try + { + + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "[ Download : ERROR ]", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void UpdReport_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "[ Download : ERROR ]", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } diff --git a/LibraryDBproject/LDBproj/Reports/ChartReport.cs b/LibraryDBproject/LDBproj/Reports/ChartReport.cs new file mode 100644 index 0000000..10dc074 --- /dev/null +++ b/LibraryDBproject/LDBproj/Reports/ChartReport.cs @@ -0,0 +1,56 @@ +using Microsoft.Extensions.Logging; +using LDBproject.Entities; +using LDBproject.Repositories; +using LDBproject.Reports; + +internal class ChartReport +{ + private readonly IUpdateRep _updR; + private readonly ILogger _logger; + + public ChartReport(IUpdateRep updR, ILogger logger) + { + _updR = updR ?? throw new ArgumentNullException(nameof(updR)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateChart(string filePath, DateTime dateTime) + { + try + { + var updates = _updR.GetUpdateList().ToList(); // Materialize the query + var data = GetData(updates, dateTime); + + System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); + + new PdfBuilder(filePath).AddHeader("Card Updates") // More descriptive header + .AddPieChart("Number of Times Card Updated", data) // Corrected caption + .Build(); + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error creating chart."); + return false; + } + } + + private List<(string Caption, double Value)> GetData(List updates, DateTime date) + { + var result = new List<(string Caption, double Value)>(); + + var distinctCards = updates.Where(u => u.LastUpdate.Date == date.Date) // Filter by date + .GroupBy(u => u.CardID) + .Select(g => new { CardID = g.Key, Count = g.Count() }) + .ToList(); + + + foreach (var cardData in distinctCards) + { + result.Add(($"Card {cardData.CardID}", cardData.Count)); + } + + return result; + } + +} diff --git a/LibraryDBproject/LDBproj/Reports/DocReport.cs b/LibraryDBproject/LDBproj/Reports/DocReport.cs new file mode 100644 index 0000000..e1f4064 --- /dev/null +++ b/LibraryDBproject/LDBproj/Reports/DocReport.cs @@ -0,0 +1,75 @@ +using Microsoft.Extensions.Logging; +using LDBproject.Repositories; + +namespace LDBproject.Reports; + +internal class DocReport +{ + private readonly IBookRep _bookRep; + private readonly ILibrarianRep _librarianRep; + private readonly ICustomerCardsRep _customerRep; + private readonly ILogger _logger; + + public DocReport(IBookRep bookRep, ILibrarianRep librarianRep, + ICustomerCardsRep customerRep, ILogger logger) + { + _bookRep = bookRep ?? throw new ArgumentNullException(nameof(bookRep)); + _librarianRep = librarianRep ?? throw new ArgumentNullException(nameof(librarianRep)); + _customerRep = customerRep ?? throw new ArgumentNullException(nameof(customerRep)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public bool CreateDoc(string filePath, bool includeOrders, bool includeLibrarians, bool includeCustomers) + { + try + { + var builder = new WordBuilder(filePath).AddHeader("Reports Document"); + + if (includeOrders) + { + builder.AddParagraph("Книги").AddTable([2400, 2400, 1200], GetBooks()); + } + + if (includeLibrarians) + { + builder.AddParagraph("Работники").AddTable([2400, 1200], GetLibrarians()); + } + + if (includeCustomers) + { + builder.AddParagraph("Читатели").AddTable([2400, 2400], GetCustomers()); + } + + builder.Build(); + + return true; + } + catch (Exception ex) + { + _logger.LogError(ex, "< Error while forming document >"); + return false; + } + } + + private List GetBooks() + { + return [ + ["Title", "Author", "Year of publishing"], + .. _bookRep.GetBookList().Select(x => new string[] + { x.Title, x.Author, x.PublishYear.ToString() }),]; + } + + private List GetLibrarians() + { + return [["FIO", "Genres"], + .. _librarianRep.GetCards().Select(x => new string[] + { x.FIO, x.GenreMask.ToString() ?? "Unknown" }),]; + } + + private List GetCustomers() + { + return [["FIO", "Birthday"], + .. _customerRep.GetCards().Select(x => new string[] + { x.FIO, x.AgeBirthday.ToString() }),]; + } +} \ No newline at end of file diff --git a/LibraryDBproject/LDBproj/Reports/ExcelBuilder.cs b/LibraryDBproject/LDBproj/Reports/ExcelBuilder.cs new file mode 100644 index 0000000..6788849 --- /dev/null +++ b/LibraryDBproject/LDBproj/Reports/ExcelBuilder.cs @@ -0,0 +1,285 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; + +namespace LDBproject.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.BoldCentered); // Changed style + for (int i = startIndex + 1; i < startIndex + count; ++i) + { + CreateCell(i, _rowIndex, "", StyleIndex.BoldCentered); // Changed style + } + + _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[] columnWidths, List data) + { + // Error handling (keep this) + if (columnWidths == null || columnWidths.Length == 0) + { + throw new ArgumentNullException(nameof(columnWidths)); + } + + if (data == null || data.Count == 0) + { + throw new ArgumentNullException(nameof(data)); + } + + if (data.Any(x => x.Length != columnWidths.Length)) + { + throw new InvalidOperationException("Column widths and data row lengths must match."); + } + + if (data.Count > 0) + { + var firstRow = data.First(); + if (firstRow.Length != columnWidths.Length) + { + throw new InvalidOperationException("Column widths and data row lengths must match."); + } + } + + //Column setup - now it's dynamically calculated + uint counter = 1; + int coef = 2; // Consider making this a configurable parameter + _columns.Append(columnWidths.Select(x => new Column + { + Min = counter, + Max = counter++, + Width = x * coef, + CustomWidth = true + })); + for (int i = 0; i < data.Count; i++) + { + for (int j = 0; j < data[i].Length; j++) + { + StyleIndex styleIndex = (i == 0) ? StyleIndex.BoldCentered : StyleIndex.WithThinBorder; // Header row style + CreateCell(j, _rowIndex, data[i][j], styleIndex); + } + _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 = "Page 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 = 3, // Increased count to accommodate bold font + 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) } + }); + + // Added bold font + fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font + { + FontSize = new FontSize() { Val = 11 }, + FontName = new FontName() { Val = "Calibri" }, + FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 }, + Bold = new Bold(), // Added Bold element + FontScheme = new FontScheme() { Val = new EnumValue(FontSchemeValues.Minor) } + }); + + workbookStylesPart.Stylesheet.Append(fonts); + + // Default Fill + var fills = new Fills() { Count = 1 }; + fills.Append(new Fill + { + PatternFill = new PatternFill() + { + PatternType = new EnumValue(PatternValues.None) + } + }); + workbookStylesPart.Stylesheet.Append(fills); + + // Default Border & Added a border with lines + var borders = new Borders() { Count = 3 }; // Increased count for the new border + borders.Append(new Border + { + LeftBorder = new LeftBorder(), + RightBorder = new RightBorder(), + TopBorder = new TopBorder(), + BottomBorder = new BottomBorder(), + DiagonalBorder = new DiagonalBorder() + }); + + // Added a border with lines + 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); + + // Default cell format and a few more formats + 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 + } + }); + + // Added formats (customize these as needed) + cellFormats.Append(new CellFormat { NumberFormatId = 0, FontId = 1, BorderId = 1, Alignment = new Alignment { Horizontal = HorizontalAlignmentValues.Center } }); //Bold and centered + cellFormats.Append(new CellFormat { NumberFormatId = 0, FontId = 0, BorderId = 1 }); // With thin border + + workbookStylesPart.Stylesheet.Append(cellFormats); + } + + private enum StyleIndex + { + SimpleTextWithoutBorder = 0, + BoldCentered = 1, + WithThinBorder = 2 + } + + 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/LibraryDBproject/LDBproj/Reports/PdfBuilder.cs b/LibraryDBproject/LDBproj/Reports/PdfBuilder.cs new file mode 100644 index 0000000..a3348c8 --- /dev/null +++ b/LibraryDBproject/LDBproj/Reports/PdfBuilder.cs @@ -0,0 +1,88 @@ +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Shapes.Charts; +using MigraDoc.Rendering; + +namespace LDBproject.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(); + } + public PdfBuilder AddHeader(string header) + { + _document.AddSection().AddParagraph(header, "HeaderStyle"); // used the defined style + return this; + // _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() + { + // defined the HeaderStyle + string[] fallbackFonts = { "Arial", "Times New Roman", "Calibri" }; //List of fonts to try + + string fontName = "Times New Roman"; + + foreach (var font in fallbackFonts) + { + if (System.Drawing.FontFamily.Families.Any(f => f.Name == font)) + { + fontName = font; + break; + } + } + + var headerStyle = _document.Styles.AddStyle("HeaderStyle", "Normal"); + headerStyle.Font.Name = fontName; + headerStyle.Font.Size = 14; + headerStyle.Font.Bold = true; + } +} diff --git a/LibraryDBproject/LDBproj/Reports/WordBuilder.cs b/LibraryDBproject/LDBproj/Reports/WordBuilder.cs new file mode 100644 index 0000000..b5762e3 --- /dev/null +++ b/LibraryDBproject/LDBproj/Reports/WordBuilder.cs @@ -0,0 +1,99 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +internal class WordBuilder +{ + private readonly string _filePath; + private readonly Document _doc; + 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; + _doc = new Document(); + _body = _doc.AppendChild(new Body()); + } + + public WordBuilder AddHeader(string header) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + + // Set bold text using RunProperties + run.AppendChild(new RunProperties(new Bold())); + run.AppendChild(new Text(header)); // Use Wordprocessing.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]))))); // Use Wordprocessing.Text + } + table.Append(tr); + + // Данные + table.Append(data.Skip(1).Select(x => new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y)))))))); // Use Wordprocessing.Text + + _body.Append(table); + + return this; + } + + public WordBuilder AddParagraph(string text) + { + var paragraph = _body.AppendChild(new Paragraph()); + var run = paragraph.AppendChild(new Run()); + run.AppendChild(new Text(text)); // Use Wordprocessing.Text + + return this; + } + + public void Build() + { + using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document); + var mainPart = wordDocument.AddMainDocumentPart(); + mainPart.Document = _doc; + } +} \ No newline at end of file diff --git a/LibraryDBproject/LDBproj/Repositories/Implementations/OrderR.cs b/LibraryDBproject/LDBproj/Repositories/Implementations/OrderR.cs index f963b72..271a0f6 100644 --- a/LibraryDBproject/LDBproj/Repositories/Implementations/OrderR.cs +++ b/LibraryDBproject/LDBproj/Repositories/Implementations/OrderR.cs @@ -3,7 +3,6 @@ using LDBproject.Entities; using Newtonsoft.Json; using Npgsql; using Dapper; -using System.Data.SqlClient; namespace LDBproject.Repositories.Implementations;