first commit

This commit is contained in:
Salikh 2024-05-17 03:17:15 +04:00
parent 570ec7a89d
commit c1c043c6c3
47 changed files with 2356 additions and 537 deletions

View File

@ -14,15 +14,12 @@ namespace MotorPlantBusinessLogic.BusinessLogics
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage; private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IEngineStorage _engineStorage; public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopStorage shopStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IEngineStorage engineStorage)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_shopStorage = shopStorage; _shopStorage = shopStorage;
_shopLogic = shopLogic;
_engineStorage = engineStorage;
} }
public List<OrderViewModel>? ReadList(OrderSearchModel? model) public List<OrderViewModel>? ReadList(OrderSearchModel? model)
@ -38,22 +35,31 @@ namespace MotorPlantBusinessLogic.BusinessLogics
return list; return list;
} }
private void CheckModel(OrderBindingModel model) private void CheckModel(OrderBindingModel model, bool WithParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
if (model.Count <= 0) if (!WithParams)
{ {
throw new ArgumentNullException("Количество заказов должно быть больше нуля"); return;
} }
if (model.Sum <= 0) if (model.Count <= 0)
{ {
throw new ArgumentNullException("Цена заказа должна быть больше нуля"); throw new ArgumentException("Количество движков в заказе не может быть меньше 1", nameof(model.Count));
} }
_logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}", model.Id, model.Sum); if (model.Sum <= 0)
} {
throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum));
}
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate)
{
throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}");
}
_logger.LogInformation("Pizza. PizzaId:{PizzaId}.Count:{Count}.Sum:{Sum}Id:{Id}",
model.EngineId, model.Count, model.Sum, model.Id);
}
public bool CreateOrder(OrderBindingModel model) public bool CreateOrder(OrderBindingModel model)
{ {
@ -72,38 +78,38 @@ namespace MotorPlantBusinessLogic.BusinessLogics
} }
private bool ChangeStatus(OrderBindingModel model, OrderStatus status) private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus)
{ {
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); CheckModel(model, false);
if (element == null) var element = _orderStorage.GetElement(new OrderSearchModel()
{ {
_logger.LogWarning("Find order failed"); Id = model.Id
return false; });
} if (element == null)
if (element.Status != status - 1) {
{ throw new ArgumentNullException(nameof(element));
_logger.LogWarning("Status change failed"); }
throw new InvalidOperationException("Невозможно перевести состояние заказа"); model.DateCreate = element.DateCreate;
} model.EngineId = element.EngineId;
if (status == OrderStatus.Готов) model.DateImplement = element.DateImplement;
{ model.Status = element.Status;
var engine = _engineStorage.GetElement(new EngineSearchModel() { Id = model.EngineId }); model.Count = element.Count;
if (engine == null) model.Sum = element.Sum;
{ if (requiredStatus - model.Status == 1)
_logger.LogWarning("Status change error. Engine not found"); {
return false; model.Status = requiredStatus;
} if (model.Status == OrderStatus.Выдан)
if (!CheckSupply(engine, model.Count)) model.DateImplement = DateTime.Now;
{ if (_orderStorage.Update(model) == null)
_logger.LogWarning("Status change error. Shop doesnt have engines"); {
return false; _logger.LogWarning("Update operation failed");
} return false;
} }
model.Status = status; return true;
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; }
_orderStorage.Update(model); _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus);
return true; throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}");
} }
public bool TakeOrderInWork(OrderBindingModel model) public bool TakeOrderInWork(OrderBindingModel model)
{ {
@ -117,67 +123,24 @@ namespace MotorPlantBusinessLogic.BusinessLogics
public bool DeliveryOrder(OrderBindingModel model) public bool DeliveryOrder(OrderBindingModel model)
{ {
return ChangeStatus(model, OrderStatus.Выдан); var order = _orderStorage.GetElement(new OrderSearchModel
} {
Id = model.Id,
});
if (order == null)
{
throw new ArgumentNullException(nameof(order));
}
if (!_shopStorage.RestockingShops(new SupplyBindingModel
{
EngineId = order.EngineId,
Count = order.Count
}))
{
throw new ArgumentException("Недостаточно места");
}
public bool CheckSupply(IEngineModel engine, int count) return ChangeStatus(model, OrderStatus.Выдан);
{ }
if (count <= 0)
{
_logger.LogWarning("Check supply operation error. Engine count < 0");
return false;
}
int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCount).Sum();
int sumCount = _shopStorage.GetFullList().Select(x => x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum();
int free = sumCapacity - sumCount;
if (free < count)
{
_logger.LogWarning("Check supply error. No place for new Engines");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
free = shop.MaxCount;
foreach (var doc in shop.ShopEngines)
{
free -= doc.Value.Item2;
}
if (free == 0)
{
continue;
}
if (free >= count)
{
if (_shopLogic.MakeSupply(new()
{
Id = shop.Id
}, engine, count))
{
count = 0;
}
else
{
_logger.LogWarning("Supply error");
return false;
}
}
else
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id }, engine, free))
count -= free;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
} }
} }

View File

@ -1,15 +1,10 @@
using MotorPlantBusinessLogic.OfficePackage.HelperModels; using MotorPlantBusinessLogic.OfficePackage;
using MotorPlantBusinessLogic.OfficePackage; using MotorPlantBusinessLogic.OfficePackage.HelperModels;
using MotorPlantContracts.BindingModels; using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels; using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels; using MotorPlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.BusinessLogic namespace MotorPlantBusinessLogic.BusinessLogic
{ {
@ -17,22 +12,25 @@ namespace MotorPlantBusinessLogic.BusinessLogic
{ {
private readonly IComponentStorage _componentStorage; private readonly IComponentStorage _componentStorage;
private readonly IEngineStorage _engineStorage; private readonly IEngineStorage _engineStorage;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf; private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IEngineStorage engineStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, public ReportLogic(IEngineStorage engineStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{ {
_engineStorage = engineStorage; _engineStorage = engineStorage;
_componentStorage = componentStorage; _componentStorage = componentStorage;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_shopStorage = shopStorage;
_saveToExcel = saveToExcel; _saveToExcel = saveToExcel;
_saveToWord = saveToWord; _saveToWord = saveToWord;
@ -42,28 +40,12 @@ namespace MotorPlantBusinessLogic.BusinessLogic
public List<ReportEngineComponentViewModel> GetEngineComponents() public List<ReportEngineComponentViewModel> GetEngineComponents()
{ {
var engines = _engineStorage.GetFullList(); return _engineStorage.GetFullList().Select(x => new ReportEngineComponentViewModel
var list = new List<ReportEngineComponentViewModel>();
foreach (var engine in engines)
{ {
var record = new ReportEngineComponentViewModel EngineName = x.EngineName,
{ Components = x.EngineComponents.Select(x => (x.Value.Item1.ComponentName, x.Value.Item2)).ToList(),
EngineName = engine.EngineName, TotalCount = x.EngineComponents.Select(x => x.Value.Item2).Sum()
Components = new List<(string Component, int Count)>(), }).ToList();
TotalCount = 0,
};
foreach (var component in engine.EngineComponents)
{
record.Components.Add(new(component.Value.Item1.ComponentName, component.Value.Item2));
record.TotalCount += component.Value.Item2;
}
list.Add(record);
}
return list;
} }
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model) public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
@ -111,5 +93,55 @@ namespace MotorPlantBusinessLogic.BusinessLogic
Orders = GetOrders(model) Orders = GetOrders(model)
}); });
} }
public List<ReportShopsViewModel> GetShops()
{
return _shopStorage.GetFullList().Select(x => new ReportShopsViewModel
{
ShopName = x.ShopName,
Engines = x.ShopEngines.Select(x => (x.Value.Item1.EngineName, x.Value.Item2)).ToList(),
TotalCount = x.ShopEngines.Select(x => x.Value.Item2).Sum()
}).ToList();
}
public List<ReportGroupOrdersViewModel> GetGroupedOrders()
{
return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportGroupOrdersViewModel
{
Date = x.Key,
OrdersCount = x.Count(),
OrdersSum = x.Select(y => y.Sum).Sum()
}).ToList();
}
public void SaveShopsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateShopsDoc(new WordShopInfo
{
FileName = model.FileName,
Title = "Список магазинов",
Shops = _shopStorage.GetFullList()
});
}
public void SaveShopsToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateShopEnginesReport(new ExcelShop
{
FileName = model.FileName,
Title = "Наполненость магазинов",
ShopEngines = GetShops()
});
}
public void SaveGroupedOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateGroupedOrdersDoc(new PdfGroupedOrdersInfo
{
FileName = model.FileName,
Title = "Список заказов сгруппированных по дате заказов",
GroupedOrders = GetGroupedOrders()
});
}
} }
} }

