WIP: ПИбд-23 Тихоненков Алексей Евгеньевич Лабораторная работа №4 (Усложненная) #13

Closed
YourDax wants to merge 11 commits from Lab4HARD into Lab4
69 changed files with 4525 additions and 47 deletions

1
.gitignore vendored
View File

@ -398,3 +398,4 @@ FodyWeavers.xsd
# JetBrains Rider
*.sln.iml
/CarpentryWorkshop/ImplementationExtensions

View File

@ -95,10 +95,10 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id: { Id}", model.ComponentName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new ComponentSearchModel
{
ComponentName = model.ComponentName
});
var element = _componentStorage.GetElement(new ComponentSearchModel
{
ComponentName = model.ComponentName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");

View File

@ -17,10 +17,13 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
private readonly IShopStorage _shopStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopStorage shopStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopStorage=shopStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
@ -105,8 +108,21 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
var order = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
Id = model.Id,
});
if (order == null)
{
throw new ArgumentNullException(nameof(order));
}
if (!_shopStorage.RestockingShops(new SupplyBindingModel
{
WoodId = order.WoodId,
Count = order.Count
}))
{
throw new ArgumentException("Недостаточно места");
}
if (order == null)
{
throw new Exception("Не найден заказ");

View File

@ -16,18 +16,21 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IWoodStorage woodStorage, IComponentStorage componentStorage, IOrderStorage orderStorage,
public ReportLogic(IWoodStorage woodStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_woodStorage = woodStorage;
_componentStorage = componentStorage;
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
@ -127,5 +130,54 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
Orders = GetOrders(model)
});
}
public List<ReportShopsViewModel> GetShops()
{
return _shopStorage.GetFullList().Select(x => new ReportShopsViewModel
{
ShopName = x.ShopName,
Woods = x.ShopWoods.Select(x => (x.Value.Item1.WoodName, x.Value.Item2)).ToList(),
TotalCount = x.ShopWoods.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.CreateShopWoodsReport(new ExcelShop
{
FileName = model.FileName,
Title = "Наполненость магазинов",
ShopWoods = GetShops()
});
}
public void SaveGroupedOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateGroupedOrdersDoc(new PdfGroupedOrdersInfo
{
FileName = model.FileName,
Title = "Список заказов сгруппированных по дате заказов",
GroupedOrders = GetGroupedOrders()
});
}
}
}

View File

@ -0,0 +1,170 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
private readonly IWoodStorage _woodStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage, IWoodStorage woodStorage)
{
_logger = logger;
_shopStorage = shopStorage;
_woodStorage = woodStorage;
}
public List<ShopViewModel> ReadList(ShopSearchModel model)
{
_logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id);
var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool MakeSupply(SupplyBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (model.Count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0");
}
var shop = _shopStorage.GetElement(new ShopSearchModel
{
Id = model.ShopId
});
if (shop == null)
{
throw new ArgumentException("Магазина не существует");
}
if (shop.ShopWoods.ContainsKey(model.WoodId))
{
var oldValue = shop.ShopWoods[model.WoodId];
oldValue.Item2 += model.Count;
shop.ShopWoods[model.WoodId] = oldValue;
}
else
{
var wood = _woodStorage.GetElement(new WoodSearchModel
{
Id = model.WoodId
});
if (wood == null)
{
throw new ArgumentException($"Поставка: Товар с id:{model.WoodId} не найден");
}
shop.ShopWoods.Add(model.WoodId, (wood, model.Count));
}
return true;
}
public ShopViewModel ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Address))
{
throw new ArgumentException("Адрес магазина длжен быть заполнен", nameof(model.Address));
}
if (string.IsNullOrEmpty(model.ShopName))
{
throw new ArgumentException("Название магазина должно быть заполнено", nameof(model.ShopName));
}
_logger.LogInformation("Shop. ShopName:{ShopName}.Adres:{Adres}.OpeningDate:{OpeningDate}.Id:{ Id}", model.ShopName, model.Address, model.DateOpen, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool Sale(SupplySearchModel model)
{
if (!model.WoodId.HasValue || !model.Count.HasValue)
{
return false;
}
_logger.LogInformation("Check wood count in all shops");
if (_shopStorage.Sale(model))
{
_logger.LogInformation("Selling success");
return true;
}
_logger.LogInformation("Selling failed");
return false;
}
}
}

View File

@ -14,6 +14,7 @@
<ItemGroup>
<ProjectReference Include="..\CarpentryWorkshopContracts\CarpentryWorkshopContracts.csproj" />
<ProjectReference Include="..\CarpentryWorkshopDataModels\CarpentryWorkshopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -79,12 +79,84 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage
SaveExcel(info);
}
public void CreateShopWoodsReport(ExcelShop info)
{
CreateExcel(info);
/// <summary>
/// Создание excel-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateExcel(ExcelInfo info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var sr in info.ShopWoods)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = sr.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Wood, Count) in sr.Woods)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Wood,
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
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);
}
/// <summary>
/// Создание excel-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateExcel(IDocument info);
/// <summary>
/// Добавляем новую ячейку в лист
@ -102,6 +174,6 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveExcel(ExcelInfo info);
protected abstract void SaveExcel(IDocument info);
}
}

View File

@ -33,12 +33,40 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage
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>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfo info);
protected abstract void CreatePdf(IDocument info);
/// <summary>
/// Создание параграфа с текстом
@ -64,6 +92,6 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfo info);
protected abstract void SavePdf(IDocument info);
}
}

View File

