Compare commits

..

16 Commits

Author SHA1 Message Date
30a3f088f7 починил странную ошибку 2023-05-23 00:11:38 +04:00
maxnes3
33d22bbb24 fix update lawyer 2023-05-20 11:00:13 +04:00
maxnes3
2cca5bd9b9 Ещё немного валидации 2023-05-20 09:55:10 +04:00
maxnes3
92c6c1c503 Мелкие правки 2023-05-20 09:10:45 +04:00
maxnes3
db5681fc25 Добавил диаграмму 2023-05-20 05:04:42 +04:00
maxnes3
636af51602 Пофиксил баги после слияния 2023-05-20 04:14:14 +04:00
2a69fbeb58 mergemerger 2023-05-20 04:05:26 +04:00
maxnes3
9c75a284f7 Осталось чуть-чуть 2023-05-20 04:01:37 +04:00
maxnes3
740f8ec2ef Ура, почти всё. Чё там с дедлайном?
Мать жива?
2023-05-20 03:13:10 +04:00
maxnes3
3134b5f6e1 Работает list 2023-05-20 00:24:04 +04:00
8207be80a7 merge commit 2023-05-19 22:38:29 +04:00
maxnes3
ba1d369a2d Cтранно 2023-05-19 22:34:30 +04:00
maxnes3
3aa0265de4 Merge branch 'main' of http://student.git.athene.tech/maxnes3/Case_accounting 2023-05-19 22:34:10 +04:00
maxnes3
7483e0682d Чек 2023-05-19 22:33:41 +04:00
86877b84eb Merge branch 'HelpBench' 2023-05-19 21:28:19 +04:00
maxnes3
cc28f399a4 Остались отчёты 2023-05-19 21:07:14 +04:00
72 changed files with 1983 additions and 182 deletions

View File

@ -76,6 +76,11 @@ namespace CaseAccountingBusinessLogic.BusinessLogics
return list; return list;
} }
public List<SpecializationCasesViewModel> GetSpecializationCases()
{
return _caseStorage.GetSpecializationCases() ?? new List<SpecializationCasesViewModel>();
}
public bool Update(CaseBindingModel model) public bool Update(CaseBindingModel model)
{ {
CheckModel(model); CheckModel(model);

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CaseAccountingContracts.BindingModels;
namespace CaseAccountingBusinessLogic.BusinessLogics
{
public class MailSender
{
private string mailLogin = string.Empty;
private string mailPassword = string.Empty;
private string smtpClientHost = string.Empty;
private int smtpClientPort;
public MailSender(){}
public void MailConfig(MailConfigBindingModel config)
{
mailLogin = config.MailLogin;
mailPassword = config.MailPassword;
smtpClientHost = config.SmtpClientHost;
smtpClientPort = config.SmtpClientPort;
}
public async void SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(smtpClientHost, smtpClientPort);
try
{
objMailMessage.From = new MailAddress(mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
MemoryStream ms = new(info.File);
objMailMessage.Attachments.Add(new Attachment(ms, "report.pdf", "application/pdf"));
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(mailLogin, mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
}
}

View File

@ -1,4 +1,6 @@
using CaseAccountingContracts.BindingModels; using CaseAccountingBusinessLogic.BusinessLogic.OfficePackage;
using CaseAccountingBusinessLogic.OfficePackage;
using CaseAccountingContracts.BindingModels;
using CaseAccountingContracts.BusinessLogicContracts; using CaseAccountingContracts.BusinessLogicContracts;
using CaseAccountingContracts.SearchModels; using CaseAccountingContracts.SearchModels;
using CaseAccountingContracts.StoragesContracts; using CaseAccountingContracts.StoragesContracts;
@ -17,27 +19,65 @@ namespace CaseAccountingBusinessLogic.BusinessLogics
private readonly ISpecializationStorage _specializationStorage; private readonly ISpecializationStorage _specializationStorage;
private readonly IHearingStorage _hearingStorage; private readonly IHearingStorage _hearingStorage;
private readonly ILawyerStorage _lawyerStorage; private readonly ILawyerStorage _lawyerStorage;
private readonly WordBuilderProvider _wordBuilder;
private readonly ExcelBuilderProvider _excelBuilder;
private readonly PdfBuilderProvider _pdfBuilder;
private readonly MailSender _mailSender;
public ReportProviderLogic(ICaseStorage caseStorage, ISpecializationStorage specializationStorage, IHearingStorage hearingStorage, ILawyerStorage lawyerStorage) public ReportProviderLogic(ICaseStorage caseStorage, ISpecializationStorage specializationStorage, IHearingStorage hearingStorage,
ILawyerStorage lawyerStorage, WordBuilderProvider wordBuilder, ExcelBuilderProvider excelBuilder,
PdfBuilderProvider pdfBuilder, MailSender mailSender)
{ {
_caseStorage = caseStorage ?? throw new ArgumentNullException(nameof(caseStorage)); _caseStorage = caseStorage ?? throw new ArgumentNullException(nameof(caseStorage));
_specializationStorage = specializationStorage ?? throw new ArgumentNullException(nameof(specializationStorage)); _specializationStorage = specializationStorage ?? throw new ArgumentNullException(nameof(specializationStorage));
_hearingStorage = hearingStorage ?? throw new ArgumentNullException(nameof(hearingStorage)); _hearingStorage = hearingStorage ?? throw new ArgumentNullException(nameof(hearingStorage));
_lawyerStorage = lawyerStorage ?? throw new ArgumentNullException(nameof(lawyerStorage)); _lawyerStorage = lawyerStorage ?? throw new ArgumentNullException(nameof(lawyerStorage));
_wordBuilder = wordBuilder ?? throw new ArgumentNullException(nameof(wordBuilder));
_excelBuilder = excelBuilder ?? throw new ArgumentNullException(nameof(excelBuilder));
_pdfBuilder = pdfBuilder ?? throw new ArgumentNullException(nameof(pdfBuilder));
_mailSender = mailSender ?? throw new ArgumentNullException(nameof(mailSender));
} }
public List<ReportCaseSpecializationViewModel> GetCaseSpecialization(List<CaseViewModel> models) public List<ReportCaseSpecializationViewModel> GetCaseSpecialization(List<CaseViewModel> models)
{ {
var сases = new List<CaseViewModel>(); List<ReportCaseSpecializationViewModel> list = new();
foreach (var model in models) foreach (var model in models)
сases.Add(_caseStorage.GetElement(new CaseSearchModel { Id = model.Id })); {
return сases.Select(x => new ReportCaseSpecializationViewModel { var specialization = _specializationStorage.GetElement(new SpecializationSearchModel { Id = model.SpecializationId });
CaseName = x.Name, var caseModel = _caseStorage.GetElement(new CaseSearchModel { Id = model.Id });
Applicant = x.Applicant, if (specialization == null)
Defendant = x.Defendant, {
Date = x.Date, throw new Exception("Некоректные данные по специализации");
Specialization = x.Specialization, }
}).ToList(); if (caseModel == null)
{
throw new Exception("Некоректные данные по делу");
}
bool hasSpec = false;
if (list.Count > 0)
{
foreach (var report in list)
{
if (hasSpec = report.Specialization.Equals(specialization.Name))
{
report.Cases.Add("Дело #" + caseModel.Id.ToString());
break;
}
}
}
if (!hasSpec)
{
var newElement = new ReportCaseSpecializationViewModel
{
Specialization = specialization.Name,
Cases = new()
};
newElement.Cases.Add("Дело #" + caseModel.Id.ToString());
list.Add(newElement);
}
}
return list;
} }
public List<ReportHearingLawyerViewModel> GetHearingLawyer(ReportBindingModel model) public List<ReportHearingLawyerViewModel> GetHearingLawyer(ReportBindingModel model)
@ -50,35 +90,64 @@ namespace CaseAccountingBusinessLogic.BusinessLogics
{ {
var record = new ReportHearingLawyerViewModel var record = new ReportHearingLawyerViewModel
{ {
Information = hearing.Information, Hearing = "Номер слушания #" + hearing.Id.ToString(),
Date = hearing.Date, CaseLawyers = new()
Lawyers = new List<(string Surname, string Name, string Patronymic)>()
}; };
foreach (var lawyer in _caseStorage.GetElement(new CaseSearchModel { Id = hearing.CaseId }).Lawyers.Values) var caseId = _caseStorage.GetElement(new CaseSearchModel { Id = hearing.CaseId }).Id;
foreach (var lawyer in _lawyerStorage.GetLawyerMTM(caseId))
{ {
record.Lawyers.Add((lawyer.Surname, lawyer.Name, lawyer.Patronymic)); record.CaseLawyers.Add(new CaseLawyerViewModel
{
Case = "Дело #" + caseId.ToString(),
Date = hearing.Date,
Lawyer = lawyer.Surname + " " + lawyer.Name + " " + lawyer.Patronymic
});
} }
list.Add(record); list.Add(record);
} }
return list; return list;
} }
public void SaveCaseSpecializationToExcelFile(ReportBindingModel model) public byte[] SaveListFile(CaseSpecializationListBindingModel model)
{ {
throw new NotImplementedException(); byte[] file = Array.Empty<byte>();
//TODO
string title = "Список специализаций по выбраным делам";
if (model.FileType == "docx")
{
_wordBuilder.CreateDocument();
_wordBuilder.CreateTitle(title);
_wordBuilder.CreateCaseSpecializationTable(GetCaseSpecialization(model.Cases));
file = _wordBuilder.GetFile();
}
else if (model.FileType == "xlsx")
{
_excelBuilder.CreateDocument();
_excelBuilder.CreateTitle(title);
_excelBuilder.CreateCaseSpecializationTable(GetCaseSpecialization(model.Cases));
file = _excelBuilder.GetFile();
}
return file;
} }
public void SaveCaseSpecializationToWordFile(ReportBindingModel model) public void SendByMailStatusReport(ReportBindingModel reportModel)
{ {
throw new NotImplementedException(); byte[] file = _pdfBuilder.GetHearingLawyerReportFile(new()
//TODO
}
public void SaveHearingLawyerToPdfFile(ReportBindingModel model)
{ {
throw new NotImplementedException(); Title = "Отчет по слушаниям",
//TODO DateFrom = reportModel.DateFrom,
DateTo = reportModel.DateTo,
Records = GetHearingLawyer(reportModel)
});
_mailSender.SendMailAsync(new()
{
MailAddress = reportModel.UserEmail,
Subject = "Отчет по слушаниям",
Text = $"За период с {reportModel.DateFrom.ToShortDateString()} " +
$"по {reportModel.DateTo.ToShortDateString()}.",
File = file
});
} }
} }
} }