View File

@ -17,11 +17,13 @@ namespace MotorPlantBusinessLogic.BusinessLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IShopStorage _shopStorage; private readonly IShopStorage _shopStorage;
private readonly IEngineStorage _engineStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage) public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage, IEngineStorage engineStorage)
{ {
_logger = logger; _logger = logger;
_shopStorage = shopStorage; _shopStorage = shopStorage;
_engineStorage = engineStorage;
} }
public List<ShopViewModel> ReadList(ShopSearchModel model) public List<ShopViewModel> ReadList(ShopSearchModel model)
@ -75,6 +77,7 @@ namespace MotorPlantBusinessLogic.BusinessLogic
} }
return true; return true;
} }
public bool Delete(ShopBindingModel model) public bool Delete(ShopBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
@ -123,52 +126,70 @@ namespace MotorPlantBusinessLogic.BusinessLogic
} }
} }
public bool MakeSell(IEngineModel model, int count) public bool MakeSupply(SupplyBindingModel model)
{
return _shopStorage.SellEngines(model, count);
}
public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count)
{ {
if (model == null) if (model == null)
throw new ArgumentNullException(nameof(model)); {
if (engine == null) throw new ArgumentNullException(nameof(model));
throw new ArgumentNullException(nameof(engine)); }
if (count <= 0) if (model.Count <= 0)
throw new ArgumentNullException("Количество должно быть положительным числом"); {
throw new ArgumentException("Количество движков должно быть больше 0");
}
var shop = _shopStorage.GetElement(new ShopSearchModel
{
Id = model.ShopId
});
if (shop == null)
{
throw new ArgumentException("Магазина не существует");
}
if (shop.ShopEngines.ContainsKey(model.EngineId))
{
var oldValue = shop.ShopEngines[model.EngineId];
oldValue.Item2 += model.Count;
shop.ShopEngines[model.EngineId] = oldValue;
}
else
{
var pizza = _engineStorage.GetElement(new EngineSearchModel
{
Id = model.EngineId
});
if (pizza == null)
{
throw new ArgumentException($"Поставка: Товар с id:{model.EngineId} не найденн");
}
shop.ShopEngines.Add(model.EngineId, (pizza, model.Count));
}
ShopViewModel? curModel = _shopStorage.GetElement(model); _shopStorage.Update(new ShopBindingModel()
_logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); {
if (curModel == null) Id = shop.Id,
throw new ArgumentNullException(nameof(curModel)); ShopName = shop.ShopName,
Adress = shop.Adress,
DateOpen = shop.DateOpen,
ShopEngines = shop.ShopEngines,
MaxCount = shop.MaxCount,
});
var countItems = curModel.ShopEngines.Select(x => x.Value.Item2).Sum(); return true;
if (curModel.MaxCount - countItems < count) }
{
_logger.LogWarning("Shop is overflowed");
return false;
}
if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) public bool MakeSell(SupplySearchModel model)
{ {
curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); if (!model.EngineId.HasValue || !model.Count.HasValue)
_logger.LogInformation("Make Supply. Add Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count + pair.Item2); {
} return false;
else }
{ _logger.LogInformation("Check pizza count in all shops");
curModel.ShopEngines.Add(engine.Id, (engine, count)); if (_shopStorage.SellEngines(model))
_logger.LogInformation("Make Supply. Add new Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count); {
} _logger.LogInformation("Selling sucsess");
return true;
return Update(new() }
{ _logger.LogInformation("Selling failed");
Id = curModel.Id, return false;
ShopName = curModel.ShopName, }
DateOpen = curModel.DateOpen,
MaxCount = curModel.MaxCount,
Adress = curModel.Adress,
ShopEngines = curModel.ShopEngines,
});
}
} }
} }

View File

@ -84,28 +84,81 @@ namespace MotorPlantBusinessLogic.OfficePackage
SaveExcel(info); SaveExcel(info);
} }
/// <summary> public void CreateShopEnginesReport(ExcelShop info)
/// Создание excel-файла {
/// </summary> CreateExcel(info);
/// <param name="info"></param>
protected abstract void CreateExcel(ExcelInfo info);
/// <summary> InsertCellInWorksheet(new ExcelCellParameters
/// Добавляем новую ячейку в лист {
/// </summary> ColumnName = "A",
/// <param name="cellParameters"></param> RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var sr in info.ShopEngines)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = sr.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Engine, Count) in sr.Engines)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Engine,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = sr.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
protected abstract void CreateExcel(IDocument info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
/// <summary>
/// Объединение ячеек
/// </summary>
/// <param name="mergeParameters"></param>
protected abstract void MergeCells(ExcelMergeParameters excelParams); protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(IDocument info);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveExcel(ExcelInfo info);
} }
} }

View File

@ -48,11 +48,40 @@ namespace MotorPlantBusinessLogic.OfficePackage
SavePdf(info); SavePdf(info);
} }
public void CreateGroupedOrdersDoc(PdfGroupedOrdersInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "4cm", "3cm", "2cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата заказа", "Кол-во", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var groupedOrder in info.GroupedOrders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { groupedOrder.Date.ToShortDateString(), groupedOrder.OrdersCount.ToString(), groupedOrder.OrdersSum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupedOrders.Sum(x => x.OrdersSum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
SavePdf(info);
}
/// <summary> /// <summary>
/// Создание pdf-файла /// Создание pdf-файла
/// </summary> /// </summary>
/// <param name="info"></param> /// <param name="info"></param>
protected abstract void CreatePdf(PdfInfo info); protected abstract void CreatePdf(IDocument info);
/// <summary> /// <summary>
/// Создание параграфа с текстом /// Создание параграфа с текстом
@ -78,6 +107,6 @@ namespace MotorPlantBusinessLogic.OfficePackage
/// Сохранение файла /// Сохранение файла
/// </summary> /// </summary>
/// <param name="info"></param> /// <param name="info"></param>
protected abstract void SavePdf(PdfInfo info); protected abstract void SavePdf(IDocument info);
} }
} }