@ -36,12 +36,52 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage
SaveWord(info);
}
public void CreateShopsDoc(WordShopInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
CreateTable(new List<string> { "3000", "3000", "3000" });
CreateRow(new WordRowParameters
{
Texts = new List<string> { "Название", "Адрес", "Дата открытия" },
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.Address, shop.DateOpen.ToString() },
TextProperties = new WordTextProperties
{
Size = "22",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateWord(IDocument info);
/// <summary>
/// Создание абзаца с текстом
@ -54,6 +94,8 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveWord(WordInfo info);
protected abstract void SaveWord(IDocument info);
protected abstract void CreateTable(List<string> colums);
protected abstract void CreateRow(WordRowParameters rowParameters);
}
}

View File

@ -2,7 +2,7 @@
namespace CarpentryWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
public class ExcelInfo : IDocument
{
public string FileName { get; set; } = string.Empty;

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarpentryWorkshopContracts.ViewModels;
namespace CarpentryWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class ExcelShop : IDocument
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportShopsViewModel> ShopWoods { get; set; } = new();
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarpentryWorkshopContracts.ViewModels;
namespace CarpentryWorkshopBusinessLogic.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

@ -2,7 +2,7 @@
namespace CarpentryWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfo
public class PdfInfo : IDocument
{
public string FileName { get; set; } = string.Empty;

View File

@ -2,7 +2,7 @@
namespace CarpentryWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
public class WordInfo : IDocument
{
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 CarpentryWorkshopBusinessLogic.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 CarpentryWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopBusinessLogic.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 CarpentryWorkshopBusinessLogic.OfficePackage
{
public interface IDocument
{
public string FileName { get; set; }
public string Title { get; set; }
}
}

View File

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

View File

@ -3,6 +3,7 @@ using CarpentryWorkshopBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using System.Text;
namespace CarpentryWorkshopBusinessLogic.OfficePackage.Implements
{
@ -16,6 +17,7 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage.Implements
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
@ -39,7 +41,7 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage.Implements
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo info)
protected override void CreatePdf(IDocument info)
{
_document = new Document();
DefineStyles(_document);
@ -101,7 +103,7 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage.Implements
}
}
protected override void SavePdf(PdfInfo info)
protected override void SavePdf(IDocument info)
{
var renderer = new PdfDocumentRenderer(true)
{

View File

@ -81,7 +81,7 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage.Implements
return properties;
}
protected override void CreateWord(WordInfo info)
protected override void CreateWord(IDocument info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
@ -119,7 +119,7 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage.Implements
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfo info)
protected override void SaveWord(IDocument info)
{
if (_docBody == null || _wordDocument == null)
{
@ -131,5 +131,76 @@ namespace CarpentryWorkshopBusinessLogic.OfficePackage.Implements
_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,14 @@
using CarpentryWorkshopDataModels.Models;
namespace CarpentryWorkshopContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime DateOpen { get; set; }
public Dictionary<int, (IWoodModel, int)> ShopWoods { get; set; } = new();
public int WoodMaxCount { get; set; }
}
}

View File

@ -0,0 +1,11 @@
using CarpentryWorkshopDataModels.Models;
namespace CarpentryWorkshopContracts.BindingModels
{
public class SupplyBindingModel : ISupplyModel
{
public int ShopId { get; set; }
public int WoodId { get; set; }
public int Count { get; set; }
}
}

View File

@ -35,5 +35,11 @@ namespace CarpentryWorkshopContracts.BusinessLogicsContracts
/// </summary>
/// <param name="model"></param>
void SaveOrdersToPdfFile(ReportBindingModel model);
List<ReportShopsViewModel> GetShops();
List<ReportGroupOrdersViewModel> GetGroupedOrders();
void SaveShopsToWordFile(ReportBindingModel model);
void SaveShopsToExcelFile(ReportBindingModel model);
void SaveGroupedOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,18 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
namespace CarpentryWorkshopContracts.BusinessLogicsContracts
{
public interface IShopLogic
{
List<ShopViewModel>? ReadList(ShopSearchModel? model);
ShopViewModel? ReadElement(ShopSearchModel model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool MakeSupply(SupplyBindingModel model);
bool Sale(SupplySearchModel model);
}
}

View File

@ -0,0 +1,8 @@
namespace CarpentryWorkshopContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? ShopName { get; set; }
}
}

View File

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

View File

@ -0,0 +1,24 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.StoragesContracts
{
public interface IShopStorage
{
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? GetElement(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool Sale(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 CarpentryWorkshopContracts.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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.ViewModels
{
public class ReportShopsViewModel
{
public string ShopName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<(string Wood, int count)> Woods { get; set; } = new();
}
}

View File

@ -0,0 +1,19 @@
using CarpentryWorkshopDataModels.Models;
using System.ComponentModel;
namespace CarpentryWorkshopContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; }
[DisplayName("Адрес магазина")]
public string Address { get; set; }
[DisplayName("Дата открытия")]
public DateTime DateOpen { get; set; }
public Dictionary<int, (IWoodModel, int)> ShopWoods { get; set; } = new();
[DisplayName("Вместимость")]
public int WoodMaxCount { get; set; }
}
}

View File

@ -0,0 +1,11 @@
namespace CarpentryWorkshopDataModels.Models
{
public interface IShopModel : IId
{
string ShopName { get; }
string Address { get; }
DateTime DateOpen { get; }
Dictionary<int, (IWoodModel, int)> ShopWoods { get; }
public int WoodMaxCount { get; }
}
}

View File

@ -0,0 +1,9 @@
namespace CarpentryWorkshopDataModels.Models
{
public interface ISupplyModel
{
int ShopId { get; }
int WoodId { get; }
int Count { get; }
}
}

View File

@ -17,10 +17,14 @@ namespace CarpentryWorkshopDatabaseImplement
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=CarpentryWorkshopDatabaseFull;Username=postgres;Password=postgres");
}
base.OnConfiguring(optionsBuilder);
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Wood> Woods { set; get; }
public virtual DbSet<WoodComponent> WoodComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { get; set; }
public virtual DbSet<ShopWood> ShopWoods { get; set; }
}
}

View File

@ -7,13 +7,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.3">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.3" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,209 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDatabaseImplement.Models;
using CarpentryWorkshopDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var element = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
return context.Shops
.Include(x => x.Woods)
.ThenInclude(x => x.Wood)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
using var context = new CarpentryWorkshopDatabase();
return context.Shops
.Include(x => x.Woods)
.ThenInclude(x => x.Wood)
.Select(x => x.GetViewModel)
.Where(x => x.ShopName.Contains(model.ShopName ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
using var context = new CarpentryWorkshopDatabase();
return context.Shops
.Include(x => x.Woods)
.ThenInclude(x => x.Wood)
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
try
{
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
if (context.Shops.Any(x => x.ShopName == newShop.ShopName))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
context.Shops.Add(newShop);
context.SaveChanges();
return newShop.GetViewModel;
}
catch
{
throw;
}
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
try
{
if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id)))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
shop.Update(model);
shop.UpdateWoods(context, model);
context.SaveChanges();
return shop.GetViewModel;
}
catch
{
throw;
}
}
public bool RestockingShops(SupplyBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var transaction = context.Database.BeginTransaction();
var Shops = context.Shops.Include(x => x.Woods).ThenInclude(x => x.Wood).ToList().
Where(x => x.WoodMaxCount > x.ShopWoods.Select(x => x.Value.Item2).Sum()).ToList();
if (model == null)
{
return false;
}
try
{
foreach (Shop shop in Shops)
{
int difference = shop.WoodMaxCount - shop.ShopWoods.Select(x => x.Value.Item2).Sum();
int refill = Math.Min(difference, model.Count);
model.Count -= refill;
if (shop.ShopWoods.ContainsKey(model.WoodId))
{
var datePair = shop.ShopWoods[model.WoodId];
datePair.Item2 += refill;
shop.ShopWoods[model.WoodId] = datePair;
}
else
{
var Wood = context.Woods.First(x => x.Id == model.WoodId);
shop.ShopWoods.Add(model.WoodId, (Wood, refill));
}
shop.WoodsDictionatyUpdate(context);
if (model.Count == 0)
{
transaction.Commit();
return true;
}
}
transaction.Rollback();
return false;
}
catch
{
transaction.Rollback();
throw;
}
}
public bool Sale(SupplySearchModel model)
{
using var context = new CarpentryWorkshopDatabase();
var transaction = context.Database.BeginTransaction();
try
{
var shops = context.Shops.Include(x => x.Woods).ThenInclude(x => x.Wood).ToList().
Where(x => x.ShopWoods.ContainsKey(model.WoodId.Value)).OrderByDescending(x => x.ShopWoods[model.WoodId.Value].Item2).ToList();
foreach (var shop in shops)
{
int residue = model.Count.Value - shop.ShopWoods[model.WoodId.Value].Item2;
if (residue > 0)
{
shop.ShopWoods.Remove(model.WoodId.Value);
shop.WoodsDictionatyUpdate(context);
context.SaveChanges();
model.Count = residue;
}
else
{
if (residue == 0)
shop.ShopWoods.Remove(model.WoodId.Value);
else
{
var dataPair = shop.ShopWoods[model.WoodId.Value];
dataPair.Item2 = -residue;
shop.ShopWoods[model.WoodId.Value] = dataPair;
}
shop.WoodsDictionatyUpdate(context);
transaction.Commit();
return true;
}
}
transaction.Rollback();
return false;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace CarpentryWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(CarpentryWorkshopDatabase))]
[Migration("20240331170647_InitialCreate")]
[Migration("20240513151351_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
@ -20,7 +20,7 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.3")
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@ -57,10 +57,10 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp with time zone");
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
.HasColumnType("timestamp without time zone");
b.Property<int>("Status")
.HasColumnType("integer");
@ -82,6 +82,59 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("Orders");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateOpen")
.HasColumnType("timestamp without time zone");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("WoodMaxCount")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.ShopWood", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("ShopId")
.HasColumnType("integer");
b.Property<int>("WoodId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ShopId");
b.HasIndex("WoodId");
b.ToTable("ShopWoods");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Property<int>("Id")
@ -137,6 +190,25 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
.IsRequired();
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.ShopWood", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Woods")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", "Wood")
.WithMany("ShopWoods")
.HasForeignKey("WoodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Shop");
b.Navigation("Wood");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.WoodComponent", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Component", "Component")
@ -161,11 +233,18 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.Navigation("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Woods");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("ShopWoods");
});
#pragma warning restore 612, 618
}