View File

@ -9,6 +9,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" /> <PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -19,7 +20,9 @@
<ItemGroup> <ItemGroup>
<Folder Include="OfficePackage\HelperEnums\" /> <Folder Include="OfficePackage\HelperEnums\" />
<Folder Include="OfficePackage\Implements\" /> <Folder Include="OfficePackage\HelperModels\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,357 @@
using CaseAccountingBusinessLogic.OfficePackage;
using CaseAccountingBusinessLogic.OfficePackage.HelperModels;
using CaseAccountingContracts.ViewModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CaseAccountingBusinessLogic.OfficePackage
{
public class ExcelBuilderProvider
{
private readonly string tempFileName = "temp.xlsx";
private SpreadsheetDocument? spreadsheetDocument;
private SharedStringTablePart? shareStringPart;
private Worksheet? worksheet;
private void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fonts.Append(fontUsual);
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 12D });
fonts.Append(fontTitle);
var fills = new Fills() { Count = 3U };
var fill1 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
var fill3 = new Fill();
fill3.Append(new PatternFill()
{
PatternType = PatternValues.Solid,
ForegroundColor = new()
{
Rgb = "e0e8ff"
}
});
var fill4 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
fills.Append(fill1);
fills.Append(fill2);
fills.Append(fill3);
fills.Append(fill4);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
CellFormats cellFormats = new() { Count = 4U };
CellFormat cellFormatEmpty = new()
{
FontId = 0U,
FillId = 0U,
BorderId = 1U,
ApplyFont = true
};
CellFormat cellFormatDefault = new()
{
FontId = 0U,
FillId = 3U,
BorderId = 1U,
ApplyFont = true
};
CellFormat cellFormatTitle = new()
{
FontId = 1U,
FillId = 2U,
BorderId = 1U,
ApplyFont = true,
ApplyBorder = true,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
Horizontal = HorizontalAlignmentValues.Center,
WrapText = true
}
};
cellFormats.Append(cellFormatEmpty);
cellFormats.Append(cellFormatDefault);
cellFormats.Append(cellFormatTitle);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellFormats);
}
public void CreateDocument()
{
spreadsheetDocument = SpreadsheetDocument.Create(tempFileName,
SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
shareStringPart = spreadsheetDocument.WorkbookPart!
.GetPartsOfType<SharedStringTablePart>()
.Any()
? spreadsheetDocument.WorkbookPart
.GetPartsOfType<SharedStringTablePart>()
.First()
: spreadsheetDocument.WorkbookPart
.AddNewPart<SharedStringTablePart>();
if (shareStringPart.SharedStringTable == null)
{
shareStringPart.SharedStringTable = new SharedStringTable();
}
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
worksheet = worksheetPart.Worksheet;
}
public void InsertCellInWorksheet(ExcelCellData cellData)
{
if (worksheet == null || shareStringPart == null)
{
return;
}
var sheetData = worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
Row? row = sheetData.Elements<Row>()
.Where(r => r.RowIndex! == cellData.RowIndex)
.FirstOrDefault();
if (row == null)
{
row = new Row() { RowIndex = cellData.RowIndex };
sheetData.Append(row);
}
Cell? cell = row.Elements<Cell>()
.Where(c => c.CellReference!.Value == cellData.CellReference)
.FirstOrDefault();
if (cell == null)
{
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, cellData.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference = cellData.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(cellData.Text)));
shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = cellData.StyleIndex;
}
private void MergeCells(ExcelMergeParameters excelParams)
{
if (worksheet == null)
{
return;
}
MergeCells mergeCells;
if (worksheet.Elements<MergeCells>().Any())
{
mergeCells = worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (worksheet.Elements<CustomSheetView>().Any())
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<CustomSheetView>().First());
}
else
{
worksheet.InsertAfter(mergeCells, worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
private void Save()
{
if (spreadsheetDocument == null)
{
return;
}
spreadsheetDocument.WorkbookPart!.Workbook.Save();
spreadsheetDocument.Dispose();
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public void CreateTitle(string text)
{
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "B1"
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = 1,
Text = text,
StyleIndex = 0
});
}
public void CreateCaseSpecializationTable(List<ReportCaseSpecializationViewModel> data)
{
if (worksheet == null || shareStringPart == null)
{
return;
}
Columns columns = new();
Column columnA = new() { Min = 1, Max = 1, Width = 30, CustomWidth = true };
columns.Append(columnA);
Column columnB = new() { Min = 2, Max = 2, Width = 30, CustomWidth = true };
columns.Append(columnB);
worksheet.InsertAt(columns, 0);
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = 2,
Text = "Специализация:",
StyleIndex = 2
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = 2,
Text = "Дела:",
StyleIndex = 2
});
uint currentRow = 3;
foreach (ReportCaseSpecializationViewModel specialization in data)
{
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = currentRow,
Text = specialization.Specialization,
StyleIndex = 1
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = currentRow,
Text = "",
StyleIndex = 1
});
currentRow++;
foreach (string caseName in specialization.Cases)
{
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "A",
RowIndex = currentRow,
Text = "",
StyleIndex = 1
});
InsertCellInWorksheet(new ExcelCellData
{
ColumnName = "B",
RowIndex = currentRow,
Text = caseName,
StyleIndex = 1
});
currentRow++;
}
}
}
}
}

View File