View File

@ -41,23 +41,51 @@ namespace MotorPlantBusinessLogic.OfficePackage
SaveWord(info); SaveWord(info);
} }
/// <summary> public void CreateShopsDoc(WordShopInfo info)
/// Создание doc-файла {
/// </summary> CreateWord(info);
/// <param name="info"></param> CreateParagraph(new WordParagraph
protected abstract void CreateWord(WordInfo info); {
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
/// <summary> CreateTable(new List<string> { "3000", "3000", "3000" });
/// Создание абзаца с текстом CreateRow(new WordRowParameters
/// </summary> {
/// <param name="paragraph"></param> Texts = new List<string> { "Название", "Адрес", "Дата открытия" },
/// <returns></returns> TextProperties = new WordTextProperties
{
Size = "24",
Bold = true,
JustificationType = WordJustificationType.Center
}
});
foreach (var shop in info.Shops)
{
CreateRow(new WordRowParameters
{
Texts = new List<string> { shop.ShopName, shop.Adress, shop.DateOpen.ToString() },
TextProperties = new WordTextProperties
{
Size = "22",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
protected abstract void CreateWord(IDocument info);
protected abstract void CreateParagraph(WordParagraph paragraph); protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(IDocument info);
/// <summary> protected abstract void CreateTable(List<string> colums);
/// Сохранение файла protected abstract void CreateRow(WordRowParameters rowParameters);
/// </summary>
/// <param name="info"></param>
protected abstract void SaveWord(WordInfo info);
} }
} }

View File

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{ {
public class ExcelInfo public class ExcelInfo : IDocument
{ {
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;

View File

@ -0,0 +1,11 @@
using MotorPlantContracts.ViewModels;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class ExcelShop : IDocument
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportShopsViewModel> ShopEngines { get; set; } = new();
}
}

View File

@ -0,0 +1,13 @@
using MotorPlantContracts.ViewModels;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class PdfGroupedOrdersInfo : IDocument
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportGroupOrdersViewModel> GroupedOrders { get; set; } = new();
}
}

View File

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{ {
public class PdfInfo public class PdfInfo : IDocument
{ {
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;

View File

@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{ {
public class WordInfo public class WordInfo : IDocument
{ {
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class WordRowParameters
{
public List<string> Texts { get; set; } = new();
public WordTextProperties TextProperties { get; set; } = new();
}
}

View File

@ -0,0 +1,16 @@
using MotorPlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.OfficePackage.HelperModels
{
public class WordShopInfo : IDocument
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ShopViewModel> Shops { 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 MotorPlantBusinessLogic.OfficePackage
{
public interface IDocument
{
public string FileName { get; set; }
public string Title { get; set; }
}
}

View File

@ -151,7 +151,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements
}; };
} }
protected override void CreateExcel(ExcelInfo info) protected override void CreateExcel(IDocument info)
{ {
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы) // Создаем книгу (в ней хранятся листы)
@ -280,7 +280,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements
mergeCells.Append(mergeCell); mergeCells.Append(mergeCell);
} }
protected override void SaveExcel(ExcelInfo info) protected override void SaveExcel(IDocument info)
{ {
if (_spreadsheetDocument == null) if (_spreadsheetDocument == null)
{ {

View File

@ -34,7 +34,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements
style.Font.Bold = true; style.Font.Bold = true;
} }
protected override void CreatePdf(PdfInfo info) protected override void CreatePdf(IDocument info)
{ {
_document = new Document(); _document = new Document();
DefineStyles(_document); DefineStyles(_document);
@ -96,7 +96,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements
} }
} }
protected override void SavePdf(PdfInfo info) protected override void SavePdf(IDocument info)
{ {
var renderer = new PdfDocumentRenderer(true) var renderer = new PdfDocumentRenderer(true)
{ {

View File

@ -81,7 +81,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements
return properties; return properties;
} }
protected override void CreateWord(WordInfo info) protected override void CreateWord(IDocument info)
{ {
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
@ -119,7 +119,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements
_docBody.AppendChild(docParagraph); _docBody.AppendChild(docParagraph);
} }
protected override void SaveWord(WordInfo info) protected override void SaveWord(IDocument info)
{ {
if (_docBody == null || _wordDocument == null) if (_docBody == null || _wordDocument == null)
{ {
@ -131,5 +131,77 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements
_wordDocument.Dispose(); _wordDocument.Dispose();
} }
private Table? _lastTable;
protected override void CreateTable(List<string> columns)
{
if (_docBody == null)
return;
_lastTable = new Table();
var tableProp = new TableProperties();
tableProp.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed });
tableProp.AppendChild(new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }
));
tableProp.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto });
_lastTable.AppendChild(tableProp);
TableGrid tableGrid = new TableGrid();
foreach (var column in columns)
{
tableGrid.AppendChild(new GridColumn() { Width = column });
}
_lastTable.AppendChild(tableGrid);
_docBody.AppendChild(_lastTable);
}
protected override void CreateRow(WordRowParameters rowParameters)
{
if (_docBody == null || _lastTable == null)
return;
TableRow docRow = new TableRow();
foreach (var column in rowParameters.Texts)
{
var docParagraph = new Paragraph();
WordParagraph paragraph = new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (column, rowParameters.TextProperties) },
TextProperties = rowParameters.TextProperties
};
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
}
TableCell docCell = new TableCell();
docCell.AppendChild(docParagraph);
docRow.AppendChild(docCell);
}
_lastTable.AppendChild(docRow);
}
} }
} }

View File

@ -0,0 +1,16 @@
using MotorPlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.BindingModels
{
public class SupplyBindingModel : ISupplyModel
{
public int ShopId { get; set; }
public int EngineId { get; set; }
public int Count { get; set; }
}
}

View File

@ -11,13 +11,14 @@ namespace MotorPlantContracts.BusinessLogicsContracts
public interface IReportLogic public interface IReportLogic
{ {
List<ReportEngineComponentViewModel> GetEngineComponents(); List<ReportEngineComponentViewModel> GetEngineComponents();
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model); List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
List<ReportShopsViewModel> GetShops();
List<ReportGroupOrdersViewModel> GetGroupedOrders();
void SaveEngineToWordFile(ReportBindingModel model); void SaveEngineToWordFile(ReportBindingModel model);
void SaveEngineComponentToExcelFile(ReportBindingModel model); void SaveEngineComponentToExcelFile(ReportBindingModel model);
void SaveOrdersToPdfFile(ReportBindingModel model); void SaveOrdersToPdfFile(ReportBindingModel model);
void SaveShopsToWordFile(ReportBindingModel model);
void SaveShopsToExcelFile(ReportBindingModel model);
void SaveGroupedOrdersToPdfFile(ReportBindingModel model);
} }
} }