View File

@ -26,6 +26,22 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ShopName = table.Column<string>(type: "text", nullable: false),
Address = table.Column<string>(type: "text", nullable: false),
DateOpen = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
WoodMaxCount = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Woods",
columns: table => new
@ -51,8 +67,8 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
Count = table.Column<int>(type: "integer", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
Status = table.Column<int>(type: "integer", nullable: false),
DateCreate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
DateImplement = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
DateCreate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
DateImplement = table.Column<DateTime>(type: "timestamp without time zone", nullable: true)
},
constraints: table =>
{
@ -65,6 +81,33 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ShopWoods",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
WoodId = table.Column<int>(type: "integer", nullable: false),
ShopId = table.Column<int>(type: "integer", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopWoods", x => x.Id);
table.ForeignKey(
name: "FK_ShopWoods_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopWoods_Woods_WoodId",
column: x => x.WoodId,
principalTable: "Woods",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "WoodComponents",
columns: table => new
@ -97,6 +140,16 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
table: "Orders",
column: "WoodId");
migrationBuilder.CreateIndex(
name: "IX_ShopWoods_ShopId",
table: "ShopWoods",
column: "ShopId");
migrationBuilder.CreateIndex(
name: "IX_ShopWoods_WoodId",
table: "ShopWoods",
column: "WoodId");
migrationBuilder.CreateIndex(
name: "IX_WoodComponents_ComponentId",
table: "WoodComponents",
@ -114,9 +167,15 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ShopWoods");
migrationBuilder.DropTable(
name: "WoodComponents");
migrationBuilder.DropTable(
name: "Shops");
migrationBuilder.DropTable(
name: "Components");

View File

@ -17,7 +17,7 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.3")
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@ -54,10 +54,10 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
.HasColumnType("integer");
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp with time zone");
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone");
.HasColumnType("timestamp without time zone");
b.Property<int>("Status")
.HasColumnType("integer");
@ -79,6 +79,59 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("Orders");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateOpen")
.HasColumnType("timestamp without time zone");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("WoodMaxCount")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.ShopWood", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("ShopId")
.HasColumnType("integer");
b.Property<int>("WoodId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ShopId");
b.HasIndex("WoodId");
b.ToTable("ShopWoods");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Property<int>("Id")
@ -134,6 +187,25 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
.IsRequired();
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.ShopWood", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Woods")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", "Wood")
.WithMany("ShopWoods")
.HasForeignKey("WoodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Shop");
b.Navigation("Wood");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.WoodComponent", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Component", "Component")
@ -158,11 +230,18 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.Navigation("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Woods");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("ShopWoods");
});
#pragma warning restore 612, 618
}

View File