@ -4,7 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ComputersShopBusinessLogic.OfficePackage.HelperEnums namespace CaseAccountingBusinessLogic.OfficePackage.HelperEnums
{ {
public enum ExcelStyleInfoType public enum ExcelStyleInfoType
{ {

View File

@ -4,7 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ComputersShopBusinessLogic.OfficePackage.HelperEnums namespace CaseAccountingBusinessLogic.OfficePackage.HelperEnums
{ {
public enum PdfParagraphAlignmentType public enum PdfParagraphAlignmentType
{ {

View File

@ -4,7 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace ComputersShopBusinessLogic.OfficePackage.HelperEnums namespace CaseAccountingBusinessLogic.OfficePackage.HelperEnums
{ {
public enum WordJustificationType public enum WordJustificationType
{ {

View File

@ -1,4 +1,4 @@
using ComputersShopBusinessLogic.OfficePackage.HelperEnums; using CaseAccountingBusinessLogic.OfficePackage.HelperEnums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;

View File

@ -1,4 +1,4 @@
using ComputersShopBusinessLogic.OfficePackage.HelperEnums; using CaseAccountingBusinessLogic.OfficePackage.HelperEnums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;

View File

@ -1,4 +1,4 @@
using ComputersShopBusinessLogic.OfficePackage.HelperEnums; using CaseAccountingBusinessLogic.OfficePackage.HelperEnums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;

View File

@ -1,4 +1,4 @@
using ComputersShopBusinessLogic.OfficePackage.HelperEnums; using CaseAccountingBusinessLogic.OfficePackage.HelperEnums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;

View File

@ -0,0 +1,183 @@
using CaseAccountingBusinessLogic.OfficePackage;
using CaseAccountingBusinessLogic.OfficePackage.HelperEnums;
using CaseAccountingBusinessLogic.OfficePackage.HelperModels;
using CaseAccountingContracts.ViewModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using PdfSharp.Pdf;
using System.Text;
namespace CaseAccountingBusinessLogic.BusinessLogic.OfficePackage
{
public class PdfBuilderProvider
{
private readonly string tempFileName = "temp.pdf";
private Document? document;
private Section? section;
private Table? table;
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
_ => ParagraphAlignment.Justify,
};
}
private void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
public void CreateDocument()
{
document = new Document();
DefineStyles(document);
section = document.AddSection();
}
public void CreateParagraph(PdfParagraph pdfParagraph)
{
if (section == null)
{
return;
}
var paragraph = section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
public void CreateTable(List<string> columns)
{
if (document == null)
{
return;
}
table = document.LastSection.AddTable();
foreach (var elem in columns)
{
table.AddColumn(elem);
}
}
public void CreateRow(PdfRowParameters rowParameters)
{
if (table == null)
{
return;
}
var row = table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
private void Save()
{
// Регистрация провайдера кодировки для кодировки 1252, без этого ошибОчка была
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true)
{
Document = document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(tempFileName);
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public byte[] GetHearingLawyerReportFile(PdfData<ReportHearingLawyerViewModel> data)
{
CreateDocument();
CreateParagraph(new PdfParagraph
{
Text = data.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"за период с {data.DateFrom.ToShortDateString()} " +
$"по {data.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "4cm","5cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер слушания", "Дело", "Дата проведения", "Юрист" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var record in data.Records)
{
List<CaseLawyerViewModel> casesAndLawyes = record.CaseLawyers;
int recordHeight = casesAndLawyes.Count + 1;
for (int i = 0; i < recordHeight; i++)
{
List<string> cellsData = new() { "", "", "", "" };
if (i == 0)
{
cellsData[0] = record.Hearing;
CreateRow(new PdfRowParameters
{
Texts = cellsData,
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
continue;
}
int k = i - 1;
if (k < casesAndLawyes.Count)
{
cellsData[1] = casesAndLawyes[k].Case;
cellsData[2] = casesAndLawyes[k].Date.ToString("yyyy-MM-dd");
cellsData[3] = casesAndLawyes[k].Lawyer;
}
CreateRow(new PdfRowParameters
{
Texts = cellsData,
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
return GetFile();
}
}
}

View File

@ -0,0 +1,170 @@
using CaseAccountingBusinessLogic.OfficePackage.HelperModels;
using CaseAccountingContracts.ViewModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace CaseAccountingBusinessLogic.OfficePackage
{
public class WordBuilderProvider
{
private readonly string tempFileName = "temp.docx";
private WordprocessingDocument? wordDocument;
private Body? documentBody;
public void CreateDocument()
{
wordDocument = WordprocessingDocument.Create(tempFileName,
WordprocessingDocumentType.Document);
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
documentBody = mainPart.Document.AppendChild(new Body());
}
public void CreateParagraph(string text)
{
if (documentBody == null)
{
return;
}
Paragraph paragraph = new();
Run run = new();
run.AppendChild(new Text
{
Text = text
});
paragraph.AppendChild(run);
documentBody.AppendChild(paragraph);
}
public void CreateTitle(string text)
{
if (documentBody == null)
{
return;
}
Paragraph paragraph = new();
Run run = new();
RunProperties properties = new();
properties.AppendChild(new Bold());
run.AppendChild(properties);
run.AppendChild(new Text
{
Text = text
});
paragraph.AppendChild(run);
documentBody.AppendChild(paragraph);
}
private TableCell CreateTableCell(string text, bool inHead = false, int? cellWidth = null)
{
Run run = new();
TableCell tableCell = new();
TableCellProperties cellProperties = new()
{
TableCellWidth = new()
{
Width = cellWidth.ToString()
},
TableCellMargin = new()
{
LeftMargin = new()
{
Width = "100"
}
}
};
if (inHead)
{
Shading shading = new()
{
Color = "auto",
Fill = "e0e8ff",
Val = ShadingPatternValues.Clear
};
cellProperties.Append(shading);
RunProperties properties = new();
properties.AppendChild(new Bold());
run.AppendChild(properties);
}
run.AppendChild(new Text
{
Text = text
});
Paragraph paragraph = new(run);
tableCell.AppendChild(paragraph);
tableCell.Append(cellProperties);
return tableCell;
}
protected void CreateTable(WordTableData tableData)
{
if (documentBody == null || tableData == null)
{
return;
}
var table = new Table();
TableProperties tableProperties = new(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 3 }
)
);
table.AppendChild(tableProperties);
table.Append(new TableRow(tableData.Columns.Select(x => CreateTableCell(x.Item1, true, x.Item2))));
table.Append(tableData.Rows.Select(x => new TableRow(x.Select(y => CreateTableCell(y)))));
documentBody.AppendChild(table);
}
private void Save()
{
if (documentBody == null || wordDocument == null)
{
return;
}
wordDocument.MainDocumentPart!.Document.Save();
wordDocument.Dispose();
}
public byte[] GetFile()
{
Save();
byte[] file = File.ReadAllBytes(tempFileName);
File.Delete(tempFileName);
return file;
}
public void CreateCaseSpecializationTable(List<ReportCaseSpecializationViewModel> data)
{
List<List<string>> rows = new();
foreach (ReportCaseSpecializationViewModel specializationl in data)
{
List<string> specializationlCells = new() { specializationl.Specialization, "" };
rows.Add(specializationlCells);
List<string> caseCells;
foreach (string caseString in specializationl.Cases)
{
caseCells = new() { "", caseString };
rows.Add(caseCells);
}
}
WordTableData wordTable = new()
{
Columns = new List<(string, int)>()
{
("Специализация", 3000),
("Дела", 3000)
},
Rows = rows
};
CreateTable(wordTable);
}
}
}

View File

@ -0,0 +1,15 @@
using CaseAccountingContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaseAccountingContracts.BindingModels
{
public class CaseSpecializationListBindingModel
{
public string FileType { get; set; } = string.Empty;
public List<CaseViewModel> Cases { get; set; } = new();
}
}

View File

@ -25,12 +25,17 @@ namespace CaseAccountingContracts.BindingModels
public List<CaseViewModel> CaseViewModels { get; set; } = new(); public List<CaseViewModel> CaseViewModels { get; set; } = new();
public Dictionary<int, IContractModel> Contracts { get; set; } = new();
public List<ContractViewModel> ContractViewModels { get; set; } = new();
public DealBindingModel() { } public DealBindingModel() { }
[JsonConstructor] [JsonConstructor]
public DealBindingModel(Dictionary<int, CaseViewModel> Cases) public DealBindingModel(Dictionary<int, CaseViewModel> Cases, Dictionary<int, ContractViewModel> Contracts)
{ {
this.Cases = Cases.ToDictionary(x => x.Key, x => (ICaseModel)x.Value); this.Cases = Cases.ToDictionary(x => x.Key, x => (ICaseModel)x.Value);
this.Contracts = Contracts.ToDictionary(x => x.Key, x => (IContractModel)x.Value);
} }
} }
} }

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaseAccountingContracts.BindingModels
{
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaseAccountingContracts.BindingModels
{
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
public byte[] File { get; set; } = Array.Empty<byte>();
}
}

View File

@ -9,12 +9,9 @@ namespace CaseAccountingContracts.BindingModels
{ {
public class ReportBindingModel public class ReportBindingModel
{ {
public string FileName { get; set; } = string.Empty; public string UserEmail { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime? DateFrom { get; set; } public DateTime DateTo { get; set; }
public DateTime? DateTo { get; set; }
public int? UserId { get; set; } public int? UserId { get; set; }
} }
} }

View File

@ -16,5 +16,6 @@ namespace CaseAccountingContracts.BusinessLogicContracts
bool Create(CaseBindingModel model); bool Create(CaseBindingModel model);
bool Update(CaseBindingModel model); bool Update(CaseBindingModel model);
bool Delete(CaseBindingModel model); bool Delete(CaseBindingModel model);
List<SpecializationCasesViewModel> GetSpecializationCases();
} }
} }

View File

@ -14,10 +14,8 @@ namespace CaseAccountingContracts.BusinessLogicContracts
List<ReportHearingLawyerViewModel> GetHearingLawyer(ReportBindingModel model); List<ReportHearingLawyerViewModel> GetHearingLawyer(ReportBindingModel model);
void SaveCaseSpecializationToWordFile(ReportBindingModel model); byte[] SaveListFile(CaseSpecializationListBindingModel model);
void SaveCaseSpecializationToExcelFile(ReportBindingModel model); void SendByMailStatusReport(ReportBindingModel reportModel);
void SaveHearingLawyerToPdfFile(ReportBindingModel model);
} }
} }

View File

@ -19,5 +19,6 @@ namespace CaseAccountingContracts.StoragesContracts
CaseViewModel? Delete(CaseBindingModel model); CaseViewModel? Delete(CaseBindingModel model);
List<HearingViewModel> GetCaseHearings(CaseSearchModel model); List<HearingViewModel> GetCaseHearings(CaseSearchModel model);
List<SpecializationCasesViewModel>? GetSpecializationCases();
} }
} }

View File

@ -19,5 +19,6 @@ namespace CaseAccountingContracts.StoragesContracts
LawyerViewModel? Delete(LawyerBindingModel model); LawyerViewModel? Delete(LawyerBindingModel model);
List<CaseViewModel> GetLawyerCases(LawyerSearchModel model); List<CaseViewModel> GetLawyerCases(LawyerSearchModel model);
List<LawyerViewModel> GetLawyerMTM(int caseId);
} }
} }

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaseAccountingContracts.ViewModels
{
public class CaseLawyerViewModel
{
public string Case { get; set; } = string.Empty;
public DateTime Date { get; set; }
public string Lawyer { get; set; } = string.Empty;
}
}

View File

@ -8,10 +8,7 @@ namespace CaseAccountingContracts.ViewModels
{ {
public class ReportCaseSpecializationViewModel public class ReportCaseSpecializationViewModel
{ {
public string CaseName { get; set; } = string.Empty;
public string Applicant { get; set; } = string.Empty;
public string Defendant { get; set; } = string.Empty;
public DateTime Date { get; set; }
public string Specialization { get; set; } = string.Empty; public string Specialization { get; set; } = string.Empty;
public List<string> Cases { get; set; } = new();
} }
} }

View File