View File

@ -14,10 +14,10 @@ namespace MotorPlantContracts.BusinessLogicsContracts
{ {
List<ShopViewModel>? ReadList(ShopSearchModel? model); List<ShopViewModel>? ReadList(ShopSearchModel? model);
ShopViewModel? ReadElement(ShopSearchModel? model); ShopViewModel? ReadElement(ShopSearchModel? model);
bool Create(ShopBindingModel? model); bool Create(ShopBindingModel model);
bool Update(ShopBindingModel? model); bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel? model); bool Delete(ShopBindingModel model);
bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); bool MakeSupply(SupplyBindingModel model);
bool MakeSell(IEngineModel model, int count); bool MakeSell(SupplySearchModel model);
} }
} }

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.SearchModels
{
public class SupplySearchModel
{
public int? EngineId { get; set; }
public int? Count { get; set; }
}
}

View File

@ -18,6 +18,7 @@ namespace MotorPlantContracts.StoragesContracts
ShopViewModel? Insert(ShopBindingModel model); ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model); ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model); ShopViewModel? Delete(ShopBindingModel model);
bool SellEngines(IEngineModel model, int count); bool SellEngines(SupplySearchModel model);
} bool RestockingShops(SupplyBindingModel model);
}
} }

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.ViewModels
{
public class ReportGroupOrdersViewModel
{
public DateTime Date { get; set; } = DateTime.Now;
public int OrdersCount { get; set; }
public double OrdersSum { get; set; }
}
}

View File

@ -0,0 +1,9 @@
namespace MotorPlantContracts.ViewModels
{
public class ReportShopsViewModel
{
public string ShopName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<(string Engine, int count)> Engines { get; set; } = new();
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantDataModels.Models
{
public interface ISupplyModel
{
int ShopId { get; }
int EngineId { get; }
int Count { get; }
}
}

View File

@ -13,10 +13,8 @@ namespace MotorPlantDatabaseImplement.Implements
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
return context.Orders return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList();
.Select(x => AccessEngineStorage(x.GetViewModel)) }
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (!model.Id.HasValue && !model.DateFrom.HasValue) if (!model.Id.HasValue && !model.DateFrom.HasValue)
@ -24,8 +22,6 @@ namespace MotorPlantDatabaseImplement.Implements
return new(); return new();
} }
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList();
}
if (model.DateFrom.HasValue) if (model.DateFrom.HasValue)
{ {
return context.Orders return context.Orders
@ -42,66 +38,58 @@ namespace MotorPlantDatabaseImplement.Implements
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (!model.Id.HasValue)
{ {
return null; return null;
} }
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
return AccessEngineStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); return context.Orders.Include(x => x.Engine)
} .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
var newOrder = Order.Create(model); using var context = new MotorPlantDatabase();
if (newOrder == null) if (model == null)
{ return null;
return null; var newOrder = Order.Create(context, model);
} if (newOrder == null)
using var context = new MotorPlantDatabase(); {
context.Orders.Add(newOrder); return null;
context.SaveChanges(); }
return AccessEngineStorage(newOrder.GetViewModel); context.Orders.Add(newOrder);
} context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
model.Id); if (order == null)
if (order == null) {
{ return null;
return null; }
} order.Update(model);
order.Update(model); context.SaveChanges();
context.SaveChanges(); return context.Orders
return AccessEngineStorage(order.GetViewModel); .Include(x => x.Engine)
} .FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
public OrderViewModel? Delete(OrderBindingModel model) }
{ public OrderViewModel? Delete(OrderBindingModel model)
using var context = new MotorPlantDatabase(); {
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); using var context = new MotorPlantDatabase();
if (element != null) var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
{ if (element != null)
context.Orders.Remove(element); {
context.SaveChanges(); var deletedElement = context.Orders
return AccessEngineStorage(element.GetViewModel); .Include(x => x.Engine)
} .FirstOrDefault(x => x.Id == model.Id)
return null; ?.GetViewModel;
} context.Orders.Remove(element);
context.SaveChanges();
public static OrderViewModel AccessEngineStorage(OrderViewModel model) return deletedElement;
{ }
if (model == null) return null;
return null; }
using var context = new MotorPlantDatabase(); }
foreach (var Engine in context.Engines)
{
if (Engine.Id == model.EngineId)
{
model.EngineName = Engine.EngineName;
break;
}
}
return model;
}
}
} }

View File

@ -84,61 +84,117 @@ namespace MotorPlantDatabaseImplement.Implements
public ShopViewModel? Update(ShopBindingModel model) public ShopViewModel? Update(ShopBindingModel model)
{ {
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); using var transaction = context.Database.BeginTransaction();
if (shop == null) try
{ {
return null; var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id);
} if (shop == null)
try {
{ return null;
if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) }
{ shop.Update(model);
throw new Exception("Не должно быть два магазина с одним названием"); context.SaveChanges();
} shop.UpdateEngines(context, model);
shop.Update(model); transaction.Commit();
shop.UpdateDresses(context, model); return shop.GetViewModel;
context.SaveChanges(); }
return shop.GetViewModel; catch
} {
catch transaction.Rollback();
{ throw;
throw; }
} }
}
public bool SellEngines(IEngineModel model, int count) public bool RestockingShops(SupplyBindingModel model)
{
using var context = new MotorPlantDatabase();
var transaction = context.Database.BeginTransaction();
var Shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList().
Where(x => x.MaxCount > x.ShopEngines.Select(x => x.Value.Item2).Sum()).ToList();
if (model == null)
{
return false;
}
try
{
foreach (Shop shop in Shops)
{
int difference = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum();
int refill = Math.Min(difference, model.Count);
model.Count -= refill;
if (shop.ShopEngines.ContainsKey(model.EngineId))
{
var datePair = shop.ShopEngines[model.EngineId];
datePair.Item2 += refill;
shop.ShopEngines[model.EngineId] = datePair;
}
else
{
var pizza = context.Engines.First(x => x.Id == model.EngineId);
shop.ShopEngines.Add(model.EngineId, (pizza, refill));
}
shop.EnginesDictionatyUpdate(context);
if (model.Count == 0)
{
transaction.Commit();
return true;
}
}
transaction.Rollback();
return false;
}
catch
{
transaction.Rollback();
throw;
}
}
public bool SellEngines(SupplySearchModel model)
{ {
if (model == null) using var context = new MotorPlantDatabase();
return false; var transaction = context.Database.BeginTransaction();
using var context = new MotorPlantDatabase(); try
using var transaction = context.Database.BeginTransaction(); {
List<ShopEngine> lst = new List<ShopEngine>(); var shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList().
foreach (var el in context.ShopEngines.Where(x => x.EngineId == model.Id)) Where(x => x.ShopEngines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.ShopEngines[model.EngineId.Value].Item2).ToList();
{
int dif = count; foreach (var shop in shops)
if (el.Count < dif) {
dif = el.Count; int residue = model.Count.Value - shop.ShopEngines[model.EngineId.Value].Item2;
el.Count -= dif; if (residue > 0)
count -= dif; {
if (el.Count == 0) shop.ShopEngines.Remove(model.EngineId.Value);
{ shop.EnginesDictionatyUpdate(context);
lst.Add(el); context.SaveChanges();
} model.Count = residue;
if (count == 0)
break; }
} else
if (count > 0) {
{ if (residue == 0)
transaction.Rollback(); shop.ShopEngines.Remove(model.EngineId.Value);
return false; else
} {
foreach (var el in lst) var dataPair = shop.ShopEngines[model.EngineId.Value];
{ dataPair.Item2 = -residue;
context.ShopEngines.Remove(el); shop.ShopEngines[model.EngineId.Value] = dataPair;
} }
context.SaveChanges();
transaction.Commit(); shop.EnginesDictionatyUpdate(context);
return true; transaction.Commit();
} return true;
}
}
transaction.Rollback();
return false;
}
catch
{
transaction.Rollback();
throw;
}
}
} }
} }