@ -0,0 +1,129 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string ShopName { get; set; } = string.Empty;
[Required]
public string Address { get; set; } = string.Empty;
[Required]
public DateTime DateOpen { get; set; }
[Required]
public int WoodMaxCount { get; set; }
[ForeignKey("ShopId")]
public List<ShopWood> Woods { get; set; } = new();
private Dictionary<int, (IWoodModel, int)>? _shopWoods = null;
[NotMapped]
public Dictionary<int, (IWoodModel, int)> ShopWoods
{
get
{
if (_shopWoods == null)
{
_shopWoods = Woods
.ToDictionary(x => x.WoodId, x =>
(x.Wood as IWoodModel, x.Count));
}
return _shopWoods;
}
}
public static Shop? Create(CarpentryWorkshopDatabase context, ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
WoodMaxCount = model.WoodMaxCount,
Woods = model.ShopWoods.Select(x => new ShopWood
{
Wood = context.Woods.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
WoodMaxCount = model.WoodMaxCount;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
ShopWoods = ShopWoods,
WoodMaxCount = WoodMaxCount
};
public void UpdateWoods(CarpentryWorkshopDatabase context,
ShopBindingModel model)
{
var ShopWoods = context.ShopWoods.Where(rec => rec.ShopId == model.Id).ToList();
if (ShopWoods != null && ShopWoods.Count > 0)
{
context.ShopWoods.RemoveRange(ShopWoods.Where(rec => !model.ShopWoods.ContainsKey(rec.WoodId)));
context.SaveChanges();
ShopWoods = context.ShopWoods.Where(rec => rec.ShopId == model.Id).ToList();
foreach (var updateWood in ShopWoods)
{
updateWood.Count = model.ShopWoods[updateWood.WoodId].Item2;
model.ShopWoods.Remove(updateWood.WoodId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var ar in model.ShopWoods)
{
context.ShopWoods.Add(new ShopWood
{
Shop = shop,
Wood = context.Woods.First(x => x.Id == ar.Key),
Count = ar.Value.Item2
});
context.SaveChanges();
}
_shopWoods = null;
}
public void WoodsDictionatyUpdate(CarpentryWorkshopDatabase context)
{
UpdateWoods(context, new ShopBindingModel
{
Id = Id,
ShopWoods = ShopWoods,
});
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models
{
public class ShopWood
{
public int Id { get; set; }
[Required]
public int WoodId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Wood Wood { get; set; } = new();
}
}

View File

@ -31,6 +31,8 @@ namespace CarpentryWorkshopDatabaseImplement.Models
public virtual List<WoodComponent> Components { get; set; } = new();
[ForeignKey("WoodId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("WoodId")]
public virtual List<ShopWood> ShopWoods { get; set; } = new();
public static Wood Create(CarpentryWorkshopDatabase context, WoodBindingModel model)
{
return new Wood()

View File

@ -9,9 +9,11 @@ namespace CarpentryWorkshopFileImplement
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string WoodFileName = "Wood.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Wood> Woods { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -23,11 +25,13 @@ namespace CarpentryWorkshopFileImplement
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveWoods() => SaveData(Woods, WoodFileName, "Woods", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Woods = LoadData(WoodFileName, "Wood", x => Wood.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{

View File

@ -0,0 +1,154 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(x => x.GetViewModel).ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return source.Shops.Where(x => x.ShopName.Contains(model.ShopName)).Select(x => x.GetViewModel).ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop != null)
{
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
return null;
}
public bool Sale(SupplySearchModel model)
{
if (model == null || !model.WoodId.HasValue || !model.Count.HasValue)
return false;
int remainingSpace = source.Shops.Select(x => x.Woods.ContainsKey(model.WoodId.Value) ? x.Woods[model.WoodId.Value] : 0).Sum();
if (remainingSpace < model.Count)
{
return false;
}
var shops = source.Shops.Where(x => x.Woods.ContainsKey(model.WoodId.Value)).OrderByDescending(x => x.Woods[model.WoodId.Value]).ToList();
foreach (var shop in shops)
{
int residue = model.Count.Value - shop.Woods[model.WoodId.Value];
if (residue > 0)
{
shop.Woods.Remove(model.WoodId.Value);
shop.WoodsUpdate();
model.Count = residue;
}
else
{
if (residue == 0)
{
shop.Woods.Remove(model.WoodId.Value);
}
else
{
shop.Woods[model.WoodId.Value] = -residue;
}
shop.WoodsUpdate();
source.SaveShops();
return true;
}
}
source.SaveShops();
return false;
}
public bool RestockingShops(SupplyBindingModel model)
{
if (model == null || source.Shops.Select(x => x.WoodMaxCount - x.ShopWoods.Select(y => y.Value.Item2).Sum()).Sum() < model.Count)
{
return false;
}
foreach (Shop shop in source.Shops)
{
int free_places = shop.WoodMaxCount - shop.ShopWoods.Select(x => x.Value.Item2).Sum();
if (free_places <= 0)
continue;
free_places = Math.Min(free_places, model.Count);
model.Count -= free_places;
if (shop.Woods.ContainsKey(model.WoodId))
{
shop.Woods[model.WoodId] += free_places;
}
else
{
shop.Woods.Add(model.WoodId, free_places);
}
shop.WoodsUpdate();
if (model.Count == 0)
{
source.SaveShops();
return true;
}
}
return false;
}
}
}

View File

@ -0,0 +1,113 @@
using CarpentryWorkshopDataModels.Models;
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using CarpentryWorkshopFileImplement;
namespace CarpentryWorkshopFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; }
public string Address { get; private set; }
public DateTime DateOpen { get; private set; }
public Dictionary<int, int> Woods { get; private set; } = new();
public int WoodMaxCount { get; private set; }
private Dictionary<int, (IWoodModel, int)>? _shopWoods = null;
public Dictionary<int, (IWoodModel, int)> ShopWoods
{
get
{
if (_shopWoods == null)
{
var source = DataFileSingleton.GetInstance();
_shopWoods = Woods.ToDictionary(x => x.Key, y => ((source.Woods.FirstOrDefault(z => z.Id == y.Key) as IWoodModel)!, y.Value));
}
return _shopWoods;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
Woods = model.ShopWoods.ToDictionary(x => x.Key, x => x.Value.Item2),
WoodMaxCount = model.WoodMaxCount
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value),
Woods = element.Element("ShopWoods")!.Elements("ShopWood")!.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)),
WoodMaxCount = Convert.ToInt32(element.Element("WoodMaxCount")!.Value)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
WoodMaxCount = model.WoodMaxCount;
Woods = model.ShopWoods.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopWoods = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
ShopWoods = ShopWoods,
WoodMaxCount = WoodMaxCount
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpen", DateOpen.ToString()),
new XElement("ShopWoods", Woods.Select(
x => new XElement("ShopWood", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()),
new XElement("WoodMaxCount", WoodMaxCount.ToString())
);
public void WoodsUpdate()
{
_shopWoods = null;
}
}
}

View File

@ -8,11 +8,13 @@ namespace CarpentryWorkshopListImplement
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Wood> Woods { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Woods = new List<Wood>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,113 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using CarpentryWorkshopListImplement.Models;
namespace CarpentryWorkshopListImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel
model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.ShopName))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.ShopName.Contains(model.ShopName))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.ShopName) &&
shop.ShopName == model.ShopName) ||
(model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public bool Sale(SupplySearchModel model)
{
throw new NotImplementedException();
}
public bool RestockingShops(SupplyBindingModel model)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,55 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopListImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; }
public string Address { get; private set; }
public DateTime DateOpen { get; private set; }
public Dictionary<int, (IWoodModel, int)> ShopWoods { get; private set; } = new();
public int WoodMaxCount { get; private set; }
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
WoodMaxCount = model.WoodMaxCount,
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
ShopWoods = ShopWoods
};
}
}

View File