@ -8,8 +8,7 @@ namespace CaseAccountingContracts.ViewModels
{ {
public class ReportHearingLawyerViewModel public class ReportHearingLawyerViewModel
{ {
public string Information { get; set; } = string.Empty; public string Hearing { get; set; } = string.Empty;
public DateTime Date { get; set; } public List<CaseLawyerViewModel> CaseLawyers { get; set; } = new();
public List<(string Surname, string Name, string Patronymic)> Lawyers { get; set; } = new();
} }
} }

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaseAccountingContracts.ViewModels
{
public class SpecializationCasesViewModel
{
public int Count { get; set; }
public string Name { get; set; } = string.Empty;
}
}

View File

@ -102,14 +102,14 @@ namespace CaseAccountingCustomerView.Controllers
} }
[HttpPost] [HttpPost]
public int[]? HearingLawyerList([FromBody] LawyerHearingListBindingModel listModel) public int[]? SpecializationCaselist([FromBody] LawyerHearingListBindingModel listModel)
{ {
if (APIUser.User == null) if (APIUser.User == null)
{ {
return Array.Empty<int>(); return Array.Empty<int>();
} }
byte[]? file = APIUser.PostRequestWithResult<LawyerHearingListBindingModel, byte[]> byte[]? file = APIUser.PostRequestWithResult<LawyerHearingListBindingModel, byte[]>
("api/reportcustomer/lawyerhearinglist", listModel); ("api/reportprovider/specializationcaselist", listModel);
return file!.Select(b => (int)b).ToArray(); return file!.Select(b => (int)b).ToArray();
} }

View File

@ -61,6 +61,13 @@ namespace CaseAccountingCustomerView.Controllers
dict.Add(element.Id, _case); dict.Add(element.Id, _case);
} }
lawyerModel.Cases = dict; lawyerModel.Cases = dict;
var dictContr = new Dictionary<int, IContractModel>();
foreach (var element in lawyerModel.ContractViewModels)
{
var contract = APIUser.GetRequest<ContractViewModel>($"api/contract/get?id={element.Id}");
dictContr.Add(element.Id, contract);
}
lawyerModel.Contracts = dictContr;
APIUser.PostRequest("api/lawyer/update", lawyerModel); APIUser.PostRequest("api/lawyer/update", lawyerModel);
Response.Redirect("/Home/Lawyers"); Response.Redirect("/Home/Lawyers");
} }

View File

@ -1,7 +1,9 @@
const createBtn = document.getElementById("create-button"); const createBtn = document.getElementById("create-button");
const tbody = document.getElementById("scrollable-table__tbody"); const tbody = document.getElementById("scrollable-table__tbody");
const serviceInput = document.getElementById("service-input"); const nameInput = document.getElementById("name-input")
const coastInput = document.getElementById("coast-input"); const surnameInput = document.getElementById("surname-input")
const patronymicInput = document.getElementById("patronymic-input")
const experienceInput = document.getElementById("experience-input")
const currentLawyerId = document.getElementById("lawyer-id").dataset.id; const currentLawyerId = document.getElementById("lawyer-id").dataset.id;
var contracts = []; var contracts = [];
var dataArray = []; var dataArray = [];
@ -17,7 +19,7 @@ window.addEventListener('load', async () => {
}); });
console.log(currentLawyerId) console.log(currentLawyerId)
await $.ajax({ await $.ajax({
url: "/lawyers/get?id=${currentLawyerId}", url: `/lawyers/get?id=${currentLawyerId}`,
type: "GET", type: "GET",
contentType: "json" contentType: "json"
}).done((result) => { }).done((result) => {
@ -36,23 +38,25 @@ window.addEventListener('load', async () => {
cell.textContent = value; cell.textContent = value;
}); });
console.log(currentLawyer); console.log(currentLawyer);
if (currentLawyer.ContractViewModels.find(x => parseInt(x.id) === parseInt(contract.id))) { /*if (currentLawyer.сontractViewModels.find(x => parseInt(x.id) === parseInt(contract.id))) {
row.classList.add("bg-success"); row.classList.add("bg-success");
dataArray.push(contract); dataArray.push(contract);
} }*/
row.addEventListener('click', () => addAndRemoveFromList(row)); row.addEventListener('click', () => addAndRemoveFromList(row));
}); });
}) })
createBtn.addEventListener('click', () => { createBtn.addEventListener('click', () => {
console.log(dataArray);
var lawyerCasesUpdate = { var lawyerCasesUpdate = {
"Id": currentLawyer.id, "Id": currentLawyerId,
"Service": serviceInput.value, "Name": nameInput.value,
"Coast": coastInput.value, "Surname": surnameInput.value,
"Date": currentLawyer.date, "Patronymic": patronymicInput.value,
"ContractViewModels": dataArray, "Experience": parseInt(experienceInput.value),
"LawyerCases": currentLawyer.lawyerCases, "SpecializationId": parseInt(currentLawyer.specializationId),
"ContractViewModels": dataArray
} }
$.ajax({ $.ajax({
url: "/lawyers/update", url: "/lawyers/update",

View File

@ -1,5 +1,4 @@
const updateBtn = const updateBtn = document.getElementById("update-button");
.getElementById("update-button");
const nameInput = document.getElementById("name-input") const nameInput = document.getElementById("name-input")
const specializationId = document.getElementById("spec-id").dataset.id const specializationId = document.getElementById("spec-id").dataset.id

View File

@ -158,7 +158,7 @@ namespace CaseAccountingDataBaseImplement.Implements
{ {
return null; return null;
} }
_case.Update(model); _case.Update(context, model);
context.SaveChanges(); context.SaveChanges();
_case.UpdateLawyers(context, model); _case.UpdateLawyers(context, model);
transaction.Commit(); transaction.Commit();
@ -185,5 +185,22 @@ namespace CaseAccountingDataBaseImplement.Implements
return hearings; return hearings;
} }
public List<SpecializationCasesViewModel>? GetSpecializationCases()
{
using var context = new CaseAccountingDatabase();
var result = context.Specializations
.GroupJoin(
context.Cases,
status => status.Id,
caseModel => caseModel.SpecializationId,
(status, caseModels) => new SpecializationCasesViewModel
{
Name = status.Name,
Count = caseModels.Count()
})
.ToList();
return result;
}
} }
} }

View File

@ -115,9 +115,9 @@ namespace CaseAccountingDataBaseImplement.Implements
{ {
return null; return null;
} }
deal.Update(model); deal.Update(context, model);
context.SaveChanges(); context.SaveChanges();
deal.UpdateCases(context, model); if(model.Cases.Count > 0) deal.UpdateCases(context, model);
transaction.Commit(); transaction.Commit();
return deal.GetViewModel; return deal.GetViewModel;
} }

View File

@ -129,7 +129,7 @@ namespace CaseAccountingDataBaseImplement.Implements
{ {
return null; return null;
} }
hearing.Update(model); hearing.Update(context, model);
context.SaveChanges(); context.SaveChanges();
return context.Hearings return context.Hearings
.Include(x => x.Case) .Include(x => x.Case)

View File

@ -89,6 +89,20 @@ namespace CaseAccountingDataBaseImplement.Implements
.Select(x => x.GetViewModel).ToList(); .Select(x => x.GetViewModel).ToList();
} }
public List<LawyerViewModel> GetLawyerMTM(int caseId)
{
using var context = new CaseAccountingDatabase();
var lawyersId = context.CaseLawyers
.Where(x => x.CaseId == caseId)
.Select(x => x.LawyerId).ToList();
return context.Lawyers
.Include(x => x.Specialization)
.Include(x => x.User)
.Where(X => lawyersId.Contains(X.Id))
.Select(x => x.GetViewModel)
.ToList();
}
public LawyerViewModel? Insert(LawyerBindingModel model) public LawyerViewModel? Insert(LawyerBindingModel model)
{ {
using var context = new CaseAccountingDatabase(); using var context = new CaseAccountingDatabase();

View File

@ -87,15 +87,19 @@ namespace CaseAccountingDataBaseImplement.Models
}; };
} }
public void Update(CaseBindingModel model) public void Update(CaseAccountingDatabase context, CaseBindingModel model)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
Name = model.Name; Name = model.Name;
Applicant = model.Applicant;
Defendant = model.Defendant;
SpecializationId = model.SpecializationId;
Specialization = context.Specializations.FirstOrDefault(x => x.Id == model.SpecializationId) ?? throw new Exception("Specialization не существует");
Annotation = model.Annotation; Annotation = model.Annotation;
Date = model.Date; Date = DateTime.SpecifyKind(model.Date, DateTimeKind.Utc);
} }
public void UpdateLawyers(CaseAccountingDatabase context, CaseBindingModel model) public void UpdateLawyers(CaseAccountingDatabase context, CaseBindingModel model)

View File

@ -72,7 +72,7 @@ namespace CaseAccountingDataBaseImplement.Models
}; };
} }
public void Update(DealBindingModel? model) public void Update(CaseAccountingDatabase context, DealBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
@ -80,7 +80,14 @@ namespace CaseAccountingDataBaseImplement.Models
} }
Subject = model.Subject; Subject = model.Subject;
Responsibilities = model.Responsibilities; Responsibilities = model.Responsibilities;
Date = model.Date; Date = DateTime.SpecifyKind(model.Date, DateTimeKind.Utc);
if (model.Contracts.Count > 0)
{
Contracts = model.Contracts.Select(x => new DealContract
{
Contract = context.Contracts.First(y => y.Id == x.Key)
}).ToList();
}
} }
public void UpdateCases(CaseAccountingDatabase context, DealBindingModel model) public void UpdateCases(CaseAccountingDatabase context, DealBindingModel model)