View File

@ -0,0 +1,246 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MotorPlantDatabaseImplement;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace MotorPlantDatabaseImplement.Migrations
{
[DbContext(typeof(MotorPlantDatabase))]
[Migration("20240516204547_ThirdMigtation")]
partial class ThirdMigtation
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("EngineName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.ToTable("Engines");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("EngineId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("EngineId");
b.ToTable("EngineComponents");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp without time zone");
b.Property<int>("EngineId")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("EngineId");
b.ToTable("Orders");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Adress")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateOpen")
.HasColumnType("timestamp without time zone");
b.Property<int>("MaxCount")
.HasColumnType("integer");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("EngineId")
.HasColumnType("integer");
b.Property<int>("ShopId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("EngineId");
b.HasIndex("ShopId");
b.ToTable("ShopEngines");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b =>
{
b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component")
.WithMany("EngineComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine")
.WithMany("Components")
.HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Engine");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null)
.WithMany("Orders")
.HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b =>
{
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine")
.WithMany()
.HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Shop", "Shop")
.WithMany("Engines")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Engine");
b.Navigation("Shop");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
{
b.Navigation("EngineComponents");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Engines");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace MotorPlantDatabaseImplement.Migrations namespace MotorPlantDatabaseImplement.Migrations
{ {
/// <inheritdoc /> /// <inheritdoc />
public partial class NewMig : Migration public partial class ThirdMigtation : Migration
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)

View File

@ -12,7 +12,7 @@ namespace MotorPlantDatabaseImplement.Models
[Required] [Required]
public int EngineId { get; private set; } public int EngineId { get; private set; }
public virtual Engine Engine { get; set; } = new();
[Required] [Required]
public int Count { get; private set; } public int Count { get; private set; }
@ -27,16 +27,13 @@ namespace MotorPlantDatabaseImplement.Models
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model) public static Order Create(MotorPlantDatabase context, OrderBindingModel model)
{ {
if (model == null)
{
return null;
}
return new Order() return new Order()
{ {
Id = model.Id, Id = model.Id,
EngineId = model.EngineId, EngineId = model.EngineId,
Engine = context.Engines.First(x => x.Id == model.EngineId),
Count = model.Count, Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
@ -58,6 +55,7 @@ namespace MotorPlantDatabaseImplement.Models
{ {
Id = Id, Id = Id,
EngineId = EngineId, EngineId = EngineId,
EngineName = Engine.EngineName,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,

View File

@ -15,16 +15,16 @@ namespace MotorPlantDatabaseImplement.Models
{ {
public int Id { get; private set; } public int Id { get; private set; }
[Required] [Required]
public string ShopName { get; private set; } public string ShopName { get; private set; } = string.Empty;
[Required] [Required]
public string Adress { get; private set; } public string Adress { get; private set; } = string.Empty;
[Required] [Required]
public DateTime DateOpen { get; private set; } public DateTime DateOpen { get; private set; }
[Required] [Required]
public int MaxCount { get; private set; } public int MaxCount { get; private set; }
private Dictionary<int, (IEngineModel, int)>? _shopEngines = null; private Dictionary<int, (IEngineModel, int)>? _shopEngines = null;
[NotMapped] [NotMapped]
public Dictionary<int, (IEngineModel, int)>? ShopEngines public Dictionary<int, (IEngineModel, int)> ShopEngines
{ {
get get
{ {
@ -74,7 +74,7 @@ namespace MotorPlantDatabaseImplement.Models
ShopEngines = ShopEngines ShopEngines = ShopEngines
}; };
public void UpdateDresses(MotorPlantDatabase context, ShopBindingModel model) public void UpdateEngines(MotorPlantDatabase context, ShopBindingModel model)
{ {
var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList(); var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList();
if (shopEngines != null && shopEngines.Count > 0) if (shopEngines != null && shopEngines.Count > 0)
@ -101,5 +101,14 @@ namespace MotorPlantDatabaseImplement.Models
} }
_shopEngines = null; _shopEngines = null;
} }
}
public void EnginesDictionatyUpdate(MotorPlantDatabase context)
{
UpdateEngines(context, new ShopBindingModel
{
Id = Id,
ShopEngines = ShopEngines,
});
}
}
} }

View File

@ -75,44 +75,73 @@ namespace MotorPlantFileImplement.Implements
return null; return null;
} }
public bool SellEngines(IEngineModel model, int count) public bool SellEngines(SupplySearchModel model)
{ {
var eng = _source.Engines.FirstOrDefault(x => x.Id == model.Id); if (model == null || !model.EngineId.HasValue || !model.Count.HasValue)
int store = _source.Shops.SelectMany(x => x.ShopEngines).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0); return false;
int remainingSpace = _source.Shops.Select(x => x.Engines.ContainsKey(model.EngineId.Value) ? x.Engines[model.EngineId.Value] : 0).Sum();
if (remainingSpace < model.Count)
{
return false;
}
var shops = _source.Shops.Where(x => x.Engines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.Engines[model.EngineId.Value]).ToList();
foreach (var shop in shops)
{
int residue = model.Count.Value - shop.Engines[model.EngineId.Value];
if (residue > 0)
{
shop.Engines.Remove(model.EngineId.Value);
shop.EngineUpdate();
model.Count = residue;
}
else
{
if (residue == 0)
{
shop.Engines.Remove(model.EngineId.Value);
}
else
{
shop.Engines[model.EngineId.Value] = -residue;
}
shop.EngineUpdate();
_source.SaveShops();
return true;
}
}
_source.SaveShops();
return false;
}
if (eng == null || store < count) public bool RestockingShops(SupplyBindingModel model)
{ {
return false; if (model == null || _source.Shops.Select(x => x.MaxCount - x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum() < model.Count)
} {
return false;
for (int i = 0; i < _source.Shops.Count; i++) }
{ foreach (Shop shop in _source.Shops)
var shop = _source.Shops[i]; {
var engines = shop.ShopEngines; int free_places = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum();
foreach (var engine in engines.Where(x => x.Value.Item1.Id == eng.Id)) if (free_places <= 0)
{ continue;
var selling = Math.Min(engine.Value.Item2, count); free_places = Math.Min(free_places, model.Count);
engines[engine.Value.Item1.Id] = (engine.Value.Item1, engine.Value.Item2 - selling); model.Count -= free_places;
if (shop.Engines.ContainsKey(model.EngineId))
count -= selling; {
shop.Engines[model.EngineId] += free_places;
if (count <= 0) }
{ else
break; {
} shop.Engines.Add(model.EngineId, free_places);
} }
shop.Update(new ShopBindingModel shop.EngineUpdate();
{ if (model.Count == 0)
Id = model.Id, {
ShopName = shop.ShopName, _source.SaveShops();
Adress = shop.Adress, return true;
MaxCount = shop.MaxCount, }
DateOpen = shop.DateOpen, }
ShopEngines = engines return false;
}); }
} }
_source.SaveShops();
return true;
}
}
} }

View File

@ -98,5 +98,10 @@ namespace MotorPlantFileImplement.Models
new XElement("DateOpen", DateOpen), new XElement("DateOpen", DateOpen),
new XElement("MaxCount", MaxCount), new XElement("MaxCount", MaxCount),
new XElement("ShopEngines", Engines.Select(x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); new XElement("ShopEngines", Engines.Select(x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()));
}
public void EngineUpdate()
{
_shopEngines = null;
}
}
} }

