ИСЭбд-21. Иванова А.А. Лабораторная работа 4 #4

Closed
Anastasia_52 wants to merge 2 commits from LabWork_4 into LabWork_3
22 changed files with 254 additions and 43 deletions

View File

@ -5,16 +5,29 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace ProjectGSM.Entities;
public class Car
{
public int Car_ID { get; private set; }
[DisplayName("Марка машины")]
public string Car_Mark { get; private set; } = string.Empty;
[DisplayName("Модель машины")]
public string Car_Model { get; private set; } = string.Empty;
public string FullCar => $"{Car_Mark} {Car_Model}";
[DisplayName("Тип машины")]
public Car_Type Car_Type { get; private set; }
[DisplayName("Категория ТС")]
public СategoryRights License { get; private set; }
[DisplayName("Потребление ГСМ")]
public float Consumption_Rate { get; private set; }
public static Car CreateEntity(int car_ID, string car_mark, string car_model, Car_Type car_type, СategoryRights license, float consumption)

View File

@ -1,6 +1,7 @@
using ProjectGSM.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,8 +11,16 @@ namespace ProjectGSM.Entities;
public class Driver
{
public int Driver_ID { get; private set; }
[DisplayName("Имя водителя")]
public string Firstname { get; private set; } = string.Empty;
[DisplayName("Фамилия водителя")]
public string Secondname { get; private set; } = string.Empty;
public string FullDriver => $"{Firstname} {Secondname}";
[DisplayName("Категория прав")]
public СategoryRights Driver_License { get; private set; }
public static Driver CreateEntity(int driver_ID, string firstname, string secondname, СategoryRights license)

View File

@ -2,6 +2,7 @@
using ProjectGSM.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -12,8 +13,14 @@ namespace ProjectGSM.Entities;
public class PetrolStation
{
public int Fuel_ID { get; private set; }
[DisplayName("Тип топлива")]
public FuelType Fuel_Type { get; private set; }
[DisplayName("Цена за литр")]
public float Price_Per_Liter { get; private set; }
[DisplayName("Количество")]
public float Amount { get; private set; }
public static PetrolStation CreateEntity(int fuel_id, FuelType type, float price, float amount)

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -9,11 +10,25 @@ namespace ProjectGSM.Entities;
public class Refill
{
public int Refill_ID { get; private set; }
[DisplayName("Дата заправки")]
public DateTime Refill_Date { get; private set; }
[DisplayName("Количество")]
public float Quantity { get; private set; }
[Browsable(false)]
public int Fuel_ID { get; private set; }
[DisplayName("Топливо")]
public string FuelName { get; private set; } = string.Empty;
[Browsable(false)]
public int Car_ID { get; private set; }
[DisplayName("Машина")]
public string CarName { get; private set; } = string.Empty;
public static Refill CreateOperation(int refill_ID, DateTime refill_date, float quantity, int fuel_id, int car_id)
{
return new Refill

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -9,8 +10,16 @@ namespace ProjectGSM.Entities;
public class Route
{
public int Route_ID { get; private set; }
[DisplayName("Начальная точка")]
public string Start_Point { get; private set; } = string.Empty;
[DisplayName("Конечная точка")]
public string End_Point { get; private set; } = string.Empty;
public string FullRoute => $"{Start_Point} {End_Point}";
[DisplayName("Длина маршрута")]
public float Route_Length { get; private set; }
public static Route CreateEntity (int route_id, string start_point, string end_point, float length)

View File

@ -1,6 +1,7 @@
using ProjectGSM.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,11 +11,34 @@ namespace ProjectGSM.Entities;
public class RouteSheet
{
public int RouteSheet_ID { get; private set; }
[DisplayName("Дата начала")]
public DateTime Start_Date { get; private set; }
[DisplayName("Дата конца")]
public DateTime End_Date { get; private set; }
[DisplayName("Расход топлива")]
public float Fuel_Consumption { get; private set; }
[Browsable(false)]
public int Car_ID { get; private set; }
[DisplayName("Машина")]
public string CarName { get; private set; } = string.Empty;
[Browsable(false)]
public int Driver_ID { get; private set; }
[DisplayName("Водитель")]
public string DriverName { get; private set; } = string.Empty;
[DisplayName("Маршруты")]
public string Route => Routes != null ?
string.Join(", ", Routes.Select(x => $"{x.RouteName}")) :
string.Empty;
[Browsable(false)]
public IEnumerable<Trip_Route> Routes { get; private set; } = [];
public static RouteSheet CreateOperation(int routeSheet_id, DateTime start_date, DateTime end_date, float consumption, int car_id, int driver_id, IEnumerable<Trip_Route> routes)
@ -30,4 +54,10 @@ public class RouteSheet
Routes = routes
};
}
public void SetTrips(IEnumerable<Trip_Route> routes)
{
if (routes != null && routes.Any())
Routes = routes;
}
}

View File

@ -10,6 +10,7 @@ public class Trip_Route
{
public int RouteSheet_ID { get; private set; }
public int Route_ID { get; private set; }
public string RouteName { get; private set; } = string.Empty;
public static Trip_Route CreateElement(int routeSheet_ID, int route_id)
{

View File

@ -29,7 +29,12 @@ namespace ProjectGSM.Forms
private void LoadList() => dataGridView.DataSource = _carRepository.ReadCars();
private void LoadList()
{
dataGridView.DataSource = _carRepository.ReadCars();
dataGridView.Columns["Car_ID"].Visible = false;
dataGridView.Columns["FullCar"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{

View File

@ -28,7 +28,12 @@ namespace ProjectGSM.Forms
}
private void LoadList() => dataGridView.DataSource = _driverRepository.ReadDrivers();
private void LoadList()
{
dataGridView.DataSource = _driverRepository.ReadDrivers();
dataGridView.Columns["Driver_ID"].Visible = false;
dataGridView.Columns["FullDriver"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{

View File

@ -28,7 +28,11 @@ namespace ProjectGSM.Forms
}
private void LoadList() => dataGridView.DataSource = _petrolStationRepository.ReadPetrolStations();
private void LoadList()
{
dataGridView.DataSource = _petrolStationRepository.ReadPetrolStations();
dataGridView.Columns["Fuel_ID"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{

View File

@ -28,7 +28,7 @@ namespace ProjectGSM.Forms
comboBoxFuelID.ValueMember = "Fuel_ID";
comboBoxCarID.DataSource = carRepository.ReadCars();
comboBoxCarID.DisplayMember = "Car_Mark";
comboBoxCarID.DisplayMember = "FullCar";
comboBoxCarID.ValueMember = "Car_ID";
}

View File

@ -30,7 +30,11 @@ namespace ProjectGSM.Forms
}
private void LoadList() => dataGridView.DataSource = _refillRepository.ReadRefills();
private void LoadList()
{
dataGridView.DataSource = _refillRepository.ReadRefills();
dataGridView.Columns["Refill_ID"].Visible = false;
}
private void buttonAdd_Click(object sender, EventArgs e)
{

View File

@ -176,14 +176,14 @@
//
// ColumnRoute
//
ColumnRoute.HeaderText = "Начало маршрута";
ColumnRoute.HeaderText = "Маршрут";
ColumnRoute.MinimumWidth = 6;
ColumnRoute.Name = "ColumnRoute";
ColumnRoute.Width = 125;
//
// ColumnEndPoint
//
ColumnEndPoint.HeaderText = "Конечная точка";
ColumnEndPoint.HeaderText = "Смена ";
ColumnEndPoint.MinimumWidth = 6;
ColumnEndPoint.Name = "ColumnEndPoint";
ColumnEndPoint.Width = 125;

View File

@ -28,11 +28,11 @@ namespace ProjectGSM.Forms
comboBoxCarID.ValueMember = "Car_ID";
comboBoxDriverID.DataSource = driverRepository.ReadDrivers();
comboBoxDriverID.DisplayMember = "Firstname";
comboBoxDriverID.DisplayMember = "FullDriver";
comboBoxDriverID.ValueMember = "Driver_ID";
ColumnRoute.DataSource = routeRepository.ReadRoutes();
ColumnRoute.DisplayMember = "Start_Point";
ColumnRoute.DisplayMember = "FullRoute";
ColumnRoute.ValueMember = "Route_ID";
}
@ -67,6 +67,5 @@ namespace ProjectGSM.Forms
}
return list;
}
}
}

View File

@ -39,9 +39,9 @@
//
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(641, 0);
panel1.Location = new Point(730, 0);
panel1.Name = "panel1";
panel1.Size = new Size(159, 450);
panel1.Size = new Size(159, 501);
panel1.TabIndex = 0;
//
// buttonAdd
@ -71,14 +71,14 @@
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(641, 450);
dataGridView.Size = new Size(730, 501);
dataGridView.TabIndex = 3;
//
// FormRouteSheets
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
ClientSize = new Size(889, 501);
Controls.Add(dataGridView);
Controls.Add(panel1);
Name = "FormRouteSheets";

View File

@ -1,4 +1,5 @@
using ProjectGSM.Repositories;
using ProjectGSM.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -29,7 +30,13 @@ namespace ProjectGSM.Forms
throw new ArgumentNullException(nameof(routeSheetRepository));
}
private void LoadList() => dataGridView.DataSource = _routeSheetRepository.ReadRouteSheet();
private void LoadList()
{
dataGridView.DataSource = _routeSheetRepository.ReadRouteSheet();
dataGridView.Columns["RouteSheet_ID"].Visible = false;
dataGridView.Columns["Start_Date"].DefaultCellStyle.Format = "dd.MM.yyyy";
dataGridView.Columns["End_Date"].DefaultCellStyle.Format = "dd.MM.yyyy";
}
private void buttonAdd_Click(object sender, EventArgs e)
{

View File

@ -26,7 +26,12 @@ namespace ProjectGSM.Forms
throw new ArgumentNullException(nameof(routeRepository));
}
private void LoadList() => dataGridView.DataSource = _routeRepository.ReadRoutes();
private void LoadList()
{
dataGridView.DataSource = _routeRepository.ReadRoutes();
dataGridView.Columns["Route_ID"].Visible = false;
dataGridView.Columns["FullRoute"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{

View File

@ -26,7 +26,7 @@ public class ChartReport
{
new PDFBuilder(filePath)
.AddHeader("Отчет по заправкам")
.AddPieChart("Объем заправленного топлива по автомобилям", GetData(dateTime))
.AddPieChart($"Объем заправленного топлива по автомобилям {dateTime: dd MMMM yyyy}", GetData(dateTime))
.Build();
return true;
}
@ -43,13 +43,13 @@ public class ChartReport
.ReadRefills()
.Where(x => x.Refill_Date.Date == dateTime.Date)
.GroupBy(
x => x.Car_ID,
x => x.CarName,
(key, group) => new
{
CarId = key,
CarName = key,
TotalRefill = group.Sum(y => y.Quantity)
})
.Select(x => ($"Автомобиль {x.CarId}", (double)x.TotalRefill))
.Select(x => ($"{x.CarName}", (double)x.TotalRefill))
.ToList();
}
}

View File

@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging;
using ProjectGSM.Repositories;
using ProjectGSM.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
@ -33,7 +34,7 @@ public class TableReport
new ExcelBuilder(filePath)
.AddHeader("Сводка по пополнению на заправках и поездкам автомобиля", 0, 4)
.AddParagraph($"за период с {startDate:yyyy-MM-dd} по {endDate:yyyy-MM-dd}", 0)
.AddParagraph($"за период с {startDate:dd.MM.yyyy} по {endDate:dd.MM.yyyy}", 0)
.AddTable(new[] { 15, 20, 20, 20 }, tableData)
.Build();
@ -49,22 +50,22 @@ public class TableReport
private List<string[]> GetData(int carId, DateTime startDate, DateTime endDate)
{
var refills = _refillRepository
.ReadRefills()
.Where(x => x.Refill_Date >= startDate && x.Refill_Date <= endDate && x.Car_ID == carId)
.Select(x => new
{
CarId = x.Car_ID,
Date = x.Refill_Date,
RefillAmount = (float?)x.Quantity,
FuelConsumption = (float?)null
})
.AsEnumerable();
.ReadRefills(dateFrom: startDate, dateTo: endDate, carId: carId)
.Select(x => new
{
x.CarName,
CarId = x.Car_ID,
Date = x.Refill_Date,
RefillAmount = (float?)x.Quantity,
FuelConsumption = (float?)null
})
.AsEnumerable();
var trips = _routeSheetRepository
.ReadRouteSheet()
.Where(x => x.Start_Date >= startDate && x.End_Date <= endDate && x.Car_ID == carId)
.ReadRouteSheet(dateFrom: startDate, dateTo: endDate, carId: carId)
.Select(x => new
{
x.CarName,
CarId = x.Car_ID,
Date = x.Start_Date,
RefillAmount = (float?)null,
@ -79,8 +80,8 @@ public class TableReport
new List<string[]>() { item }
.Union(data.Select(x => new string[]
{
x.CarId.ToString(),
x.Date.ToString("yyyy-MM-dd HH:mm"),
x.CarName.ToString(),
x.Date.ToString("dd.MM.yyyy"),
x.RefillAmount?.ToString() ?? string.Empty,
x.FuelConsumption?.ToString() ?? string.Empty
}))

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectGSM.Repositories.Implementation;
public class QuerryBuilder
{
private readonly StringBuilder _builder;
public QuerryBuilder()
{
_builder = new();
}
public QuerryBuilder AddCondition(string condition)
{
if (_builder.Length > 0)
_builder.Append(" AND ");
_builder.Append(condition);
return this;
}
public string Build()
{
if (_builder.Length == 0)
return string.Empty;
return $"WHERE {_builder}";
}
}

View File

@ -3,6 +3,7 @@ using Newtonsoft.Json;
using Npgsql;
using ProjectGSM.Entities;
using Dapper;
using ProjectGSM.Repositories.Implementation;
namespace ProjectGSM.Repositories.Implementations;
@ -42,9 +43,31 @@ VALUES (@Refill_Date, @Quantity, @Fuel_ID, @Car_ID)";
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QuerryBuilder();
if (dateFrom.HasValue)
builder.AddCondition("r.Refill_Date >= @dateFrom");
if (dateTo.HasValue)
builder.AddCondition("r.Refill_Date <= @dateTo");
if (fuelId.HasValue)
builder.AddCondition("r.Fuel_ID = @fuelId");
if (carId.HasValue)
builder.AddCondition("r.Car_ID = @carId");
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Refill";
var refills = connection.Query<Refill>(querySelect);
var querySelect = $@"SELECT
r.*,
CONCAT(c.Car_Mark, ' ', c.Car_Model) AS CarName,
CASE f.Fuel_Type :: int
WHEN 1 THEN 'Бензин'
WHEN 2 THEN 'Дизель'
ELSE 'Unknown'
END AS FuelName
FROM Refill r
LEFT JOIN PetrolStation f ON r.Fuel_ID = f.Fuel_ID
LEFT JOIN Car c ON r.Car_ID = c.Car_ID
{builder.Build()}";
var refills = connection.Query<Refill>(querySelect, new { dateFrom, dateTo, fuelId, carId });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(refills));
return refills;
}

View File

@ -3,6 +3,7 @@ using Newtonsoft.Json;
using Npgsql;
using ProjectGSM.Entities;
using Dapper;
using ProjectGSM.Repositories.Implementation;
namespace ProjectGSM.Repositories.Implementations;
@ -60,12 +61,52 @@ public class RouteSheetRepository : IRouteSheetRepository
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QuerryBuilder();
if (dateFrom != null)
builder.AddCondition("t.Start_Date >= @dateFrom");
if (dateTo != null)
builder.AddCondition("t.End_Date <= @dateTo");
if (carId != null)
builder.AddCondition("t.Car_ID = @carId");
if (driverId != null)
builder.AddCondition("t.Driver_ID = @driverId");
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM RouteSheet";
var routeSheets = connection.Query<RouteSheet>(querySelect);
var querySelect = $@"SELECT
t.*,
CONCAT(c.Car_Mark, ' ', c.Car_Model) AS CarName,
CONCAT(d.Firstname, ' ', d.Secondname) AS DriverName,
tr.Route_ID,
CONCAT(r.Start_Point, ' ', r.End_Point) AS RouteName
FROM RouteSheet t
LEFT JOIN Car c ON t.Car_ID = c.Car_ID
LEFT JOIN Driver d ON t.Driver_ID = d.Driver_ID
INNER JOIN Trip_Route tr ON t.RouteSheet_ID = tr.RouteSheet_ID
LEFT JOIN Route r ON r.Route_ID = tr.Route_ID
{builder.Build()}";
var tripDict = new Dictionary<int, List<Trip_Route>>();
var trips = connection.Query<RouteSheet, Trip_Route, RouteSheet>(querySelect,
(trip, tripRoute) =>
{
if (!tripDict.TryGetValue(trip.RouteSheet_ID, out var tr))
{
tr = new List<Trip_Route>();
tripDict.Add(trip.RouteSheet_ID, tr);
}
tr.Add(tripRoute);
return trip;
}, splitOn: "Route_ID", param: new { dateFrom, dateTo, carId, driverId });
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(routeSheets));
return routeSheets;
JsonConvert.SerializeObject(trips));
return tripDict.Select(x =>
{
var t = trips.First(y => y.RouteSheet_ID == x.Key);
t.SetTrips(x.Value);
return t;
}).ToList();
}
catch (Exception ex)
{
@ -73,6 +114,4 @@ public class RouteSheetRepository : IRouteSheetRepository
throw;
}
}
}