View File

@ -47,14 +47,16 @@ namespace CaseAccountingDataBaseImplement.Models
}; };
} }
public void Update (HearingBindingModel? model) public void Update (CaseAccountingDatabase context, HearingBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
Information = model.Information; Information = model.Information;
Date = model.Date; CaseId = model.CaseId;
Case = context.Cases.FirstOrDefault(x => x.Id == model.CaseId) ?? throw new Exception("Case не существует");
DateTime.SpecifyKind(model.Date, DateTimeKind.Utc);
} }
public HearingViewModel GetViewModel => new() public HearingViewModel GetViewModel => new()

View File

@ -114,6 +114,13 @@ namespace CaseAccountingDataBaseImplement.Models
Case = context.Cases.First(y => y.Id == x.Key) Case = context.Cases.First(y => y.Id == x.Key)
}).ToList(); }).ToList();
} }
if (model.Contracts.Count > 0)
{
LawyerContracts = model.Contracts.Select(x => new LawyerContract
{
Contract = context.Contracts.First(y => y.Id == x.Key)
}).ToList();
}
} }
public void UpdateContracts(CaseAccountingDatabase context, LawyerBindingModel model) public void UpdateContracts(CaseAccountingDatabase context, LawyerBindingModel model)

View File

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

View File

@ -129,5 +129,15 @@ namespace CaseAccountingProviderView.Controllers
List<SpecializationViewModel>? specializationModel = APIUser.GetRequest<List<SpecializationViewModel>>($"api/case/getallspecializations"); List<SpecializationViewModel>? specializationModel = APIUser.GetRequest<List<SpecializationViewModel>>($"api/case/getallspecializations");
return specializationModel ?? new(); return specializationModel ?? new();
} }
public List<SpecializationCasesViewModel> GetSpecializationCases()
{
if (APIUser.User == null)
{
return new();
}
List<SpecializationCasesViewModel>? specializationCases = APIUser.GetRequest<List<SpecializationCasesViewModel>>($"api/case/getspecializationcases");
return specializationCases ?? new();
}
} }
} }

View File

@ -53,6 +53,13 @@ namespace CaseAccountingProviderView.Controllers
throw new Exception("403"); throw new Exception("403");
} }
dealModel.UserId = APIUser.User.Id; dealModel.UserId = APIUser.User.Id;
var contractdict = new Dictionary<int, IContractModel>();
foreach (var element in dealModel.ContractViewModels)
{
var contractModel = APIUser.GetRequest<ContractViewModel>($"api/contract/get?id={element.Id}");
contractdict.Add(element.Id, contractModel);
}
dealModel.Contracts = contractdict;
APIUser.PostRequest("api/deal/update", dealModel); APIUser.PostRequest("api/deal/update", dealModel);
Response.Redirect("/Home/Deals"); Response.Redirect("/Home/Deals");
} }
@ -127,5 +134,15 @@ namespace CaseAccountingProviderView.Controllers
DealViewModel? dealModel = APIUser.GetRequest<DealViewModel>($"api/deal/get?id={id}"); DealViewModel? dealModel = APIUser.GetRequest<DealViewModel>($"api/deal/get?id={id}");
return dealModel; return dealModel;
} }
public List<ContractViewModel> GetAllContracts()
{
if (APIUser.User == null)
{
return new();
}
List<ContractViewModel>? contractModel = APIUser.GetRequest<List<ContractViewModel>>($"api/deal/getallcontracts");
return contractModel ?? new();
}
} }
} }

View File