View File

@ -31,7 +31,7 @@ namespace MotorPlantListImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
var result = new List<OrderViewModel>(); var result = new List<OrderViewModel>();
if (model == null || !model.Id.HasValue) if (model == null)
{ {
return result; return result;
} }

View File

@ -108,9 +108,14 @@ namespace MotorPlantListImplement.Implements
{ {
return true; return true;
} }
public bool SellEngines(IEngineModel model, int count) public bool SellEngines(SupplySearchModel model)
{ {
return true; throw new NotImplementedException();
} }
}
public bool RestockingShops(SupplyBindingModel model)
{
throw new NotImplementedException();
}
}
} }

View File

@ -1,26 +1,26 @@
namespace MotorPlantView.Forms namespace MotorPlantView.Forms
{ {
partial class FormMain partial class FormMain
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
@ -32,10 +32,16 @@
toolStripDropDownButton1 = new ToolStripDropDownButton(); toolStripDropDownButton1 = new ToolStripDropDownButton();
КомпонентыToolStripMenuItem = new ToolStripMenuItem(); КомпонентыToolStripMenuItem = new ToolStripMenuItem();
ДвигателиToolStripMenuItem = new ToolStripMenuItem(); ДвигателиToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
поставкаToolStripMenuItem = new ToolStripMenuItem();
продажаToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem();
списокДвигателейToolStripMenuItem = new ToolStripMenuItem(); списокДвигателейToolStripMenuItem = new ToolStripMenuItem();
компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem(); компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
списокМагазиновToolStripMenuItem = new ToolStripMenuItem();
загруженностьМагазиновToolStripMenuItem = new ToolStripMenuItem();
заказыПоГруппамToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button(); buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button(); buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button(); buttonOrderReady = new Button();
@ -59,7 +65,7 @@
// toolStripDropDownButton1 // toolStripDropDownButton1
// //
toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem }); toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, магазиныToolStripMenuItem, поставкаToolStripMenuItem, продажаToolStripMenuItem });
toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.ImageTransparentColor = Color.Magenta;
toolStripDropDownButton1.Name = "toolStripDropDownButton1"; toolStripDropDownButton1.Name = "toolStripDropDownButton1";
toolStripDropDownButton1.Size = new Size(88, 22); toolStripDropDownButton1.Size = new Size(88, 22);
@ -79,9 +85,30 @@
ДвигателиToolStripMenuItem.Text = "Двигатели"; ДвигателиToolStripMenuItem.Text = "Двигатели";
ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
// //
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(145, 22);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click;
//
// поставкаToolStripMenuItem
//
поставкаToolStripMenuItem.Name = "поставкаToolStripMenuItem";
поставкаToolStripMenuItem.Size = new Size(145, 22);
поставкаToolStripMenuItem.Text = "Поставка";
поставкаToolStripMenuItem.Click += поставкаToolStripMenuItem_Click;
//
// продажаToolStripMenuItem
//
продажаToolStripMenuItem.Name = "продажаToolStripMenuItem";
продажаToolStripMenuItem.Size = new Size(145, 22);
продажаToolStripMenuItem.Text = "Продажа";
продажаToolStripMenuItem.Click += продажаToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem // отчетыToolStripMenuItem
// //
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, загруженностьМагазиновToolStripMenuItem, заказыПоГруппамToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(60, 25); отчетыToolStripMenuItem.Size = new Size(60, 25);
отчетыToolStripMenuItem.Text = "Отчеты"; отчетыToolStripMenuItem.Text = "Отчеты";
@ -107,6 +134,27 @@
списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
// //
// списокМагазиновToolStripMenuItem
//
списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem";
списокМагазиновToolStripMenuItem.Size = new Size(228, 22);
списокМагазиновToolStripMenuItem.Text = "Список магазинов";
списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click;
//
// загруженностьМагазиновToolStripMenuItem
//
загруженностьМагазиновToolStripMenuItem.Name = агруженностьМагазиновToolStripMenuItem";
загруженностьМагазиновToolStripMenuItem.Size = new Size(228, 22);
загруженностьМагазиновToolStripMenuItem.Text = "Загруженность магазинов";
загруженностьМагазиновToolStripMenuItem.Click += загруженностьМагазиновToolStripMenuItem_Click;
//
// заказыПоГруппамToolStripMenuItem
//
заказыПоГруппамToolStripMenuItem.Name = аказыПоГруппамToolStripMenuItem";
заказыПоГруппамToolStripMenuItem.Size = new Size(228, 22);
заказыПоГруппамToolStripMenuItem.Text = "Заказы по группам";
заказыПоГруппамToolStripMenuItem.Click += заказыПоГруппамToolStripMenuItem_Click;
//
// buttonCreateOrder // buttonCreateOrder
// //
buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right;
@ -203,7 +251,7 @@
PerformLayout(); PerformLayout();
} }
#endregion #endregion
private ToolStrip toolStrip1; private ToolStrip toolStrip1;
private Button buttonCreateOrder; private Button buttonCreateOrder;
@ -219,5 +267,11 @@
private ToolStripMenuItem списокДвигателейToolStripMenuItem; private ToolStripMenuItem списокДвигателейToolStripMenuItem;
private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem поставкаToolStripMenuItem;
private ToolStripMenuItem продажаToolStripMenuItem;
private ToolStripMenuItem списокМагазиновToolStripMenuItem;
private ToolStripMenuItem загруженностьМагазиновToolStripMenuItem;
private ToolStripMenuItem заказыПоГруппамToolStripMenuItem;
} }
} }

View File