@ -32,6 +32,8 @@
справочникиToolStripMenuItem = new ToolStripMenuItem();
КомпонентыToolStripMenuItem = new ToolStripMenuItem();
ИзделияToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem1 = new ToolStripMenuItem();
отчетыToolStripMenuItem2 = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
списокИзделийToolStripMenuItem = new ToolStripMenuItem();
списокКомпонентовПоИзделиямToolStripMenuItem = new ToolStripMenuItem();
@ -42,14 +44,26 @@
ButtonOrderReady = new Button();
ButtonIssuedOrder = new Button();
ButtonRef = new Button();
отчетыToolStripMenuItem1 = new ToolStripMenuItem();
toolStripMenuItem1 = new ToolStripMenuItem();
отчетыToolStripMenuItem3 = new ToolStripMenuItem();
toolStripMenuItem3 = new ToolStripMenuItem();
toolStripMenuItem4 = new ToolStripMenuItem();
изделияToolStripMenuItem1 = new ToolStripMenuItem();
магазинToolStripMenuItem = new ToolStripMenuItem();
заказыToolStripMenuItem = new ToolStripMenuItem();
списокИзделийToolStripMenuItem1 = new ToolStripMenuItem();
изделияСКомпонентамиToolStripMenuItem = new ToolStripMenuItem();
информацияToolStripMenuItem = new ToolStripMenuItem();
загруженностьToolStripMenuItem = new ToolStripMenuItem();
заказыToolStripMenuItem1 = new ToolStripMenuItem();
заказыПоГруппамToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, toolStripMenuItem1, отчетыToolStripMenuItem3 });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(896, 24);
@ -58,7 +72,7 @@
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ИзделияToolStripMenuItem, отчетыToolStripMenuItem1 });
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ИзделияToolStripMenuItem, отчетыToolStripMenuItem1, отчетыToolStripMenuItem2 });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
@ -77,6 +91,18 @@
ИзделияToolStripMenuItem.Text = "Изделия";
ИзделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem1
//
отчетыToolStripMenuItem1.Name = "отчетыToolStripMenuItem1";
отчетыToolStripMenuItem1.Size = new Size(180, 22);
отчетыToolStripMenuItem1.Text = "Магазины";
отчетыToolStripMenuItem1.Click += магазиныToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem2
//
отчетыToolStripMenuItem2.Name = "отчетыToolStripMenuItem2";
отчетыToolStripMenuItem2.Size = new Size(180, 22);
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокИзделийToolStripMenuItem, списокКомпонентовПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem });
@ -166,11 +192,96 @@
ButtonRef.UseVisualStyleBackColor = true;
ButtonRef.Click += ButtonRef_Click;
//
// отчетыToolStripMenuItem1
// toolStripMenuItem1
//
отчетыToolStripMenuItem1.Name = "отчетыToolStripMenuItem1";
отчетыToolStripMenuItem1.Size = new Size(180, 22);
отчетыToolStripMenuItem1.Text = "Отчеты";
toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem3, toolStripMenuItem4 });
toolStripMenuItem1.Name = "toolStripMenuItem1";
toolStripMenuItem1.Size = new Size(75, 20);
toolStripMenuItem1.Text = "Операции";
//
// отчетыToolStripMenuItem3
//
отчетыToolStripMenuItem3.DropDownItems.AddRange(new ToolStripItem[] { изделияToolStripMenuItem1, магазинToolStripMenuItem, заказыToolStripMenuItem });
отчетыToolStripMenuItem3.Name = "отчетыToolStripMenuItem3";
отчетыToolStripMenuItem3.Size = new Size(60, 20);
отчетыToolStripMenuItem3.Text = "Отчеты";
//
// toolStripMenuItem3
//
toolStripMenuItem3.Name = "toolStripMenuItem3";
toolStripMenuItem3.Size = new Size(180, 22);
toolStripMenuItem3.Text = "Поставка";
toolStripMenuItem3.Click += поставкиToolStripMenuItem_Click;
//
// toolStripMenuItem4
//
toolStripMenuItem4.Name = "toolStripMenuItem4";
toolStripMenuItem4.Size = new Size(180, 22);
toolStripMenuItem4.Text = "Продажа";
toolStripMenuItem4.DropDownClosed += SellToolStripMenuItem_Click;
//
// изделияToolStripMenuItem1
//
изделияToolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { списокИзделийToolStripMenuItem1, изделияСКомпонентамиToolStripMenuItem });
изделияToolStripMenuItem1.Name = "изделияToolStripMenuItem1";
изделияToolStripMenuItem1.Size = new Size(180, 22);
изделияToolStripMenuItem1.Text = "Изделия";
//
// магазинToolStripMenuItem
//
магазинToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { информацияToolStripMenuItem, загруженностьToolStripMenuItem });
магазинToolStripMenuItem.Name = агазинToolStripMenuItem";
магазинToolStripMenuItem.Size = new Size(180, 22);
магазинToolStripMenuItem.Text = "Магазин";
//
// заказыToolStripMenuItem
//
заказыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { заказыToolStripMenuItem1, заказыПоГруппамToolStripMenuItem });
заказыToolStripMenuItem.Name = аказыToolStripMenuItem";
заказыToolStripMenuItem.Size = new Size(180, 22);
заказыToolStripMenuItem.Text = "Заказы";
//
// списокИзделийToolStripMenuItem1
//
списокИзделийToolStripMenuItem1.Name = "списокИзделийToolStripMenuItem1";
списокИзделийToolStripMenuItem1.Size = new Size(215, 22);
списокИзделийToolStripMenuItem1.Text = "Список изделий";
списокИзделийToolStripMenuItem1.Click += списокИзделийToolStripMenuItem_Click;
//
// изделияСКомпонентамиToolStripMenuItem
//
изделияСКомпонентамиToolStripMenuItem.Name = "изделияСКомпонентамиToolStripMenuItem";
изделияСКомпонентамиToolStripMenuItem.Size = new Size(215, 22);
изделияСКомпонентамиToolStripMenuItem.Text = "Изделия с компонентами";
изделияСКомпонентамиToolStripMenuItem.Click += изделияПоКомпонентамToolStripMenuItem_Click;
//
// информацияToolStripMenuItem
//
информацияToolStripMenuItem.Name = "информацияToolStripMenuItem";
информацияToolStripMenuItem.Size = new Size(180, 22);
информацияToolStripMenuItem.Text = "Информация";
информацияToolStripMenuItem.Click += InfoToolStripMenuItem_Click;
//
// загруженностьToolStripMenuItem
//
загруженностьToolStripMenuItem.Name = агруженностьToolStripMenuItem";
загруженностьToolStripMenuItem.Size = new Size(180, 22);
загруженностьToolStripMenuItem.Text = "Загруженность";
загруженностьToolStripMenuItem.Click += BusyShopsToolStripMenuItem_Click;
//
// заказыToolStripMenuItem1
//
заказыToolStripMenuItem1.Name = аказыToolStripMenuItem1";
заказыToolStripMenuItem1.Size = new Size(180, 22);
заказыToolStripMenuItem1.Text = "Заказы";
заказыToolStripMenuItem1.Click += списокЗаказовToolStripMenuItem_Click;
//
// заказыПоГруппамToolStripMenuItem
//
заказыПоГруппамToolStripMenuItem.Name = аказыПоГруппамToolStripMenuItem";
заказыПоГруппамToolStripMenuItem.Size = new Size(180, 22);
заказыПоГруппамToolStripMenuItem.Text = "Заказы по группам";
заказыПоГруппамToolStripMenuItem.Click += GroupOrdersToolStripMenuItem_Click;
//
// FormMain
//
@ -205,11 +316,29 @@
private System.Windows.Forms.Button ButtonIssuedOrder;
private System.Windows.Forms.Button ButtonRef;
private System.Windows.Forms.ToolStripMenuItem КомпонентыToolStripMenuItem;
private System.Windows.Forms.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 отчетыToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem ИзделияToolStripMenuItem;
private ToolStripMenuItem отчетыToolStripMenuItem2;
private ToolStripMenuItem toolStripMenuItem1;
private ToolStripMenuItem toolStripMenuItem3;
private ToolStripMenuItem toolStripMenuItem4;
private ToolStripMenuItem отчетыToolStripMenuItem3;
private ToolStripMenuItem изделияToolStripMenuItem1;
private ToolStripMenuItem списокИзделийToolStripMenuItem1;
private ToolStripMenuItem изделияСКомпонентамиToolStripMenuItem;
private ToolStripMenuItem магазинToolStripMenuItem;
private ToolStripMenuItem информацияToolStripMenuItem;
private ToolStripMenuItem загруженностьToolStripMenuItem;
private ToolStripMenuItem заказыToolStripMenuItem;
private ToolStripMenuItem заказыToolStripMenuItem1;
private ToolStripMenuItem заказыПоГруппамToolStripMenuItem;
}
}

View File