@ -35,6 +35,59 @@ namespace CaseAccountingProviderView.Controllers
return View(); return View();
} }
public IActionResult SpecializationCaselist()
{
return View();
}
public IActionResult Diagram()
{
return View();
}
[HttpPost]
public int[]? SpecializationCaselist([FromBody] CaseSpecializationListBindingModel listModel)
{
if (APIUser.User == null)
{
return Array.Empty<int>();
}
byte[]? file = APIUser.PostRequestWithResult<CaseSpecializationListBindingModel, byte[]>
("api/reportcustomer/lawyerhearinglist", listModel);
return file!.Select(b => (int)b).ToArray();
}
public IActionResult GetReport()
{
return View();
}
[HttpPost]
public List<ReportHearingLawyerViewModel>? GetReport([FromBody] ReportBindingModel reportModel)
{
if (APIUser.User == null)
{
return new();
}
reportModel.UserId = APIUser.User.Id;
reportModel.UserEmail = APIUser.User.Login;
List<ReportHearingLawyerViewModel>? list = APIUser.PostRequestWithResult<ReportBindingModel, List<ReportHearingLawyerViewModel>>
("api/reportprovider/getreportdata", reportModel);
return list;
}
[HttpPost]
public void SendByMailStatusReport([FromBody] ReportBindingModel reportModel)
{
if (APIUser.User == null)
{
return;
}
reportModel.UserId = APIUser.User.Id;
reportModel.UserEmail = APIUser.User.Login;
APIUser.PostRequest("api/reportprovider/sendbymailstatusreport", reportModel);
}
[HttpPost] [HttpPost]
public void Login(string login, string password) public void Login(string login, string password)
{ {
@ -73,15 +126,8 @@ namespace CaseAccountingProviderView.Controllers
{ {
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
/*if (page == 0)
{
page = 1;
}*/
ViewBag.Cases = APIUser.GetRequest<List<CaseViewModel>> ViewBag.Cases = APIUser.GetRequest<List<CaseViewModel>>
($"api/case/getallbyuser?userId={APIUser.User.Id}"); ($"api/case/getallbyuser?userId={APIUser.User.Id}");
/*ViewBag.Page = page;
ViewBag.NumberOfPages = APIUser.GetRequest<int>
($"api/student/getnumberofpages?userId={APIUser.User.Id}");*/
return View(); return View();
} }

View File

@ -6,7 +6,7 @@
<div id="error-div-shell" class="error-div-shell mb-2"> <div id="error-div-shell" class="error-div-shell mb-2">
<div> <div>
<p id="error-p" class="error-p"></p> <p id="error-p" class="error-p text-danger"></p>
</div> </div>
</div> </div>

View File

@ -14,7 +14,7 @@
<div id="error-div-shell" class="error-div-shell mb-2"> <div id="error-div-shell" class="error-div-shell mb-2">
<div> <div>
<p id="error-p" class="error-p"></p> <p id="error-p" class="error-p text-danger"></p>
</div> </div>
</div> </div>

View File

@ -0,0 +1,37 @@
@{
ViewData["Title"] = "Договор";
}
@{
<h4 id="deal-data" class="fw-bold" data-id="@ViewBag.Deal.Id">Привязка контракта к договору</h4>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<p class="mb-0">Номер:</p>
<input type="text" readonly value="@ViewBag.Deal.Id" id="name-input" name="name" class="form-control mb-3" />
<div>
<div class="scrollable-table">
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>Услуга:</th>
<th>Цена:</th>
<th>Дата:</th>
</tr>
</thead>
<tbody id="scrollable-table__tbody">
</tbody>
</table>
</div>
</div>
<button id="save-button" type="button" class="btn btn-primary text-button">
Сохранить привязку
</button>
}
<script src="~/js/deal/deal-bind.js" asp-append-version="true"></script>

View File

@ -6,7 +6,7 @@
<div id="error-div-shell" class="error-div-shell mb-2"> <div id="error-div-shell" class="error-div-shell mb-2">
<div> <div>
<p id="error-p" class="error-p"></p> <p id="error-p" class="error-p text-danger"></p>
</div> </div>
</div> </div>

View File

@ -14,7 +14,7 @@
<div id="error-div-shell" class="error-div-shell mb-2"> <div id="error-div-shell" class="error-div-shell mb-2">
<div> <div>
<p id="error-p" class="error-p"></p> <p id="error-p" class="error-p text-danger"></p>
</div> </div>
</div> </div>

View File

@ -6,7 +6,7 @@
<div id="error-div-shell" class="error-div-shell mb-2"> <div id="error-div-shell" class="error-div-shell mb-2">
<div> <div>
<p id="error-p" class="error-p"></p> <p id="error-p" class="error-p text-danger"></p>
</div> </div>
</div> </div>

View File

@ -14,7 +14,7 @@
<div id="error-div-shell" class="error-div-shell mb-2"> <div id="error-div-shell" class="error-div-shell mb-2">
<div> <div>
<p id="error-p" class="error-p"></p> <p id="error-p" class="error-p text-danger"></p>
</div> </div>
</div> </div>

View File

@ -28,6 +28,9 @@
<th> <th>
Дата составления Дата составления
</th> </th>
<th>
Привязать запись
</th>
<th> <th>
Изменить запись Изменить запись
</th> </th>
@ -49,6 +52,9 @@
<td> <td>
@item.Date.ToString("yyyy-MM-dd") @item.Date.ToString("yyyy-MM-dd")
</td> </td>
<td>
<a id="update-button-@item.Id" class="btn btn-primary" asp-controller="Deal" asp-action="Bind" asp-route-id="@item.Id">Привязка</a>
</td>
<td> <td>
<a id="update-button-@item.Id" class="btn btn-warning" asp-controller="Deal" asp-action="Update" asp-route-id="@item.Id">Изменить</a> <a id="update-button-@item.Id" class="btn btn-warning" asp-controller="Deal" asp-action="Update" asp-route-id="@item.Id">Изменить</a>
</td> </td>

View File

@ -0,0 +1,15 @@

<div class="text-center">
<h1 class="display-4">Круговая диаграмма</h1>
</div>
<div class="container">
<button class="btn btn-success mt-4" id="btnStatus">Статистика по специализации дел</button>
<div class="container col-8 mt-4">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="~/js/diagram/diagram.js" asp-append-version="true"></script>

View File

@ -0,0 +1,55 @@
@{
ViewData["Title"] = "Отчет";
}
<div class="text-center">
<h1 class="display-4">Отчет по слушаниям</h1>
</div>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<div class="d-flex flex-wrap gap-1 align-items-end mb-2">
<div class="mb-2">
<p class="mb-0">Дата начала:</p>
<input id="date-from-input" class="form-control" type="date" />
</div>
<div class="mb-2">
<p class="mb-0">Дата конца:</p>
<input id="date-to-input" class="form-control" type="date" />
</div>
<button id="generate-button" class="btn btn-primary mb-2">
Показать
</button>
<button id="send-by-mail-button" class="btn btn-primary mb-2">
На почту
</button>
</div>
<p class="mb-0">
<span>За период с&nbsp;</span>
<span id="date-from-span" class="fw-bold">...</span>
<span>&nbsp;по&nbsp;</span>
<span id="date-to-span" class="fw-bold">...</span>
</p>
<div class="table-shell mb-2 border">
<table class="table mb-0">
<thead class="table-head">
<tr>
<th>Номер слушания</th>
<th>Дело</th>
<th>Дата проведения</th>
<th>Юрист</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<div id="table"></div>
<script src="~/js/report/reportpdf.js" asp-append-version="true"></script>

View File

@ -0,0 +1,42 @@
@{
ViewData["Title"] = "Список специализаций по делам";
}
<h4 class="fw-bold">Список специализаций по делам</h4>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<select id="file-type" class="form-control mb-3">
<option>docx</option>
<option>xlsx</option>
</select>
<button id="create-button" type="button" class="btn btn-success text-button">
Сохранить результат
</button>
<div>
<div class="scrollable-table">
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>Номер дела:</th>
<th>Истец:</th>
<th>Ответчик:</th>
<th>Дата составления:</th>
<th>Примечание:</th>
<th>Специализация:</th>
</tr>
</thead>
<tbody id="scrollable-table__tbody">
</tbody>
</table>
</div>
</div>
<script src="~/js/report/reportlist.js" asp-append-version="true"></script>

View File

@ -12,7 +12,7 @@
<header> <header>
<nav class="navbar navbar-expand-lg bg-body-tertiary bg-primary" data-bs-theme="dark"> <nav class="navbar navbar-expand-lg bg-body-tertiary bg-primary" data-bs-theme="dark">
<div class="container"> <div class="container">
<a class="navbar-brand text-white" asp-area="" asp-controller="Home" aspaction="Index">Юридическая фирма "Вас обманут"</a> <a class="navbar-brand text-white" asp-area="" asp-controller="Home" asp-action="Index">Юридическая фирма "Вас обманут"</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
@ -21,6 +21,9 @@
<a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Cases">Дела</a> <a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Cases">Дела</a>
<a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Deals">Договора</a> <a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Deals">Договора</a>
<a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Hearings">Слушания</a> <a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Hearings">Слушания</a>
<a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="SpecializationCaselist">Получение список</a>
<a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="GetReport">Получение отчёта</a>
<a class="nav-link text-white" asp-area="" asp-controller="Home" asp-action="Diagram">Формирование диаграммы</a>
</div> </div>
</div> </div>
</div> </div>

View File

@ -5,6 +5,8 @@ const defendantInput = document.getElementById("defendant-input");
const annotationInput = document.getElementById("annotation-input"); const annotationInput = document.getElementById("annotation-input");
const dateInput = document.getElementById("date-input"); const dateInput = document.getElementById("date-input");
const specializationSelect = document.getElementById("specialization-select"); const specializationSelect = document.getElementById("specialization-select");
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");
var specializations = []; var specializations = [];
@ -29,6 +31,40 @@ window.addEventListener("load", async () => {
} }
}); });
const correctData = function () {
return true;
};
const validate = function () {
if (nameInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Название дела'";
return false;
}
if (applicantInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Истец'";
return false;
}
if (defendantInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Ответчик'";
return false;
}
if (annotationInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Примечание'";
return false;
}
if (specializationSelect.value === '') {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Выберите 'Специализацию'";
return false;
}
return true;
};
createBtn.addEventListener("click", () => { createBtn.addEventListener("click", () => {
if (!correctData()) { if (!correctData()) {
return; return;
@ -36,19 +72,7 @@ createBtn.addEventListener("click", () => {
if (!validate()) { if (!validate()) {
return; return;
} }
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
createBtn.addEventListener("click", () => {
let caseModel = { let caseModel = {
"Name": nameInput.value, "Name": nameInput.value,
"Applicant": applicantInput.value, "Applicant": applicantInput.value,

View File

@ -6,11 +6,33 @@ const annotationInput = document.getElementById("annotation-input");
const dateInput = document.getElementById("date-input"); const dateInput = document.getElementById("date-input");
const specializationSelect = document.getElementById("specialization-select"); const specializationSelect = document.getElementById("specialization-select");
const caseId = document.getElementById("vb-id").dataset.id; const caseId = document.getElementById("vb-id").dataset.id;
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");
var specializations = []; var specializations = [];
const formatDate = (dateString) => {
const date = new Date(dateString);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
return `${year}-${month}-${day}`;
};
window.addEventListener("load", async () => { window.addEventListener("load", async () => {
try { try {
await $.ajax({
url: `/case/get?id=${caseId}`,
type: "GET",
contentType: "json"
}).done((result) => {
nameInput.value = result.name;
applicantInput.value = result.applicant;
defendantInput.value = result.defendant;
annotationInput.value = result.annotation;
dateInput.value = formatDate(result.date);
});
await $.ajax({ await $.ajax({
url: `/case/getallspecializations`, url: `/case/getallspecializations`,
type: "GET", type: "GET",
@ -30,6 +52,40 @@ window.addEventListener("load", async () => {
} }
}); });
const correctData = function () {
return true;
};
const validate = function () {
if (nameInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Название дела'";
return false;
}
if (applicantInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Истец'";
return false;
}
if (defendantInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Ответчик'";
return false;
}
if (annotationInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Примечание'";
return false;
}
if (specializationSelect.value === '') {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Выберите 'Специализацию'";
return false;
}
return true;
};
updateBtn.addEventListener("click", () => { updateBtn.addEventListener("click", () => {
if (!correctData()) { if (!correctData()) {
return; return;
@ -37,25 +93,13 @@ updateBtn.addEventListener("click", () => {
if (!validate()) { if (!validate()) {
return; return;
} }
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
updateBtn.addEventListener("click", () => {
let caseModel = { let caseModel = {
"Id": parseInt(caseId), "Id": parseInt(caseId),
"Name": nameInput.value, "Name": nameInput.value,
"Applicant": applicantInput.value, "Applicant": applicantInput.value,
"Defendant": defendantInput.value, "Defendant": defendantInput.value,
"Date": new Date(dateInput.value), "Date": dateInput.value,
"Annotation": annotationInput.value, "Annotation": annotationInput.value,
"SpecializationId": parseInt(specializationSelect.value), "SpecializationId": parseInt(specializationSelect.value),
}; };

View File

@ -0,0 +1,95 @@
const saveBtn = document.getElementById("save-button");
const tbody = document.getElementById("scrollable-table__tbody");
const currentDealId = document.getElementById("deal-data").dataset.id;
var contracts = [];
var dataArray = [];
var currentDeal = null;
window.addEventListener("load", async () => {
try {
await $.ajax({
url: `/deal/getallcontracts`,
type: "GET",
contentType: "json"
}).done((result) => {
contracts = result;
console.log(contracts);
contracts.forEach((contract) => {
const { id, service, coast, date } = contract;
const row = tbody.insertRow();
row.setAttribute("data-id", id);
const cells = [service, coast, date];
cells.forEach((value) => {
const cell = row.insertCell();
cell.textContent = value;
});
row.addEventListener('click', () => addAndRemoveFromList(row));
});
});
await $.ajax({
url: `/deal/get?id=${currentDealId}`,
type: "GET",
contentType: "json"
}).done((result) => {
currentDeal = result;
console.log(currentDeal)
});
} catch (error) {
console.error(error);
}
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
saveBtn.addEventListener("click", () => {
if (!correctData()) {
return;
}
if (!validate()) {
return;
}
let dealModel = {
"Id": currentDeal.id,
"Subject": currentDeal.subject,
"Responsibilities": currentDeal.responsibilities,
"Date": currentDeal.date,
"ContractViewModels": dataArray
};
console.log(dealModel);
console.log(dataArray);
$.ajax({
url: "/deal/update",
type: "POST",
contentType: "application/json",
data: JSON.stringify(dealModel)
}).done(() => {
window.location.href = "/Home/Deals";
});
});
const addAndRemoveFromList = (row) => {
var id = parseInt(row.dataset.id);
console.log(contracts.find(x => x.id === id))
var index = dataArray.indexOf(contracts.find(x => x.id === id));
if (index === -1) {
dataArray.push(contracts.find(x => x.id === id));
row.classList.add("bg-info");
} else {
dataArray.splice(index, 1);
row.classList.remove("bg-info");
}
console.log(dataArray);
}

View File

@ -3,6 +3,8 @@ const subjectInput = document.getElementById("subject-input");
const responsibilitiesInput = document.getElementById("responsibilities-input"); const responsibilitiesInput = document.getElementById("responsibilities-input");
const dateInput = document.getElementById("date-input"); const dateInput = document.getElementById("date-input");
const tbody = document.getElementById("scrollable-table__tbody") const tbody = document.getElementById("scrollable-table__tbody")
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");
var cases = []; var cases = [];
var dataArray = []; var dataArray = [];
@ -34,6 +36,30 @@ window.addEventListener("load", async () => {
} }
}); });
const correctData = function () {
return true;
};
const validate = function () {
if (subjectInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Предмет договора'";
return false;
}
if (responsibilitiesInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Обязаности'";
return false;
}
if (dataArray.length === 0) {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните список 'Дел'";
return false;
}
return true;
};
createBtn.addEventListener("click", () => { createBtn.addEventListener("click", () => {
if (!correctData()) { if (!correctData()) {
return; return;
@ -41,19 +67,7 @@ createBtn.addEventListener("click", () => {
if (!validate()) { if (!validate()) {
return; return;
} }
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
createBtn.addEventListener("click", () => {
let dealModel = { let dealModel = {
"Subject": subjectInput.value, "Subject": subjectInput.value,
"Responsibilities": responsibilitiesInput.value, "Responsibilities": responsibilitiesInput.value,
@ -77,10 +91,10 @@ const addAndRemoveFromList = (row) => {
var index = dataArray.indexOf(cases.find(x => x.id === id)); var index = dataArray.indexOf(cases.find(x => x.id === id));
if (index === -1) { if (index === -1) {
dataArray.push(cases.find(x => x.id === id)); dataArray.push(cases.find(x => x.id === id));
row.classList.add("bg-primary"); row.classList.add("bg-info");
} else { } else {
dataArray.splice(index, 1); dataArray.splice(index, 1);
row.classList.remove("bg-primary"); row.classList.remove("bg-info");
} }
console.log(dataArray); console.log(dataArray);
} }

View File

@ -3,13 +3,30 @@ const subjectInput = document.getElementById("subject-input");
const responsibilitiesInput = document.getElementById("responsibilities-input"); const responsibilitiesInput = document.getElementById("responsibilities-input");
const dateInput = document.getElementById("date-input"); const dateInput = document.getElementById("date-input");
const dealId = document.getElementById("vb-id").dataset.id; const dealId = document.getElementById("vb-id").dataset.id;
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");
updateBtn.addEventListener("click", () => { const formatDate = (dateString) => {
if (!correctData()) { const date = new Date(dateString);
return; const year = date.getFullYear();
} const month = ('0' + (date.getMonth() + 1)).slice(-2);
if (!validate()) { const day = ('0' + date.getDate()).slice(-2);
return; return `${year}-${month}-${day}`;
};
window.addEventListener("load", async () => {
try {
await $.ajax({
url: `/deal/get?id=${dealId}`,
type: "GET",
contentType: "json"
}).done((result) => {
subjectInput.value = result.subject;
responsibilitiesInput.value = result.responsibilities;
dateInput.value = formatDate(result.date);
});
} catch (error) {
console.error(error);
} }
}); });
@ -20,15 +37,37 @@ const correctData = function () {
const validate = function () { const validate = function () {
if (subjectInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Предмет договора'";
return false;
}
if (responsibilitiesInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Обязаности'";
return false;
}
if (dataArray.length === 0) {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните список 'Дел'";
return false;
}
return true; return true;
}; };
updateBtn.addEventListener("click", () => { updateBtn.addEventListener("click", () => {
if (!correctData()) {
return;
}
if (!validate()) {
return;
}
let dealModel = { let dealModel = {
"Id": parseInt(dealId), "Id": parseInt(dealId),
"Subject": subjectInput.value, "Subject": subjectInput.value,
"Responsibilities": responsibilitiesInput.value, "Responsibilities": responsibilitiesInput.value,
"Date": new Date(dateInput.value) "Date": dateInput.value
}; };
console.log(dealModel) console.log(dealModel)
$.ajax({ $.ajax({

View File

@ -0,0 +1,52 @@
var btnStatus = document.getElementById('btnStatus');
var casespecializations = [];
window.addEventListener('load', async () => {
await $.ajax({
url: "/case/getspecializationcases",
type: "GET",
contentType: "json"
}).done((result) => {
casespecializations = result;
console.log(casespecializations);
});
})
var ctx = document.getElementById('myChart').getContext('2d');
var chart;
function drawStatusChart() {
var edStatus = [];
var edCount = [];
console.log(casespecializations)
casespecializations.forEach((item) => {
edStatus.push(item.name);
});
casespecializations.forEach((item) => {
edCount.push(item.count);
});
var statusData = {
labels: edStatus,
datasets: [{
data: edCount
}]
};
// Clear the previous chart if it exists
if (chart) {
chart.destroy();
}
chart = new Chart(ctx, {
type: 'pie',
data: statusData,
options: {
responsive: true
}
});
}
btnStatus.addEventListener('click', function () {
drawStatusChart();
});

View File

@ -2,6 +2,8 @@
const informationInput = document.getElementById("information-input"); const informationInput = document.getElementById("information-input");
const dateInput = document.getElementById("date-input"); const dateInput = document.getElementById("date-input");
const caseSelect = document.getElementById("case-select"); const caseSelect = document.getElementById("case-select");
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");
var cases = []; var cases = [];
@ -26,6 +28,25 @@ window.addEventListener("load", async () => {
} }
}); });
const correctData = function () {
return true;
};
const validate = function () {
if (informationInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Информация по слушанию'";
return false;
}
if (caseSelect.value === '') {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Выберите 'Дело'";
return false;
}
return true;
};
createBtn.addEventListener("click", () => { createBtn.addEventListener("click", () => {
if (!correctData()) { if (!correctData()) {
return; return;
@ -33,19 +54,7 @@ createBtn.addEventListener("click", () => {
if (!validate()) { if (!validate()) {
return; return;
} }
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
createBtn.addEventListener("click", () => {
let hearingModel = { let hearingModel = {
"Information": informationInput.value, "Information": informationInput.value,
"CaseId": parseInt(caseSelect.value), "CaseId": parseInt(caseSelect.value),

View File

@ -3,12 +3,30 @@ const informationInput = document.getElementById("information-input");
const dateInput = document.getElementById("date-input"); const dateInput = document.getElementById("date-input");
const caseSelect = document.getElementById("case-select"); const caseSelect = document.getElementById("case-select");
const hearingId = document.getElementById("vb-id").dataset.id; const hearingId = document.getElementById("vb-id").dataset.id;
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");
var cases = []; var cases = [];
const formatDate = (dateString) => {
const date = new Date(dateString);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
return `${year}-${month}-${day}`;
};
window.addEventListener("load", async () => { window.addEventListener("load", async () => {
try { try {
$.ajax({ await $.ajax({
url: `/hearing/get?id=${hearingId}`,
type: "GET",
contentType: "json"
}).done((result) => {
informationInput.value = result.information;
dateInput.value = formatDate(result.date);
});
await $.ajax({
url: "/case/getallbyuser", url: "/case/getallbyuser",
type: "GET", type: "GET",
contentType: "json" contentType: "json"
@ -27,6 +45,25 @@ window.addEventListener("load", async () => {
} }
}); });
const correctData = function () {
return true;
};
const validate = function () {
if (informationInput.value === "") {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Заполните поле 'Информация по слушанию'";
return false;
}
if (caseSelect.value === '') {
errorDivShell.style.gridTemplateRows = "1fr";
errorP.innerHTML = "Выберите 'Дело'";
return false;
}
return true;
};
updateBtn.addEventListener("click", () => { updateBtn.addEventListener("click", () => {
if (!correctData()) { if (!correctData()) {
return; return;
@ -34,24 +71,12 @@ updateBtn.addEventListener("click", () => {
if (!validate()) { if (!validate()) {
return; return;
} }
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
updateBtn.addEventListener("click", () => {
let hearingModel = { let hearingModel = {
"Id": parseInt(hearingId), "Id": parseInt(hearingId),
"Information": informationInput.value, "Information": informationInput.value,
"CaseId": parseInt(caseSelect.value), "CaseId": parseInt(caseSelect.value),
"Date": new Date(dateInput.value) "Date": dateInput.value
}; };
console.log(hearingModel) console.log(hearingModel)
$.ajax({ $.ajax({

View File

@ -0,0 +1,91 @@
const createBtn = document.getElementById("create-button")
const tbody = document.getElementById("scrollable-table__tbody")
const nameInput = document.getElementById("name-input")
var fileType = document.getElementById("file-type")
var cases = []
var dataArray = [];
const wordMIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const excelMIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
window.addEventListener('load', async () => {
try {
await $.ajax({
url: `/case/getallbyuser`,
type: "GET",
contentType: "json"
}).done((result) => {
cases = result;
cases.forEach((caseModel) => {
const { id, name, applicant, defendant, annotation, date, specialization } = caseModel;
const row = tbody.insertRow();
row.setAttribute("data-id", id);
const cells = [name, applicant, defendant, annotation, date, specialization];
cells.forEach((value) => {
const cell = row.insertCell();
cell.textContent = value;
});
row.addEventListener('click', () => addAndRemoveFromList(row));
});
});
} catch (error) {
console.error(error);
}
})
createBtn.addEventListener('click', () => {
let listModel = {
"Cases": Array.from(dataArray),
"FileType": fileType.value
};
$.ajax({
url: "/home/specializationcaselist",
type: "POST",
contentType: "application/json",
data: JSON.stringify(listModel)
}).done((file) => {
let byteArray = new Uint8Array(file);
saveFile(byteArray, fileType);
});
})
const saveFile = async function (bytes, fileType) {
if (window.showSaveFilePicker) {
let type;
if (fileType.value == "docx") {
type = {
description: "Microsoft Word (OpenXML)",
accept: { [wordMIME]: [".docx"] }
};
} else if (fileType.value == "xlsx") {
type = {
description: "Microsoft Excel (OpenXML)",
accept: { [excelMIME]: [".xlsx"] }
};
}
const opts = {
suggestedName: `case-specialization-list.${fileType.value}`,
types: [type],
};
const handle = await showSaveFilePicker(opts);
const writable = await handle.createWritable();
await writable.write(bytes);
writable.close();
}
}
const addAndRemoveFromList = (row) => {
var id = parseInt(row.dataset.id);
console.log(cases.find(x => x.id === id))
var index = dataArray.indexOf(cases.find(x => x.id === id));
if (index === -1) {
dataArray.push(cases.find(x => x.id === id));
row.classList.add("bg-info");
} else {
dataArray.splice(index, 1);
row.classList.remove("bg-info");
}
console.log(dataArray);
}

View File

@ -0,0 +1,87 @@
const dateFromInput = document.getElementById("date-from-input");
const dateToInput = document.getElementById("date-to-input");
const generateButton = document.getElementById("generate-button");
const sendByMailButton = document.getElementById("send-by-mail-button");
const dateToSpan = document.getElementById("date-to-span");
const dateFromSpan = document.getElementById("date-from-span");
const tbody = document.getElementById("tbody");
generateButton.addEventListener("click", () => {
const dateFrom = new Date(dateFromInput.value);
const dateTo = new Date(dateToInput.value);
const reportModel = {
"DateFrom": dateFrom,
"DateTo": dateTo
};
$.ajax({
url: "/home/getreport",
type: "POST",
contentType: "application/json",
data: JSON.stringify(reportModel)
}).done((data) => {
dateFromSpan.innerHTML = reportModel["DateFrom"].toLocaleDateString();
dateToSpan.innerHTML = reportModel["DateTo"].toLocaleDateString();
renderTable(data);
});
});
const formatDate = (dateString) => {
const date = new Date(dateString);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
return `${year}-${month}-${day}`;
};
sendByMailButton.addEventListener("click", () => {
const dateFrom = new Date(dateFromInput.value);
const dateTo = new Date(dateToInput.value);
const reportModel = {
"DateFrom": dateFrom,
"DateTo": dateTo
};
$.ajax({
url: "/home/sendbymailstatusreport",
type: "POST",
contentType: "application/json",
data: JSON.stringify(reportModel)
}).done(() => {
alert("Отчет успешно отправлен на вашу почту!")
});
});
const renderTable = (data) => {
tbody.innerHTML = "";
for (var i = 0; i < data.length; i++) {
var hearingData = data[i];
var hearingName = hearingData.hearing;
for (var j = 0; j < hearingData.caseLawyers.length; j++) {
var info = hearingData.caseLawyers[j];
if (j === 0) {
var row = tbody.insertRow();
var hearingNameCell = row.insertCell()
hearingNameCell.textContent = hearingName;
var caseNameCell = row.insertCell();
var dateCell = row.insertCell();
var lawyerCell = row.insertCell();
tbody.appendChild(row)
}
var row = tbody.insertRow();
var hearingNameCell = row.insertCell()
var caseNameCell = row.insertCell();
caseNameCell.textContent = info.case;
var dateCell = row.insertCell();
dateCell.textContent = formatDate(info.date);
var lawyerCell = row.insertCell();
lawyerCell.textContent = info.lawyer;
tbody.appendChild(row);
}
}
}

View File

@ -59,6 +59,19 @@ namespace CaseAccountingRestApi.Controllers
} }
} }
[HttpGet]
public List<SpecializationCasesViewModel> GetSpecializationCases()
{
try
{
return _logic.GetSpecializationCases();
}
catch (Exception)
{
throw;
}
}
[HttpPost] [HttpPost]
public void Create(CaseBindingModel model) public void Create(CaseBindingModel model)
{ {

View File

@ -1,4 +1,5 @@
using CaseAccountingContracts.BindingModels; using CaseAccountingBusinessLogic.BusinessLogics;
using CaseAccountingContracts.BindingModels;
using CaseAccountingContracts.BusinessLogicContracts; using CaseAccountingContracts.BusinessLogicContracts;
using CaseAccountingContracts.SearchModels; using CaseAccountingContracts.SearchModels;
using CaseAccountingContracts.ViewModels; using CaseAccountingContracts.ViewModels;
@ -11,10 +12,12 @@ namespace CaseAccountingRestApi.Controllers
public class DealController : Controller public class DealController : Controller
{ {
private readonly IDealLogic _logic; private readonly IDealLogic _logic;
private readonly IContractLogic _contractLogic;
public DealController(IDealLogic logic) public DealController(IDealLogic logic, IContractLogic contractLogic)
{ {
_logic = logic; _logic = logic;
_contractLogic = contractLogic;
} }
[HttpGet] [HttpGet]
@ -43,6 +46,19 @@ namespace CaseAccountingRestApi.Controllers
} }
} }
[HttpGet]
public List<ContractViewModel>? GetAllContracts()
{
try
{
return _contractLogic.ReadList(null);
}
catch (Exception)
{
throw;
}
}
[HttpPost] [HttpPost]
public void Create(DealBindingModel model) public void Create(DealBindingModel model)
{ {

View File

@ -16,7 +16,7 @@ namespace CaseAccountingRestApi.Controllers
} }
[HttpPost] [HttpPost]
public byte[] LawyerHearingList(LawyerHearingListBindingModel listModel) public byte[] LawyerHearinglist(LawyerHearingListBindingModel listModel)
{ {
byte[] file = _reportCustomerLogic.SaveListFile(listModel); byte[] file = _reportCustomerLogic.SaveListFile(listModel);
return file; return file;

View File

@ -0,0 +1,39 @@
using CaseAccountingContracts.BindingModels;
using CaseAccountingContracts.BusinessLogicContracts;
using CaseAccountingContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace CaseAccountingRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ReportProviderController : Controller
{
private readonly IReportProviderLogic reportLogic;
public ReportProviderController(IReportProviderLogic reportLogic)
{
this.reportLogic = reportLogic;
}
[HttpPost]
public byte[] SpecializationCaselist(CaseSpecializationListBindingModel listModel)
{
byte[] file = reportLogic.SaveListFile(listModel);
return file;
}
[HttpPost]
public List<ReportHearingLawyerViewModel> GetReportData(ReportBindingModel reportModel)
{
var list = reportLogic.GetHearingLawyer(reportModel);
return list;
}
[HttpPost]
public void SendByMailStatusReport(ReportBindingModel reportModel)
{
reportLogic.SendByMailStatusReport(reportModel);
}
}
}

View File

@ -1,6 +1,7 @@
using CaseAccountingBusinessLogic.BusinessLogic.OfficePackage;
using CaseAccountingBusinessLogic.BusinessLogics; using CaseAccountingBusinessLogic.BusinessLogics;
using CaseAccountingBusinessLogic.OfficePackage; using CaseAccountingBusinessLogic.OfficePackage;
using CaseAccountingBusinessLogic.OfficePackage.HelperModels; using CaseAccountingContracts.BindingModels;
using CaseAccountingContracts.BusinessLogicContracts; using CaseAccountingContracts.BusinessLogicContracts;
using CaseAccountingContracts.StoragesContracts; using CaseAccountingContracts.StoragesContracts;
using CaseAccountingDataBaseImplement.Implements; using CaseAccountingDataBaseImplement.Implements;
@ -28,8 +29,13 @@ builder.Services.AddTransient<ILawyerLogic, LawyerLogic>();
builder.Services.AddTransient<ISpecializationLogic, SpecializationLogic>(); builder.Services.AddTransient<ISpecializationLogic, SpecializationLogic>();
builder.Services.AddTransient<IUserLogic, UserLogic>(); builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddTransient<WordBuilderCustomer>(); builder.Services.AddTransient<IReportProviderLogic, ReportProviderLogic>();
builder.Services.AddTransient<ExcelBuilderCustomer>();
builder.Services.AddTransient<WordBuilderProvider>();
builder.Services.AddTransient<ExcelBuilderProvider>();
builder.Services.AddTransient<PdfBuilderProvider>();
builder.Services.AddSingleton<MailSender>();
builder.Services.AddControllers().AddNewtonsoftJson(); builder.Services.AddControllers().AddNewtonsoftJson();
@ -47,6 +53,15 @@ builder.Services.AddSwaggerGen(c =>
var app = builder.Build(); var app = builder.Build();
var mailSender = app.Services.GetService<MailSender>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
});
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {

View File

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "rpplabs098@gmail.com",
"MailPassword": "sxwf ohjr cgba wext"
} }