@ -18,6 +18,7 @@ namespace MotorPlantView.Forms
_orderLogic = orderLogic; _orderLogic = orderLogic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
} }
private void FormMain_Load(object sender, EventArgs e) private void FormMain_Load(object sender, EventArgs e)
{ {
LoadData(); LoadData();
@ -29,38 +30,41 @@ namespace MotorPlantView.Forms
{ {
var list = _orderLogic.ReadList(null); var list = _orderLogic.ReadList(null);
if (list != null) if (list != null)
{ {
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["EngineId"].Visible = false; dataGridView.Columns["EngineId"].Visible = false;
dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
_logger.LogInformation("Загрузка заказов"); _logger.LogInformation("Загрузка заказов");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки заказов"); _logger.LogError(ex, "Ошибка загрузки заказов");
} }
} }
private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form) private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{ {
form.ShowDialog(); var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
}
} if (service is FormComponents form)
private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) {
{ form.ShowDialog();
var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); }
}
private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEngines));
if (service is FormEngines form) if (service is FormEngines form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void buttonCreateOrder_Click(object sender, EventArgs e) private void buttonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
@ -70,6 +74,7 @@ namespace MotorPlantView.Forms
LoadData(); LoadData();
} }
} }
private void buttonTakeOrderInWork_Click(object sender, EventArgs e) private void buttonTakeOrderInWork_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
@ -95,6 +100,7 @@ namespace MotorPlantView.Forms
} }
} }
} }
private void buttonOrderReady_Click(object sender, EventArgs e) private void buttonOrderReady_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
@ -118,6 +124,7 @@ namespace MotorPlantView.Forms
} }
} }
} }
private void buttonIssuedOrder_Click(object sender, EventArgs e) private void buttonIssuedOrder_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
@ -139,10 +146,12 @@ namespace MotorPlantView.Forms
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
private void buttonRef_Click(object sender, EventArgs e) private void buttonRef_Click(object sender, EventArgs e)
{ {
LoadData(); LoadData();
@ -175,5 +184,60 @@ namespace MotorPlantView.Forms
form.ShowDialog(); form.ShowDialog();
} }
} }
private void поставкаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSupply));
if (service is FormSupply form)
{
form.ShowDialog();
}
}
private void продажаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSell));
if (service is FormSell form)
{
form.ShowDialog();
}
}
private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void загруженностьМагазиновToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShop));
if (service is FormReportShop form)
{
form.ShowDialog();
}
}
private void заказыПоГруппамToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders));
if (service is FormReportGroupedOrders form)
{
form.ShowDialog();
}
}
private void магазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
} }
} }

View File

@ -0,0 +1,86 @@
namespace MotorPlantView
{
partial class FormReportGroupedOrders
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel = new System.Windows.Forms.Panel();
this.buttonToPDF = new System.Windows.Forms.Button();
this.buttonMake = new System.Windows.Forms.Button();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonToPDF);
this.panel.Controls.Add(this.buttonMake);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(970, 52);
this.panel.TabIndex = 1;
//
// buttonToPDF
//
this.buttonToPDF.Location = new System.Drawing.Point(486, 12);
this.buttonToPDF.Name = "buttonToPDF";
this.buttonToPDF.Size = new System.Drawing.Size(411, 29);
this.buttonToPDF.TabIndex = 5;
this.buttonToPDF.Text = "В PDF";
this.buttonToPDF.UseVisualStyleBackColor = true;
this.buttonToPDF.Click += new System.EventHandler(this.buttonToPDF_Click);
//
// buttonMake
//
this.buttonMake.Location = new System.Drawing.Point(49, 12);
this.buttonMake.Name = "buttonMake";
this.buttonMake.Size = new System.Drawing.Size(377, 29);
this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true;
this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click);
//
// FormReportGroupedOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(970, 450);
this.Controls.Add(this.panel);
this.Name = "FormReportGroupedOrders";
this.Text = "Отчёт по группированным заказам ";
this.panel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonToPDF;
private Button buttonMake;
}
}

View File