@ -2,6 +2,7 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using CarpentryWorkshopDataModels.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -12,6 +13,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarpentryWorkshopView
{
public partial class FormMain : Form
@ -147,6 +149,31 @@ namespace CarpentryWorkshopView
{
LoadData();
}
private void магазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
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 SellToolStripMenuItem_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" };
@ -174,5 +201,42 @@ namespace CarpentryWorkshopView
form.ShowDialog();
}
}
private void InfoToolStripMenuItem_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 BusyShopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShop));
if (service is FormReportShop form)
{
form.ShowDialog();
}
}
private void GroupOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders));
if (service is FormReportGroupedOrders form)
{
form.ShowDialog();
}
}
private void отчетыToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
private void отчетыToolStripMenuItem2_Click(object sender, EventArgs e)
{
}
}
}

View File

@ -0,0 +1,86 @@
namespace CarpentryWorkshopView
{
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 CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.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 CarpentryWorkshopView
{
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("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,115 @@
namespace CarpentryWorkshopView
{
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()
{
buttonSaveToExcel = new Button();
dataGridView = new DataGridView();
ColumnShop = new DataGridViewTextBoxColumn();
ColumnWood = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonSaveToExcel
//
buttonSaveToExcel.Location = new Point(0, 4);
buttonSaveToExcel.Margin = new Padding(3, 2, 3, 2);
buttonSaveToExcel.Name = "buttonSaveToExcel";
buttonSaveToExcel.Size = new Size(195, 22);
buttonSaveToExcel.TabIndex = 3;
buttonSaveToExcel.Text = "Сохранить в Excel";
buttonSaveToExcel.UseVisualStyleBackColor = true;
buttonSaveToExcel.Click += ButtonSaveToExcel_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToOrderColumns = true;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnShop, ColumnWood, ColumnCount });
dataGridView.Dock = DockStyle.Bottom;
dataGridView.Location = new Point(0, 36);
dataGridView.Margin = new Padding(3, 2, 3, 2);
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(523, 302);
dataGridView.TabIndex = 2;
//
// ColumnShop
//
ColumnShop.FillWeight = 130F;
ColumnShop.HeaderText = "Магазин";
ColumnShop.MinimumWidth = 6;
ColumnShop.Name = "ColumnShop";
ColumnShop.ReadOnly = true;
//
// ColumnWood
//
ColumnWood.FillWeight = 140F;
ColumnWood.HeaderText = "Изделие";
ColumnWood.MinimumWidth = 6;
ColumnWood.Name = "ColumnWood";
ColumnWood.ReadOnly = true;
//
// ColumnCount
//
ColumnCount.FillWeight = 90F;
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
//
// FormReportShop
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(523, 338);
Controls.Add(buttonSaveToExcel);
Controls.Add(dataGridView);
Margin = new Padding(3, 2, 3, 2);
Name = "FormReportShop";
Text = "Наполненость магазинов";
Load += FormReportShop_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonSaveToExcel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumnShop;
private DataGridViewTextBoxColumn ColumnWood;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,78 @@
using Microsoft.Extensions.Logging;
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.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 CarpentryWorkshopView
{
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.Woods)
{
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

@ -0,0 +1,124 @@
namespace CarpentryWorkshopView
{
partial class FormSell
{
/// <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()
{
labelWood = new Label();
comboBoxWood = new ComboBox();
labelCount = new Label();
textBoxCount = new TextBox();
buttonSell = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelWood
//
labelWood.AutoSize = true;
labelWood.Location = new Point(10, 10);
labelWood.Name = "labelWood";
labelWood.Size = new Size(59, 15);
labelWood.TabIndex = 0;
labelWood.Text = "Изделие: ";
//
// comboBoxWood
//
comboBoxWood.FormattingEnabled = true;
comboBoxWood.Location = new Point(101, 8);
comboBoxWood.Margin = new Padding(3, 2, 3, 2);
comboBoxWood.Name = "comboBoxWood";
comboBoxWood.Size = new Size(210, 23);
comboBoxWood.TabIndex = 1;
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(10, 41);
labelCount.Name = "labelCount";
labelCount.Size = new Size(78, 15);
labelCount.TabIndex = 2;
labelCount.Text = "Количество: ";
//
// textBoxCount
//
textBoxCount.Location = new Point(101, 39);
textBoxCount.Margin = new Padding(3, 2, 3, 2);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(210, 23);
textBoxCount.TabIndex = 3;
//
// buttonSell
//
buttonSell.Location = new Point(112, 74);
buttonSell.Margin = new Padding(3, 2, 3, 2);
buttonSell.Name = "buttonSell";
buttonSell.Size = new Size(82, 22);
buttonSell.TabIndex = 4;
buttonSell.Text = "Продать";
buttonSell.UseVisualStyleBackColor = true;
buttonSell.Click += ButtonSell_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(212, 74);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormSell
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(320, 105);
Controls.Add(buttonCancel);
Controls.Add(buttonSell);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Controls.Add(comboBoxWood);
Controls.Add(labelWood);
Margin = new Padding(3, 2, 3, 2);
Name = "FormSell";
Text = "Продажа изделий";
Load += FormSellingWood_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelWood;
private ComboBox comboBoxWood;
private Label labelCount;
private TextBox textBoxCount;
private Button buttonSell;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,88 @@
using Microsoft.Extensions.Logging;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
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 CarpentryWorkshopView
{
public partial class FormSell : Form
{
private readonly ILogger _logger;
private readonly IWoodLogic _logicP;
private readonly IShopLogic _logicS;
private List<WoodViewModel> _woodList = new List<WoodViewModel>();
public FormSell(ILogger<FormSell> logger, IWoodLogic logicP, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicS = logicS;
}
private void FormSellingWood_Load(object sender, EventArgs e)
{
_woodList = _logicP.ReadList(null);
if (_woodList != null)
{
comboBoxWood.DisplayMember = "WoodName";
comboBoxWood.ValueMember = "Id";
comboBoxWood.DataSource = _woodList;
comboBoxWood.SelectedItem = null;
_logger.LogInformation("Загрузка изделий для продажи");
}
}
private void ButtonSell_Click(object sender, EventArgs e)
{
if (comboBoxWood.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание покупки");
try
{
bool resout = _logicS.Sale(new SupplySearchModel
{
WoodId = Convert.ToInt32(comboBoxWood.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text)
});
if (resout)
{
_logger.LogInformation("Проверка пройдена, продажа проведена");
MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
else
{
_logger.LogInformation("Проверка не пройдена");
MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания покупки");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

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,213 @@
namespace CarpentryWorkshopView
{
partial class FormShop
{
/// <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()
{
DateTimePicker = new DateTimePicker();
NameTextBox = new TextBox();
AddressTextBox = new TextBox();
NameLabel = new Label();
AdressLabel = new Label();
DateLabel = new Label();
SaveButton = new Button();
CancelButton = new Button();
DataGridView = new DataGridView();
Column1 = new DataGridViewTextBoxColumn();
Название = new DataGridViewTextBoxColumn();
Цена = new DataGridViewTextBoxColumn();
Количество = new DataGridViewTextBoxColumn();
labelCapacity = new Label();
numericUpWoodMaxCount = new NumericUpDown();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpWoodMaxCount).BeginInit();
SuspendLayout();
//
// DateTimePicker
//
DateTimePicker.Location = new Point(98, 70);
DateTimePicker.Name = "DateTimePicker";
DateTimePicker.Size = new Size(305, 23);
DateTimePicker.TabIndex = 0;
//
// NameTextBox
//
NameTextBox.Location = new Point(98, 12);
NameTextBox.Name = "NameTextBox";
NameTextBox.Size = new Size(305, 23);
NameTextBox.TabIndex = 1;
//
// AddressTextBox
//
AddressTextBox.Location = new Point(98, 41);
AddressTextBox.Name = "AddressTextBox";
AddressTextBox.Size = new Size(305, 23);
AddressTextBox.TabIndex = 2;
//
// NameLabel
//
NameLabel.AutoSize = true;
NameLabel.Location = new Point(12, 15);
NameLabel.Name = "NameLabel";
NameLabel.Size = new Size(59, 15);
NameLabel.TabIndex = 3;
NameLabel.Text = "Название";
//
// AdressLabel
//
AdressLabel.AutoSize = true;
AdressLabel.Location = new Point(12, 44);
AdressLabel.Name = "AdressLabel";
AdressLabel.Size = new Size(40, 15);
AdressLabel.TabIndex = 4;
AdressLabel.Text = "Адрес";
//
// DateLabel
//
DateLabel.AutoSize = true;
DateLabel.Location = new Point(12, 76);
DateLabel.Name = "DateLabel";
DateLabel.Size = new Size(32, 15);
DateLabel.TabIndex = 5;
DateLabel.Text = "Дата";
//
// SaveButton
//
SaveButton.Location = new Point(248, 320);
SaveButton.Name = "SaveButton";
SaveButton.Size = new Size(75, 23);
SaveButton.TabIndex = 6;
SaveButton.Text = "Сохранить";
SaveButton.UseVisualStyleBackColor = true;
SaveButton.Click += SaveButton_Click;
//
// CancelButton
//
CancelButton.Location = new Point(329, 320);
CancelButton.Name = "CancelButton";
CancelButton.Size = new Size(75, 23);
CancelButton.TabIndex = 7;
CancelButton.Text = "Отмена";
CancelButton.UseVisualStyleBackColor = true;
CancelButton.Click += CancelButton_Click;
//
// DataGridView
//
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Columns.AddRange(new DataGridViewColumn[] { Column1, Название, Цена, Количество });
DataGridView.Location = new Point(12, 139);
DataGridView.Name = "DataGridView";
DataGridView.Size = new Size(391, 175);
DataGridView.TabIndex = 8;
//
// Column1
//
Column1.HeaderText = "Column1";
Column1.Name = "Column1";
Column1.Visible = false;
//
// Название
//
Название.HeaderText = "Название";
Название.Name = "Название";
Название.ReadOnly = true;
Название.Width = 150;
//
// Цена
//
Цена.HeaderText = "Цена";
Цена.Name = "Цена";
Цена.ReadOnly = true;
//
// Количество
//
Количество.HeaderText = "Количество";
Количество.Name = "Количество";
Количество.ReadOnly = true;
//
// labelCapacity
//
labelCapacity.AutoSize = true;
labelCapacity.Location = new Point(12, 103);
labelCapacity.Name = "labelCapacity";
labelCapacity.Size = new Size(80, 15);
labelCapacity.TabIndex = 9;
labelCapacity.Text = "Вместимость";
//
// numericUpWoodMaxCount
//
numericUpWoodMaxCount.Location = new Point(98, 101);
numericUpWoodMaxCount.Margin = new Padding(3, 2, 3, 2);
numericUpWoodMaxCount.Maximum = new decimal(new int[] { 10000, 0, 0, 0 });
numericUpWoodMaxCount.Name = "numericUpWoodMaxCount";
numericUpWoodMaxCount.Size = new Size(305, 23);
numericUpWoodMaxCount.TabIndex = 12;
//
// FormShop
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(411, 355);
Controls.Add(numericUpWoodMaxCount);
Controls.Add(labelCapacity);
Controls.Add(DataGridView);
Controls.Add(CancelButton);
Controls.Add(SaveButton);
Controls.Add(DateLabel);
Controls.Add(AdressLabel);
Controls.Add(NameLabel);
Controls.Add(AddressTextBox);
Controls.Add(NameTextBox);
Controls.Add(DateTimePicker);
Name = "FormShop";
Text = "Редактор магазина";
Load += ShopForm_Load;
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpWoodMaxCount).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker DateTimePicker;
private TextBox NameTextBox;
private TextBox AddressTextBox;
private Label NameLabel;
private Label AdressLabel;
private Label DateLabel;
private Button SaveButton;
private Button CancelButton;
private DataGridView DataGridView;
private DataGridViewTextBoxColumn Column1;
private DataGridViewTextBoxColumn Название;
private DataGridViewTextBoxColumn Цена;
private DataGridViewTextBoxColumn Количество;
private Label labelCapacity;
private NumericUpDown numericUpWoodMaxCount;
}
}

View File

@ -0,0 +1,120 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace CarpentryWorkshopView
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public int? _id;
public int Id { set { _id = value; } }
private Dictionary<int, (IWoodModel, int)> _woods;
private DateTime? _dateopen = null;
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_woods = new Dictionary<int, (IWoodModel, int)>();
}
private void ShopForm_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var shop = _logic.ReadElement(new ShopSearchModel { Id = _id });
if (shop != null)
{
NameTextBox.Text = shop.ShopName;
AddressTextBox.Text = shop.Address;
DateTimePicker.Text = shop.DateOpen.ToString();
numericUpWoodMaxCount.Value = shop.WoodMaxCount;
_woods = shop.ShopWoods ?? new Dictionary<int, (IWoodModel, int)>();
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка товаров магазина");
try
{
if (_woods != null)
{
foreach (var wood in _woods)
{
DataGridView.Rows.Add(new object[] { wood.Key, wood.Value.Item1.WoodName, wood.Value.Item1.Price, wood.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(NameTextBox.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(AddressTextBox.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = NameTextBox.Text,
Address = AddressTextBox.Text,
DateOpen = DateTimePicker.Value.Date,
WoodMaxCount = (int)numericUpWoodMaxCount.Value,
ShopWoods = _woods
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
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,117 @@
namespace CarpentryWorkshopView
{
partial class FormShops
{
/// <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()
{
DataGridView = new DataGridView();
AddButton = new Button();
UpdateButton = new Button();
RefreshButton = new Button();
DeleteButton = new Button();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
//
// DataGridView
//
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Location = new Point(12, 12);
DataGridView.Name = "DataGridView";
DataGridView.Size = new Size(393, 374);
DataGridView.TabIndex = 0;
//
// AddButton
//
AddButton.Location = new Point(411, 12);
AddButton.Name = "AddButton";
AddButton.Size = new Size(114, 23);
AddButton.TabIndex = 1;
AddButton.Text = "Добавить";
AddButton.UseVisualStyleBackColor = true;
AddButton.Click += AddButton_Click;
//
// UpdateButton
//
UpdateButton.Location = new Point(411, 41);
UpdateButton.Name = "UpdateButton";
UpdateButton.Size = new Size(114, 23);
UpdateButton.TabIndex = 2;
UpdateButton.Text = "Изменить";
UpdateButton.UseVisualStyleBackColor = true;
UpdateButton.Click += UpdateButton_Click;
//
// RefreshButton
//
RefreshButton.Location = new Point(411, 70);
RefreshButton.Name = "RefreshButton";
RefreshButton.Size = new Size(114, 23);
RefreshButton.TabIndex = 3;
RefreshButton.Text = "Обновить";
RefreshButton.UseVisualStyleBackColor = true;
RefreshButton.Click += RefreshButton_Click;
//
// DeleteButton
//
DeleteButton.Location = new Point(411, 99);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(114, 23);
DeleteButton.TabIndex = 4;
DeleteButton.Text = "Удалить";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += DeleteButton_Click;
//
// FormShops
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(539, 403);
Controls.Add(DeleteButton);
Controls.Add(RefreshButton);
Controls.Add(UpdateButton);
Controls.Add(AddButton);
Controls.Add(DataGridView);
Name = "FormShops";
Text = "Магазины";
Load += ShopsForm_Load;
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView DataGridView;
private Button AddButton;
private Button UpdateButton;
private Button RefreshButton;
private Button DeleteButton;
private DataGridViewTextBoxColumn Column1;
private DataGridViewTextBoxColumn Column2;
private DataGridViewTextBoxColumn Column3;
private DataGridViewTextBoxColumn Column4;
private DataGridViewTextBoxColumn Column5;
}
}

View File

@ -0,0 +1,107 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace CarpentryWorkshopView
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShops> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["Address"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
DataGridView.Columns["ShopWoods"].Visible = false;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ShopsForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void AddButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
var tmp = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
form._id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление магазина");
try
{
if (!_logic.Delete(new ShopBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
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,107 @@
namespace CarpentryWorkshopView
{
partial class FormSupply
{
/// <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()
{
ShopComboBox = new ComboBox();
WoodComboBox = new ComboBox();
CountTextBox = new TextBox();
SaveButton = new Button();
CancelButton = new Button();
SuspendLayout();
//
// ShopComboBox
//
ShopComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
ShopComboBox.FormattingEnabled = true;
ShopComboBox.Location = new Point(12, 12);
ShopComboBox.Name = "ShopComboBox";
ShopComboBox.Size = new Size(331, 23);
ShopComboBox.TabIndex = 0;
//
// WoodComboBox
//
WoodComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
WoodComboBox.FormattingEnabled = true;
WoodComboBox.Location = new Point(12, 41);
WoodComboBox.Name = "WoodComboBox";
WoodComboBox.Size = new Size(331, 23);
WoodComboBox.TabIndex = 1;
//
// CountTextBox
//
CountTextBox.Location = new Point(12, 70);
CountTextBox.Name = "CountTextBox";
CountTextBox.Size = new Size(331, 23);
CountTextBox.TabIndex = 2;
//
// SaveButton
//
SaveButton.Location = new Point(187, 99);
SaveButton.Name = "SaveButton";
SaveButton.Size = new Size(75, 23);
SaveButton.TabIndex = 3;
SaveButton.Text = "Сохранить";
SaveButton.UseVisualStyleBackColor = true;
SaveButton.Click += SaveButton_Click;
//
// CancelButton
//
CancelButton.Location = new Point(268, 99);
CancelButton.Name = "CancelButton";
CancelButton.Size = new Size(75, 23);
CancelButton.TabIndex = 4;
CancelButton.Text = "Отмена";
CancelButton.UseVisualStyleBackColor = true;
CancelButton.Click += CancelButton_Click;
//
// FormSupply
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(355, 136);
Controls.Add(CancelButton);
Controls.Add(SaveButton);
Controls.Add(CountTextBox);
Controls.Add(WoodComboBox);
Controls.Add(ShopComboBox);
Name = "FormSupply";
Text = "Поставки";
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox ShopComboBox;
private ComboBox WoodComboBox;
private TextBox CountTextBox;
private Button SaveButton;
private Button CancelButton;
}
}

View File

@ -0,0 +1,153 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
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 CarpentryWorkshopView
{
public partial class FormSupply : Form
{
private readonly List<WoodViewModel>? _woodList;
private readonly List<ShopViewModel>? _shopsList;
IShopLogic _shopLogic;
IWoodLogic _woodLogic;
public int ShopId
{
get
{
return
Convert.ToInt32(ShopComboBox.SelectedValue);
}
set
{
ShopComboBox.SelectedValue = value;
}
}
public int WoodId
{
get
{
return
Convert.ToInt32(WoodComboBox.SelectedValue);
}
set
{
WoodComboBox.SelectedValue = value;
}
}
public IWoodModel? WoodModel
{
get
{
if (_woodList == null)
{
return null;
}
foreach (var elem in _woodList)
{
if (elem.Id == WoodId)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(CountTextBox.Text); }
set
{ CountTextBox.Text = value.ToString(); }
}
public FormSupply(IWoodLogic woodLogic, IShopLogic shopLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_woodLogic = woodLogic;
_woodList = woodLogic.ReadList(null);
_shopsList = shopLogic.ReadList(null);
if (_woodList != null)
{
WoodComboBox.DisplayMember = "WoodName";
WoodComboBox.ValueMember = "Id";
WoodComboBox.DataSource = _woodList;
WoodComboBox.SelectedItem = null;
}
if (_shopsList != null)
{
ShopComboBox.DisplayMember = "ShopName";
ShopComboBox.ValueMember = "Id";
ShopComboBox.DataSource = _shopsList;
ShopComboBox.SelectedItem = null;
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(CountTextBox.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (WoodComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (ShopComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int count = Convert.ToInt32(CountTextBox.Text);
bool res = _shopLogic.MakeSupply(new SupplyBindingModel
{
ShopId = Convert.ToInt32(ShopComboBox.SelectedValue),
WoodId = Convert.ToInt32(WoodComboBox.SelectedValue),
Count = Convert.ToInt32(CountTextBox.Text)
});
if (!res)
{
throw new Exception("Ошибка при пополнении. Дополнительная информация в логах");
}
MessageBox.Show("Пополнение прошло успешно");
DialogResult = DialogResult.OK;
Close();
}
catch (Exception err)
{
MessageBox.Show("Ошибка пополнения");
return;
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

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

@ -7,6 +7,7 @@ using CarpentryWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using CarpentryWorkshopView;
namespace CarpentryWorkshopView
{
@ -38,10 +39,13 @@ namespace CarpentryWorkshopView
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IWoodStorage, WoodStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IWoodLogic, WoodLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
@ -55,8 +59,14 @@ namespace CarpentryWorkshopView
services.AddTransient<FormWood>();
services.AddTransient<FormWoodComponent>();
services.AddTransient<FormWoods>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSell>();
services.AddTransient<FormReportWoodComponents>();
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>