@ -0,0 +1,80 @@
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MotorPlantView
{
public partial class FormReportGroupedOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportGroupedOrders(ILogger<FormReportGroupedOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\salih\\OneDrive\\Рабочий стол\\MotorPlant\\MotorPlant\\MotorPlantView\\ReportGroupedOrders.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void ButtonMake_Click(object sender, EventArgs e)
{
try
{
var dataSource = _logic.GetGroupedOrders();
var source = new ReportDataSource("DataSetGroupedOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка группированных заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка группированных заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonToPDF_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveGroupedOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName,
});
_logger.LogInformation("Сохранение списка группированных заказов");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка группированных заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,116 @@
namespace MotorPlantView
{
partial class FormReportShop
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.buttonSaveToExcel = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ColumnShop = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnPizza = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonSaveToExcel
//
this.buttonSaveToExcel.Location = new System.Drawing.Point(0, 6);
this.buttonSaveToExcel.Name = "buttonSaveToExcel";
this.buttonSaveToExcel.Size = new System.Drawing.Size(223, 29);
this.buttonSaveToExcel.TabIndex = 3;
this.buttonSaveToExcel.Text = "Сохранить в Excel";
this.buttonSaveToExcel.UseVisualStyleBackColor = true;
this.buttonSaveToExcel.Click += new System.EventHandler(this.ButtonSaveToExcel_Click);
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.AllowUserToOrderColumns = true;
this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnShop,
this.ColumnPizza,
this.ColumnCount});
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Bottom;
this.dataGridView.Location = new System.Drawing.Point(0, 47);
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(598, 403);
this.dataGridView.TabIndex = 2;
//
// ColumnShop
//
this.ColumnShop.FillWeight = 130F;
this.ColumnShop.HeaderText = "Магазин";
this.ColumnShop.MinimumWidth = 6;
this.ColumnShop.Name = "ColumnShop";
this.ColumnShop.ReadOnly = true;
//
// ColumnPizza
//
this.ColumnPizza.FillWeight = 140F;
this.ColumnPizza.HeaderText = "Пицца";
this.ColumnPizza.MinimumWidth = 6;
this.ColumnPizza.Name = "ColumnPizza";
this.ColumnPizza.ReadOnly = true;
//
// ColumnCount
//
this.ColumnCount.FillWeight = 90F;
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.MinimumWidth = 6;
this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.ReadOnly = true;
//
// FormReportShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(598, 450);
this.Controls.Add(this.buttonSaveToExcel);
this.Controls.Add(this.dataGridView);
this.Name = "FormReportShop";
this.Text = "Наполненость магазинов";
this.Load += new System.EventHandler(this.FormReportShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonSaveToExcel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumnShop;
private DataGridViewTextBoxColumn ColumnPizza;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,78 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MotorPlantView
{
public partial class FormReportShop : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShop(ILogger<FormReportShop> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportShop_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShops();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" });
foreach (var listElem in elem.Engines)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка пицц по магазинам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка пицц по магазинам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSaveToExcel_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveShopsToExcelFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка пицц по магазинам");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка пицц по магазинам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -10,6 +10,7 @@ using System.Windows.Forms;
using MotorPlantDataModels.Models; using MotorPlantDataModels.Models;
using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.ViewModels; using MotorPlantContracts.ViewModels;
using MotorPlantContracts.SearchModels;
namespace MotorPlantView namespace MotorPlantView
{ {
@ -73,44 +74,34 @@ namespace MotorPlantView
private void buttonSave_Click(object sender, EventArgs e) private void buttonSave_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxCount.Text)) if (comboBoxEngine.SelectedValue == null)
{ {
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); return;
return; }
} try
if (comboBoxEngine.SelectedValue == null) {
{ bool resout = _shopLogic.MakeSell(new SupplySearchModel
MessageBox.Show("Выберите двигатель", "Ошибка", {
MessageBoxButtons.OK, MessageBoxIcon.Error); EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue),
return; Count = Convert.ToInt32(textBoxCount.Text)
} });
if (resout)
try {
{ MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
int count = Convert.ToInt32(textBoxCount.Text); DialogResult = DialogResult.OK;
Close();
bool res = _shopLogic.MakeSell( }
_engineLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxEngine.SelectedValue) }), else
count {
); MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
if (!res) }
{ catch (Exception ex)
throw new Exception("Ошибка при продаже."); {
} MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Продажа прошла успешно"); }
DialogResult = DialogResult.OK;
Close();
}
catch (Exception err)
{
MessageBox.Show("Ошибка продажи");
return;
}
}
private void buttonCancel_Click(object sender, EventArgs e) private void buttonCancel_Click(object sender, EventArgs e)
{ {

View File

@ -1,4 +1,5 @@
using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels; using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels; using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models; using MotorPlantDataModels.Models;
@ -85,49 +86,35 @@ namespace MotorPlantView
private void SaveButton_Click(object sender, EventArgs e) private void SaveButton_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(CountTextBox.Text)) if (ShopComboBox.SelectedValue == null)
{ {
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if (EngineComboBox.SelectedValue == null) if (EngineComboBox.SelectedValue == null)
{ {
MessageBox.Show("Выберите двигатель", "Ошибка", MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if (ShopComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try try
{ {
int count = Convert.ToInt32(CountTextBox.Text); var operationResult = _shopLogic.MakeSupply(new SupplyBindingModel
bool res = _shopLogic.MakeSupply(
new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) },
_engineLogic.ReadElement(new() { Id = Convert.ToInt32(EngineComboBox.SelectedValue) }),
count
);
if (!res)
{ {
throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); ShopId = Convert.ToInt32(ShopComboBox.SelectedValue),
EngineId = Convert.ToInt32(EngineComboBox.SelectedValue),
Count = Convert.ToInt32(CountTextBox.Text)
});
if (!operationResult)
{
throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах.");
} }
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Пополнение прошло успешно");
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Close(); Close();
} }
catch (Exception er) catch (Exception ex)
{ {
MessageBox.Show("Ошибка пополнения"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
} }
} }

View File

@ -44,10 +44,13 @@ namespace MotorPlantView
services.AddTransient<IComponentStorage, ComponentStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IEngineStorage, EngineStorage>(); services.AddTransient<IEngineStorage, EngineStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IEngineLogic, EngineLogic>(); services.AddTransient<IEngineLogic, EngineLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
@ -59,8 +62,14 @@ namespace MotorPlantView
services.AddTransient<FormEngine>(); services.AddTransient<FormEngine>();
services.AddTransient<FormEngineComponent>(); services.AddTransient<FormEngineComponent>();
services.AddTransient<FormEngines>(); services.AddTransient<FormEngines>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSell>();
services.AddTransient<FormReportEngineComponents>(); services.AddTransient<FormReportEngineComponents>();
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportShop>();
services.AddTransient<FormReportGroupedOrders>();
} }
} }
} }

View File

@ -0,0 +1,441 @@
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<AutoRefresh>0</AutoRefresh>
<DataSources>
<DataSource Name="PrecastConcretePlantContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>20791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetGroupedOrders">
<Query>
<DataSourceName>PrecastConcretePlantContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="Date">
<DataField>Date</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="OrdersCount">
<DataField>OrdersCount</DataField>
<rd:TypeName>System.Int32</rd:TypeName>
</Field>
<Field Name="OrdersSum">
<DataField>OrdersSum</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>PrecastConcretePlantContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportGroupOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>PrecastConcretePlantContracts.ViewModels.ReportGroupOrdersViewModel, PrecastConcretePlantContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Отчёт по заказам</Value>
<Style />
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>0.6cm</Height>
<Width>16.51cm</Width>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="ReportParameterPeriod">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Parameters!ReportParameterPeriod.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<rd:DefaultName>ReportParameterPeriod</rd:DefaultName>
<Top>0.6cm</Top>
<Height>0.6cm</Height>
<Width>16.51cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>3.90406cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.97461cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.65711cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="TextboxDate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата создания</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="TextboxCount">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Количество заказов</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="TextboxSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Общая сумма заказов</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Date">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Date.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Date</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="OrdersCount">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!OrdersCount.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>OrdersCount</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="OrdersSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!OrdersSum.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>OrdersSum</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
<TablixColumnHierarchy>
<TablixMembers>
<TablixMember />
<TablixMember />
<TablixMember />
</TablixMembers>
</TablixColumnHierarchy>
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
</TablixMember>
<TablixMember>
<Group Name="Подробности" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
<DataSetName>DataSetGroupedOrders</DataSetName>
<Top>1.88242cm</Top>
<Left>2.68676cm</Left>
<Height>1.2cm</Height>
<Width>11.53578cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxResout">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Итого:</Value>
<Style />
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>3.29409cm</Top>
<Left>8.06542cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>3</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="TextboxFullSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!OrdersSum.Value, "DataSetGroupedOrders")</Value>
<Style>
<Format>0.00;(0.00)</Format>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>3.29409cm</Top>
<Left>10.70653cm</Left>
<Height>0.6cm</Height>
<Width>3.48072cm</Width>
<ZIndex>4</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</ReportItems>
<Height>2in</Height>
<Style />
</Body>
<Width>6.5in</Width>
<Page>
<PageHeight>29.7cm</PageHeight>
<PageWidth>21cm</PageWidth>
<LeftMargin>2cm</LeftMargin>
<RightMargin>2cm</RightMargin>
<TopMargin>2cm</TopMargin>
<BottomMargin>2cm</BottomMargin>
<ColumnSpacing>0.13cm</ColumnSpacing>
<Style />
</Page>
</ReportSection>
</ReportSections>
<ReportParameters>
<ReportParameter Name="ReportParameterPeriod">
<DataType>String</DataType>
<Nullable>true</Nullable>
<Prompt>ReportParameter1</Prompt>
</ReportParameter>
</ReportParameters>
<ReportParametersLayout>
<GridLayoutDefinition>
<NumberOfColumns>4</NumberOfColumns>
<NumberOfRows>2</NumberOfRows>
<CellDefinitions>
<CellDefinition>
<ColumnIndex>0</ColumnIndex>
<RowIndex>0</RowIndex>
<ParameterName>ReportParameterPeriod</ParameterName>
</CellDefinition>
</CellDefinitions>
</GridLayoutDefinition>
</ReportParametersLayout>
<rd:ReportUnitType>Cm</rd:ReportUnitType>
<rd:ReportID>b5a8ad5e-1151-4687-8576-a5270295c079</rd:ReportID>
</Report>