Compare commits

..

143 Commits

Author SHA1 Message Date
0ff4abc04a Сданная LabWork05_Hard. 2023-04-25 12:59:54 +04:00
cba839f32a Ура, вроде как всё работает. 2023-04-21 11:57:59 +04:00
4489c8bddb Добавление контроллера в RestAPI. 2023-04-21 10:04:53 +04:00
d3cffdaa59 Начало 5-й усложнённой лабораторной. 2023-04-21 01:42:19 +04:00
fdfc94016f Устранение конфликта. 2023-04-20 00:13:18 +04:00
2471698c93 Мелкая правка. 2023-04-20 00:06:21 +04:00
aec2aa1e20 Проверка. 2023-04-19 23:37:16 +04:00
e71b781749 Ээээ, оно работает? 2023-04-19 23:25:23 +04:00
a2cb71b297 Начало дозагрузки 4-й базовой. 2023-04-19 22:54:29 +04:00
8b3574fae7 Мелкая правка. 2023-04-19 22:39:46 +04:00
0e9b3b140e Мелкие правки. 2023-04-11 13:03:56 +04:00
7060c3da24 Настройка зависимостей и путей. 2023-04-11 00:33:59 +04:00
506ec5202d Вроде всё добавил. 2023-04-11 00:20:54 +04:00
7bd2afd486 Добавление необходимых форм и отчётов. 2023-04-10 23:43:15 +04:00
064bbb7a1e Доделанный BusinessLogic. 2023-04-10 22:39:00 +04:00
69ae32c8af Работа с OfficePackage. 2023-04-10 22:19:29 +04:00
4aade8f845 Начало работ. 2023-04-10 22:04:39 +04:00
90b9cbbcc1 Устранение конфликта. 2023-04-04 13:17:30 +04:00
11f0a8bd42 Устранение конфликта. 2023-04-04 13:12:14 +04:00
b757f6ad12 Мелкая правка. 2023-03-28 12:37:12 +04:00
f479c3070a Мелкая правка. 2023-03-28 12:36:20 +04:00
ba69cb0660 Вроде рабочая 5-я лаба. 2023-03-27 22:19:54 +04:00
bf3837d300 Мелкие правки. Не выводится список заказов на сайте. 2023-03-27 12:56:32 +04:00
1676bfd40a Мелкие правки. 2023-03-27 12:33:55 +04:00
c213555ba1 Revert "Revert "Промежуточное сохранение мелких исправлений. Но они капец выжные""
This reverts commit 63ea657569.
2023-03-27 11:56:52 +04:00
63ea657569 Revert "Промежуточное сохранение мелких исправлений. Но они капец выжные"
This reverts commit 6f178a6f1c.
2023-03-27 11:55:41 +04:00
6f178a6f1c Промежуточное сохранение мелких исправлений. Но они капец выжные 2023-03-27 11:55:17 +04:00
df8dbdd4fc Работа с формами. 2023-03-27 11:00:05 +04:00
445525cf8e Вроде успешная миграция. 2023-03-27 10:37:11 +04:00
1ca9dcf5c6 Исправление финального OrderStorage (надеюсь, что там всё нормально теперь везде). 2023-03-27 10:32:06 +04:00
47c32113a7 Настройка OrderStorage для работы с учётом появления клиента в БД. 2023-03-27 10:28:20 +04:00
fadef43698 FileImplements. 2023-03-27 09:26:06 +04:00
a093ca253d Промежуточное сохранение. 2023-03-25 20:49:06 +04:00
e0838cceec Реализация ClientLogic. 2023-03-25 20:16:36 +04:00
e7a7ba5411 LabWork05 по видео. 2023-03-25 18:03:20 +04:00
78d451f828 Создание видов в клиентском приложении. 2023-03-25 17:48:47 +04:00
c5db6541c6 Разработка клиентского приложения. 2023-03-25 17:28:18 +04:00
8042d78396 Добавление клиентского приложения. 2023-03-25 16:57:08 +04:00
d5394c869f Добавление проекта RestApi. 2023-03-25 16:13:08 +04:00
e070505e85 Добавление контрактов. Добавление бизнес логики, формы для работы с клиентами. 2023-03-25 15:51:54 +04:00
848946f26b LabWork05. Start work. 2023-03-25 13:47:57 +04:00
4a0a69ecc2 Hard LabWork №3. 2023-03-24 22:15:17 +04:00
f0720038c9 Заработало. 2023-03-24 19:36:31 +04:00
6870753d1a Попытка исправить ошибку миграции. 2023-03-24 10:52:44 +04:00
a2760750d5 Мелкий рефакторинг. 2023-03-24 00:37:43 +04:00
e89900b24c Промежуточное сохранение. 2023-03-24 00:31:38 +04:00
883c050eb9 Глобальное промежуточное сохранение. А то что-то я подустал))(((( 2023-03-24 00:15:37 +04:00
d5a8e38d9e Очередное важное несохранившееся изменение. 2023-03-23 23:59:44 +04:00
6b5b1ec34d Незагруженное исправление. 2023-03-23 23:46:10 +04:00
d572253caf Промежуточное сохранение. 2023-03-23 23:44:29 +04:00
990129b09f Мелкая правка. 2023-03-23 23:31:24 +04:00
867b5507db Мелкая правка. 2023-03-23 23:30:35 +04:00
9851d284ca Промежуточное сохранение. 2023-03-23 23:29:34 +04:00
cc59bf5dd5 Получается рефакторинг. 2023-03-23 22:25:19 +04:00
3c803705c3 Merge branch 'LabWork03' into LabWork03_Hard 2023-03-23 22:13:02 +04:00
119050cef3 Добавлена проверка на переполнение магазина изделиями. 2023-03-23 22:00:37 +04:00
bf266b777d Вроде почти всё. 2023-03-23 16:48:20 +04:00
e1b22db805 Добавление формы продажи изделий. 2023-03-23 16:36:11 +04:00
d1dc6f93d8 Добавление новой кнопки на FormMain. 2023-03-23 16:26:01 +04:00
d377511cba Промежуточное сохранение. 2023-03-23 11:23:25 +04:00
a0d1981bee Промежуточное сохранение. 2023-03-23 11:05:00 +04:00
1e56812c08 Промежуточне сохранение. 2023-03-23 10:28:44 +04:00
3c1388cbaf Начало работ. 2023-03-23 10:26:18 +04:00
7082a6593e Merge branch 'LabWork02' into LabWork02_Hard 2023-03-23 10:15:17 +04:00
e1eada8462 Косметическая правка сохранения отчёта) 2023-03-19 13:53:09 +04:00
3113ba8d31 ОНО РАБОТАЕТ, ЫЫЫЫЫ 2023-03-19 13:38:33 +04:00
7b682adb00 Уже почти всё работает. Но этот отчёт на форме... 2023-03-19 13:22:53 +04:00
400b9350cd Очень надеюсь, что финиш. 2023-03-19 13:12:17 +04:00
e2034af97d Промежуточное сохранение. 2023-03-19 12:53:48 +04:00
d38144af20 Промежуточное сохранение. 2023-03-18 22:15:22 +04:00
6e1cae3752 Снова промежуточное)))0) 2023-03-18 19:03:00 +04:00
b9245a0a62 Очередное промежуточное сохранение. 2023-03-18 19:02:14 +04:00
0cb3b31194 Промежуточное сохранение. 2023-03-18 19:00:47 +04:00
6938c31141 Промежуточное сохранение. 2023-03-18 18:50:46 +04:00
636a9b51a9 Промежуточное сохранение. ИБО УРА, ОТЧЁТ НАКОНЕЦ-ТО ПЕРЕСТАЛ ВЫКИДЫВАТЬ ОШИБКУ О КОНФЛИКТЕ МЕТОДОВ. 2023-03-18 18:09:04 +04:00
f8f008d5dc Удаление лишнего Numget пакета. 2023-03-18 17:11:32 +04:00
50f51100c6 Промежуточное сохранение. 2023-03-17 18:13:34 +04:00
ac75bb0d24 Промежуточное сохранение. 2023-03-17 16:47:18 +04:00
17eeef9ade Промежуточное сохранение. Добавление колонки "Статус" в отчёт. 2023-03-17 16:45:10 +04:00
d09961c4f2 Редактирование главной формы. 2023-03-17 15:43:10 +04:00
556b83d46d Промежуточное сохранение. 2023-03-17 15:30:49 +04:00
e3664a7331 Создание формы с отчётом. 2023-03-17 15:27:24 +04:00
e275d69888 Исправление отчёта. 2023-03-17 15:07:35 +04:00
72cb7704d7 Добавление отчёта и первой формы. 2023-03-16 18:46:14 +04:00
1a6b8e8e9e Добавление новых зависимостей. 2023-03-16 16:43:32 +04:00
fb97f13daa Реализация бизнес логики отчётов. 2023-03-16 16:40:30 +04:00
318a28094b Реализация абстрактных классов сохранения документов. 2023-03-16 14:59:46 +04:00
61b9a5058c Создание классов в папке OfficePackage. 2023-03-15 20:32:26 +04:00
25fc708859 Создание вспомогательных классов для оформления отчётов. 2023-03-15 19:58:55 +04:00
65278a764a Класс с бизнес логикой для отчётов. 2023-03-15 19:16:10 +04:00
15fb786e03 Добавили новые классы в Contracts. 2023-03-15 19:10:00 +04:00
7b5e16988b Мелкие правки. 2023-03-14 11:16:52 +04:00
b25a248c54 Мелкая правка (почему-то не отправилось сразу). 2023-03-14 11:09:37 +04:00
user
4e6da8e751 Первая усложнённая лабораторная. 2023-02-28 13:48:16 +04:00
7fb40e2c88 Промежуточное сохранение. 2023-02-28 10:35:11 +04:00
807966a19d Старт работ. 2023-02-28 09:55:56 +04:00
4ec9fa5f30 Исправленная миграция. 2023-02-28 08:36:02 +04:00
27384ba263 Исправление миграци. 2023-02-28 00:32:59 +04:00
0f46fbef9f Мелкие правки. 2023-02-28 00:13:54 +04:00
24d020220c Мелкий (НО ОЧЕНЬ ВНЕЗАПНЫЙ) фикс! 2023-02-27 23:59:19 +04:00
65f5de9943 Правки хранилищ. 2023-02-27 23:51:07 +04:00
0ce85a004c Начало реализации хранилищ. 2023-02-27 23:18:18 +04:00
6f31bcd0a0 Создание миграции. 2023-02-27 21:26:22 +04:00
fe555f44a9 Начало 3-й лабораторной. 2023-02-27 19:38:57 +04:00
82eeceb0ef Исправление конфликта. 2023-02-24 12:46:13 +04:00
edcc92c681 Исправление конфликта. 2023-02-24 12:38:23 +04:00
f83986aa7b Мелкие правки. 2023-02-24 12:27:33 +04:00
d11fc9960b Исправления алгоритма обновления статуса заказа. 2023-02-24 11:58:18 +04:00
b187f20196 Исправления алгоритма обновления статуса заказа. 2023-02-24 11:49:17 +04:00
e41554b69c Правки для корректной работы. 2023-02-14 12:53:11 +04:00
1c7e4211d1 Правка файла Program. 2023-02-14 10:04:54 +04:00
3b17272252 Мелкая правка. 2023-02-14 09:50:35 +04:00
660ea2894f Создание класса хранилища заказов. 2023-02-14 09:48:56 +04:00
c0fa37bd4b Реализация хранилища заготовок. 2023-02-14 00:34:36 +04:00
a60b8e7edc Создание DataFile для FileImplement. 2023-02-14 00:22:30 +04:00
74c4cb4d9d Мелкие правки. 2023-02-14 00:17:04 +04:00
38d9a88d6b Создание модели Order. 2023-02-14 00:15:13 +04:00
2f4c7b4db4 Первые два класса моделей. 2023-02-13 23:46:35 +04:00
3cd62dec9e Вроде финальные правки. 2023-02-13 23:06:34 +04:00
52e276b9bd Мелкие правки. 2023-02-13 21:53:02 +04:00
09ca448bb0 Мелкий фикс. 2023-02-12 23:06:37 +04:00
2dde084ba1 Удаление всех столбцов во всех DataGrid. 2023-02-12 22:59:29 +04:00
51d367dbc3 Сохранение возможно рабочей версии. 2023-02-12 22:48:22 +04:00
e5a9b72a76 Завершение проверки корректности кода. 2023-02-12 22:37:47 +04:00
5d37351d22 Сохранение перед проверкой корректности форм. 2023-02-12 21:59:33 +04:00
d0b97a0dc9 Глобальное промежуточное сохранение. 2023-02-12 17:05:47 +04:00
b93d5ff13f Реализация интерейсов хранилищ. 2023-02-11 00:07:41 +04:00
cdcdfa9709 Реализация интерфейсов моделей. 2023-02-10 14:25:11 +04:00
3b4adf6001 Изменения названий в проекте BusinessLogic. 2023-02-10 12:49:10 +04:00
fa5a6c35b7 Изменение названий в проекте Contracts. 2023-02-10 12:29:17 +04:00
950263a842 Изменение названий в проекте DataModels. 2023-02-10 12:19:17 +04:00
9a246b7311 Финальный класс с бизнес-логикой. 2023-02-09 23:32:49 +04:00
9c8d9a0f2a Промежуточное сохранение. 2023-02-06 19:57:06 +04:00
97bb4fafac Мелкое исправление. 2023-02-06 16:58:28 +04:00
ca54e7c5bc Начало реализации бизнес-логики. 2023-02-06 16:56:33 +04:00
f49c753a8d Создание интерфейсов для хранилища. 2023-02-05 22:14:40 +04:00
507df27f8f Реализация бизнес-логики. 2023-02-05 22:00:23 +04:00
af39ace4b7 Создание классов ViewModel. 2023-02-05 21:39:51 +04:00
89c8a663d1 Создание моделей для поиска. 2023-02-05 21:19:48 +04:00
590a9901ce Реализация сущностей. 2023-02-05 21:10:11 +04:00
bbc58f7482 Настройка папок проекта. 2023-02-05 21:00:26 +04:00
82f11ec29b Правильное добавление первой библиотеки классов. 2023-02-05 17:44:46 +04:00
67538380e3 Создание первой библиотеки. 2023-02-04 21:31:11 +04:00
340 changed files with 165654 additions and 53 deletions

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="6.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopBusinessLogic\BlacksmithWorkshopBusinessLogic.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,73 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace BlacksmithWorkshopRestApi.Controllers
{
//указание у контроллера, что Route будет строиться не только по наванию контроллера, но и по названию метода (так как у нас два Post-метода)
[Route("api/[controller]/[action]")]
[ApiController]
public class ClientController : Controller
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger)
{
_logger = logger;
_logic = logic;
}
[HttpGet]
public ClientViewModel? Login(string login, string password)
{
try
{
//попытка найти запись по переданным логину и паролю
return _logic.ReadElement(new ClientSearchModel
{
Email = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка входа в систему");
throw;
}
}
[HttpPost]
public void Register(ClientBindingModel model)
{
try
{
//создание клиента
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
[HttpPost]
public void UpdateData(ClientBindingModel model)
{
try
{
//изменение клиента
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных");
throw;
}
}
}
}

View File

@ -0,0 +1,94 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Mvc;
namespace BlacksmithWorkshopRestApi.Controllers
{
/// <summary>
/// в этом контроллере логика по заказам и изделиям
/// </summary>
//настройка у контроллера, так как снова используем несколько Post и Get запросов
[Route("api/[controller]/[action]")]
[ApiController]
public class MainController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly IManufactureLogic _manufacture;
public MainController(ILogger<MainController> logger, IOrderLogic order, IManufactureLogic manufacture)
{
_logger = logger;
_order = order;
_manufacture = manufacture;
}
[HttpGet]
public List<ManufactureViewModel>? GetManufactureList()
{
try
{
return _manufacture.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка изделий");
throw;
}
}
[HttpGet]
public ManufactureViewModel? GetManufacture(int manufactureId)
{
try
{
return _manufacture.ReadElement(new ManufactureSearchModel
{
Id = manufactureId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения изделия по id={Id}", manufactureId);
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetOrders(int clientId)
{
try
{
return _order.ReadList(new OrderSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка заказов клиента id ={ Id}", clientId);
throw;
}
}
[HttpPost]
public void CreateOrder(OrderBindingModel model)
{
try
{
_order.CreateOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
}
}

View File

@ -0,0 +1,110 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace BlacksmithWorkshopRestApi.Controllers
{
//настройка у контроллера, так как снова используем несколько Post и Get запросов
[Route("api/[controller]/[action]")]
[ApiController]
public class ShopController : Controller
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public ShopController(IShopLogic logic, ILogger<ShopController> logger)
{
_logger = logger;
_logic = logic;
}
[HttpGet]
public List<ShopViewModel>? GetShopList()
{
try
{
return _logic.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка магазинов");
throw;
}
}
[HttpGet]
public ShopViewModel? GetShop(int shopId)
{
try
{
return _logic.ReadElement(new ShopSearchModel { Id = shopId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения магазина по id={Id}", shopId);
throw;
}
}
[HttpPost]
public void CreateShop(ShopBindingModel model)
{
try
{
//создание магазина
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания магазина");
throw;
}
}
[HttpPost]
public void UpdateShop(ShopBindingModel model)
{
try
{
//изменение магазина
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных магазина");
throw;
}
}
[HttpPost]
public void DeleteShop(ShopBindingModel model)
{
try
{
_logic.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
throw;
}
}
[HttpPost]
public void AddManufacture(Tuple<ShopSearchModel, ManufactureBindingModel, int> model)
{
try
{
_logic.AddManufacture(model.Item1, model.Item2, model.Item3);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка добавления изделия в магазин");
throw;
}
}
}
}

View File

@ -0,0 +1,52 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopDatabaseImplement.Implements;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddLog4Net("log4net.config");
// Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IManufactureStorage, ManufactureStorage>();
builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IManufactureLogic, ManufactureLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//äëÿ ðàáîòû app.UseSwaggerUI
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "BlacksmithWorkshopRestApi", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
//âñòðîåííûé ñâàããåð äëÿ ïðîâåðêè
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BlacksmithWorkshopRestApi v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:22588",
"sslPort": 44369
}
},
"profiles": {
"BlackmithWorkshopRestApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7272;http://localhost:5169",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="c:/temp/BlacksmithWorkshopResrApi.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="TRACE" />
<appender-ref ref="RollingFile" />
</root>
</log4net>

View File

@ -3,7 +3,25 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33103.184
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshop", "BlacksmithWorkshop\BlacksmithWorkshop.csproj", "{FEF2DC94-D11E-4D77-9F59-5B89A09D0996}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshop", "BlacksmithWorkshop\BlacksmithWorkshop.csproj", "{FEF2DC94-D11E-4D77-9F59-5B89A09D0996}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopDataModels", "BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj", "{842406BF-3B58-4F5C-A4EB-AAB84F66ABEC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopContracts", "BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj", "{EBDA1A18-346F-4427-BC86-ED41C062A75B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopBusinessLogic", "BlacksmithWorkshopBusinessLogic\BlacksmithWorkshopBusinessLogic.csproj", "{B3C97222-2894-4D74-B0D7-B3BEB347081D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopListImplement", "BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj", "{2942D468-0C3B-4B8D-A15F-184F5D7C969A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopFileImplement", "BlacksmithWorkshopFileImplement\BlacksmithWorkshopFileImplement.csproj", "{58737D93-9A12-4D07-BF3F-86AC512CE626}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopDatabaseImplement", "BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj", "{EE03BAE3-52EE-4E3B-8992-382D89E61E1A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopRestApi", "BlackmithWorkshopRestApi\BlacksmithWorkshopRestApi.csproj", "{23DBD9A3-2107-44AB-8B87-6982BFD2E69A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopClientApp", "BlacksmithWorkshopClientApp\BlacksmithWorkshopClientApp.csproj", "{FCA95914-11AF-494A-8116-BB7B3253D925}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopShopApp", "BlacksmithWorkshopShopApp\BlacksmithWorkshopShopApp.csproj", "{3ADC69D9-EACA-4D59-840E-EB4A7F40BAEE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +33,42 @@ Global
{FEF2DC94-D11E-4D77-9F59-5B89A09D0996}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FEF2DC94-D11E-4D77-9F59-5B89A09D0996}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FEF2DC94-D11E-4D77-9F59-5B89A09D0996}.Release|Any CPU.Build.0 = Release|Any CPU
{842406BF-3B58-4F5C-A4EB-AAB84F66ABEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{842406BF-3B58-4F5C-A4EB-AAB84F66ABEC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{842406BF-3B58-4F5C-A4EB-AAB84F66ABEC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{842406BF-3B58-4F5C-A4EB-AAB84F66ABEC}.Release|Any CPU.Build.0 = Release|Any CPU
{EBDA1A18-346F-4427-BC86-ED41C062A75B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EBDA1A18-346F-4427-BC86-ED41C062A75B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EBDA1A18-346F-4427-BC86-ED41C062A75B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EBDA1A18-346F-4427-BC86-ED41C062A75B}.Release|Any CPU.Build.0 = Release|Any CPU
{B3C97222-2894-4D74-B0D7-B3BEB347081D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3C97222-2894-4D74-B0D7-B3BEB347081D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3C97222-2894-4D74-B0D7-B3BEB347081D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3C97222-2894-4D74-B0D7-B3BEB347081D}.Release|Any CPU.Build.0 = Release|Any CPU
{2942D468-0C3B-4B8D-A15F-184F5D7C969A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2942D468-0C3B-4B8D-A15F-184F5D7C969A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2942D468-0C3B-4B8D-A15F-184F5D7C969A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2942D468-0C3B-4B8D-A15F-184F5D7C969A}.Release|Any CPU.Build.0 = Release|Any CPU
{58737D93-9A12-4D07-BF3F-86AC512CE626}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{58737D93-9A12-4D07-BF3F-86AC512CE626}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58737D93-9A12-4D07-BF3F-86AC512CE626}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58737D93-9A12-4D07-BF3F-86AC512CE626}.Release|Any CPU.Build.0 = Release|Any CPU
{EE03BAE3-52EE-4E3B-8992-382D89E61E1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EE03BAE3-52EE-4E3B-8992-382D89E61E1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EE03BAE3-52EE-4E3B-8992-382D89E61E1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EE03BAE3-52EE-4E3B-8992-382D89E61E1A}.Release|Any CPU.Build.0 = Release|Any CPU
{23DBD9A3-2107-44AB-8B87-6982BFD2E69A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{23DBD9A3-2107-44AB-8B87-6982BFD2E69A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{23DBD9A3-2107-44AB-8B87-6982BFD2E69A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{23DBD9A3-2107-44AB-8B87-6982BFD2E69A}.Release|Any CPU.Build.0 = Release|Any CPU
{FCA95914-11AF-494A-8116-BB7B3253D925}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FCA95914-11AF-494A-8116-BB7B3253D925}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FCA95914-11AF-494A-8116-BB7B3253D925}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FCA95914-11AF-494A-8116-BB7B3253D925}.Release|Any CPU.Build.0 = Release|Any CPU
{3ADC69D9-EACA-4D59-840E-EB4A7F40BAEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3ADC69D9-EACA-4D59-840E-EB4A7F40BAEE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3ADC69D9-EACA-4D59-840E-EB4A7F40BAEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3ADC69D9-EACA-4D59-840E-EB4A7F40BAEE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -8,4 +8,23 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.2.2" />
<PackageReference Include="ReportViewerCore.WinForms" Version="15.1.17" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopBusinessLogic\BlacksmithWorkshopBusinessLogic.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopFileImplement\BlacksmithWorkshopFileImplement.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -1,39 +0,0 @@
namespace BlacksmithWorkshop
{
partial class Form1
{
/// <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.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace BlacksmithWorkshop
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,151 @@
namespace BlacksmithWorkshop
{
partial class FormAddManufacture
{
/// <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.labelIceCream = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.labelShop = new System.Windows.Forms.Label();
this.comboBoxManufacture = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// labelIceCream
//
this.labelIceCream.AutoSize = true;
this.labelIceCream.Location = new System.Drawing.Point(28, 58);
this.labelIceCream.Name = "labelIceCream";
this.labelIceCream.Size = new System.Drawing.Size(56, 15);
this.labelIceCream.TabIndex = 0;
this.labelIceCream.Text = "Изделие:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(28, 91);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(75, 15);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(28, 23);
this.labelShop.Name = "labelShop";
this.labelShop.Size = new System.Drawing.Size(57, 15);
this.labelShop.TabIndex = 2;
this.labelShop.Text = "Магазин:";
//
// comboBoxManufacture
//
this.comboBoxManufacture.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxManufacture.FormattingEnabled = true;
this.comboBoxManufacture.Location = new System.Drawing.Point(149, 55);
this.comboBoxManufacture.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.comboBoxManufacture.Name = "comboBoxManufacture";
this.comboBoxManufacture.Size = new System.Drawing.Size(230, 23);
this.comboBoxManufacture.TabIndex = 3;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(149, 88);
this.textBoxCount.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(230, 23);
this.textBoxCount.TabIndex = 4;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(209, 123);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(82, 22);
this.buttonSave.TabIndex = 6;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(297, 123);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(82, 22);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// comboBoxShop
//
this.comboBoxShop.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(149, 23);
this.comboBoxShop.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(230, 23);
this.comboBoxShop.TabIndex = 8;
//
// FormAddManufacture
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(394, 159);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxManufacture);
this.Controls.Add(this.labelShop);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelIceCream);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormAddManufacture";
this.Text = "Пополнение магазина";
this.Load += new System.EventHandler(this.FormAddManufacture_Load_1);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelIceCream;
private Label labelCount;
private Label labelShop;
private ComboBox comboBoxManufacture;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
private ComboBox comboBoxShop;
}
}

View File

@ -0,0 +1,128 @@
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormAddManufacture : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logicI;
private readonly IShopLogic _logicS;
public FormAddManufacture(ILogger<FormAddManufacture> logger, IManufactureLogic logicI, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicI = logicI;
_logicS = logicS;
}
private void FormAddManufacture_Load_1(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка списка изделий для пополнения");
try
{
var list = _logicI.ReadList(null);
if (list != null)
{
comboBoxManufacture.DisplayMember = "ManufactureName";
comboBoxManufacture.ValueMember = "Id";
comboBoxManufacture.DataSource = list;
comboBoxManufacture.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка списка магазинов для пополнения");
try
{
var list = _logicS.ReadList(null);
if (list != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = list;
comboBoxShop.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxManufacture.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Пополнение магазина");
try
{
var operationResult = _logicS.AddManufacture(new ShopSearchModel
{
Id = Convert.ToInt32(comboBoxShop.SelectedValue)
},
_logicI.ReadElement(new ManufactureSearchModel()
{
Id = Convert.ToInt32(comboBoxManufacture.SelectedValue)
})!, Convert.ToInt32(textBoxCount.Text));
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);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,88 @@
namespace BlacksmithWorkshop
{
partial class FormClients
{
/// <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();
buttonDelete = new Button();
buttonRef = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(582, 426);
dataGridView.TabIndex = 0;
//
// buttonDelete
//
buttonDelete.Location = new Point(638, 35);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(125, 29);
buttonDelete.TabIndex = 1;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonRef
//
buttonRef.Location = new Point(638, 103);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(125, 29);
buttonRef.TabIndex = 2;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// FormClients
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRef);
Controls.Add(buttonDelete);
Controls.Add(dataGridView);
Name = "FormClients";
Text = "Клиенты";
Load += FormClients_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonDelete;
private Button buttonRef;
}
}

View File

@ -0,0 +1,96 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormClients : Form
{
private readonly ILogger _logger;
private readonly IClientLogic _clientLogic;
public FormClients(ILogger<FormClients> logger, IClientLogic clientLogic)
{
InitializeComponent();
_logger = logger;
_clientLogic = clientLogic;
}
private void FormClients_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка клиентов");
try
{
var list = _clientLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Успешная загрузка клиентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_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 (!_clientLogic.Delete(new ClientBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,166 @@
namespace BlacksmithWorkshop
{
partial class FormCreateOrder
{
/// <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()
{
labelManufacture = new Label();
labelCount = new Label();
labelSum = new Label();
comboBoxManufacture = new ComboBox();
textBoxCount = new TextBox();
textBoxSum = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
labelClient = new Label();
comboBoxClient = new ComboBox();
SuspendLayout();
//
// labelManufacture
//
labelManufacture.AutoSize = true;
labelManufacture.Location = new Point(24, 24);
labelManufacture.Name = "labelManufacture";
labelManufacture.Size = new Size(71, 20);
labelManufacture.TabIndex = 0;
labelManufacture.Text = "Изделие:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(24, 114);
labelCount.Name = "labelCount";
labelCount.Size = new Size(93, 20);
labelCount.TabIndex = 1;
labelCount.Text = "Количество:";
//
// labelSum
//
labelSum.AutoSize = true;
labelSum.Location = new Point(24, 157);
labelSum.Name = "labelSum";
labelSum.Size = new Size(58, 20);
labelSum.TabIndex = 2;
labelSum.Text = "Сумма:";
//
// comboBoxManufacture
//
comboBoxManufacture.FormattingEnabled = true;
comboBoxManufacture.Location = new Point(166, 21);
comboBoxManufacture.Name = "comboBoxManufacture";
comboBoxManufacture.Size = new Size(278, 28);
comboBoxManufacture.TabIndex = 3;
comboBoxManufacture.SelectedIndexChanged += ComboBoxManufacture_SelectedIndexChanged;
//
// textBoxCount
//
textBoxCount.Location = new Point(166, 111);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(278, 27);
textBoxCount.TabIndex = 4;
textBoxCount.TextChanged += TextBoxCount_TextChanged;
//
// textBoxSum
//
textBoxSum.Location = new Point(166, 154);
textBoxSum.Name = "textBoxSum";
textBoxSum.Size = new Size(278, 27);
textBoxSum.TabIndex = 5;
//
// buttonSave
//
buttonSave.Location = new Point(230, 199);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(340, 199);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// labelClient
//
labelClient.AutoSize = true;
labelClient.Location = new Point(24, 69);
labelClient.Name = "labelClient";
labelClient.Size = new Size(74, 20);
labelClient.TabIndex = 8;
labelClient.Text = "Заказчик:";
//
// comboBoxClient
//
comboBoxClient.FormattingEnabled = true;
comboBoxClient.Location = new Point(166, 66);
comboBoxClient.Name = "comboBoxClient";
comboBoxClient.Size = new Size(278, 28);
comboBoxClient.TabIndex = 9;
//
// FormCreateOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(479, 256);
Controls.Add(comboBoxClient);
Controls.Add(labelClient);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxSum);
Controls.Add(textBoxCount);
Controls.Add(comboBoxManufacture);
Controls.Add(labelSum);
Controls.Add(labelCount);
Controls.Add(labelManufacture);
Name = "FormCreateOrder";
Text = "Заказ";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelManufacture;
private Label labelCount;
private Label labelSum;
private ComboBox comboBoxManufacture;
private TextBox textBoxCount;
private TextBox textBoxSum;
private Button buttonSave;
private Button buttonCancel;
private Label labelClient;
private ComboBox comboBoxClient;
}
}

View File

@ -0,0 +1,165 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logicM;
private readonly IOrderLogic _logicO;
private readonly IClientLogic _logicCl;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IManufactureLogic logicM, IOrderLogic logicO, IClientLogic logicCl)
{
InitializeComponent();
_logger = logger;
_logicM = logicM;
_logicO = logicO;
_logicCl = logicCl;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка изделий для заказа");
try
{
var list = _logicM.ReadList(null);
var listClients = _logicCl.ReadList(null);
if (list != null)
{
comboBoxManufacture.DisplayMember = "ManufactureName";
comboBoxManufacture.ValueMember = "Id";
comboBoxManufacture.DataSource = list;
comboBoxManufacture.SelectedItem = null;
}
if(listClients != null)
{
comboBoxClient.DisplayMember = "ClientFIO";
comboBoxClient.ValueMember = "Id";
comboBoxClient.DataSource = listClients;
comboBoxClient.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий для заказа или списка клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CalcSum()
{
if (comboBoxManufacture.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxManufacture.SelectedValue);
var manufacture = _logicM.ReadElement(new ManufactureSearchModel
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (manufacture?.Price ?? 0), 2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void TextBoxCount_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void ComboBoxManufacture_SelectedIndexChanged(object sender, EventArgs e)
{
CalcSum();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxManufacture.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxClient.SelectedValue == null)
{
MessageBox.Show("Выберите заказчика", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
ManufactureId = Convert.ToInt32(comboBoxManufacture.SelectedValue),
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)
});
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);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,267 @@
namespace BlacksmithWorkshop
{
partial class FormMain
{
/// <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();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
menuStrip = new MenuStrip();
toolStripMenuItem = new ToolStripMenuItem();
workPieceToolStripMenuItem = new ToolStripMenuItem();
manufactureToolStripMenuItem = new ToolStripMenuItem();
shopToolStripMenuItem = new ToolStripMenuItem();
addManufactureToolStripMenuItem = new ToolStripMenuItem();
reportToolStripMenuItem = new ToolStripMenuItem();
groupedOrdersReportToolStripMenuItem = new ToolStripMenuItem();
ordersReportToolStripMenuItem = new ToolStripMenuItem();
workloadStoresReportToolStripMenuItem = new ToolStripMenuItem();
shopsReportToolStripMenuItem = new ToolStripMenuItem();
reportManufactureToolStripMenuItem = new ToolStripMenuItem();
workPieceManufacturesToolStripMenuItem = new ToolStripMenuItem();
buttonSellManufacture = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(11, 36);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(937, 448);
dataGridView.TabIndex = 0;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1014, 67);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(235, 29);
buttonCreateOrder.TabIndex = 1;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(1014, 143);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(235, 29);
buttonTakeOrderInWork.TabIndex = 2;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(1014, 220);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(235, 29);
buttonOrderReady.TabIndex = 3;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1014, 296);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(235, 29);
buttonIssuedOrder.TabIndex = 4;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(1014, 369);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(235, 29);
buttonRef.TabIndex = 5;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(6, 3, 0, 3);
menuStrip.Size = new Size(1297, 30);
menuStrip.TabIndex = 6;
menuStrip.Text = "menuStrip1";
//
// toolStripMenuItem
//
toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPieceToolStripMenuItem, manufactureToolStripMenuItem, shopToolStripMenuItem, addManufactureToolStripMenuItem });
toolStripMenuItem.Name = "toolStripMenuItem";
toolStripMenuItem.Size = new Size(117, 24);
toolStripMenuItem.Text = "Справочники";
//
// workPieceToolStripMenuItem
//
workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem";
workPieceToolStripMenuItem.Size = new Size(251, 26);
workPieceToolStripMenuItem.Text = "Заготовки";
workPieceToolStripMenuItem.Click += WorkPieceToolStripMenuItem_Click;
//
// manufactureToolStripMenuItem
//
manufactureToolStripMenuItem.Name = "manufactureToolStripMenuItem";
manufactureToolStripMenuItem.Size = new Size(251, 26);
manufactureToolStripMenuItem.Text = "Изделия";
manufactureToolStripMenuItem.Click += ManufactureToolStripMenuItem_Click;
//
// shopToolStripMenuItem
//
shopToolStripMenuItem.Name = "shopToolStripMenuItem";
shopToolStripMenuItem.Size = new Size(251, 26);
shopToolStripMenuItem.Text = "Магазины";
shopToolStripMenuItem.Click += ShopToolStripMenuItem_Click;
//
// addManufactureToolStripMenuItem
//
addManufactureToolStripMenuItem.Name = "addManufactureToolStripMenuItem";
addManufactureToolStripMenuItem.Size = new Size(251, 26);
addManufactureToolStripMenuItem.Text = "Пополнение магазина";
addManufactureToolStripMenuItem.Click += AddManufactureToolStripMenuItem_Click;
//
// reportToolStripMenuItem
//
reportToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { groupedOrdersReportToolStripMenuItem, ordersReportToolStripMenuItem, workloadStoresReportToolStripMenuItem, shopsReportToolStripMenuItem, reportManufactureToolStripMenuItem, workPieceManufacturesToolStripMenuItem });
reportToolStripMenuItem.Name = "reportToolStripMenuItem";
reportToolStripMenuItem.Size = new Size(73, 24);
reportToolStripMenuItem.Text = "Отчёты";
//
// groupedOrdersReportToolStripMenuItem
//
groupedOrdersReportToolStripMenuItem.Name = "groupedOrdersReportToolStripMenuItem";
groupedOrdersReportToolStripMenuItem.Size = new Size(310, 26);
groupedOrdersReportToolStripMenuItem.Text = "Список заказов за весь период";
groupedOrdersReportToolStripMenuItem.Click += GroupedOrdersReportToolStripMenuItem_Click;
//
// ordersReportToolStripMenuItem
//
ordersReportToolStripMenuItem.Name = "ordersReportToolStripMenuItem";
ordersReportToolStripMenuItem.Size = new Size(310, 26);
ordersReportToolStripMenuItem.Text = "Список заказов";
ordersReportToolStripMenuItem.Click += OrdersReportToolStripMenuItem_Click;
//
// workloadStoresReportToolStripMenuItem
//
workloadStoresReportToolStripMenuItem.Name = "workloadStoresReportToolStripMenuItem";
workloadStoresReportToolStripMenuItem.Size = new Size(310, 26);
workloadStoresReportToolStripMenuItem.Text = "Загруженность магазинов";
workloadStoresReportToolStripMenuItem.Click += WorkloadStoresReportToolStripMenuItem_Click;
//
// shopsReportToolStripMenuItem
//
shopsReportToolStripMenuItem.Name = "shopsReportToolStripMenuItem";
shopsReportToolStripMenuItem.Size = new Size(310, 26);
shopsReportToolStripMenuItem.Text = "Таблица магазинов";
shopsReportToolStripMenuItem.Click += ShopsReportToolStripMenuItem_Click;
//
// reportManufactureToolStripMenuItem
//
reportManufactureToolStripMenuItem.Name = "reportManufactureToolStripMenuItem";
reportManufactureToolStripMenuItem.Size = new Size(310, 26);
reportManufactureToolStripMenuItem.Text = "Список изделий";
reportManufactureToolStripMenuItem.Click += ReportManufactureToolStripMenuItem_Click;
//
// workPieceManufacturesToolStripMenuItem
//
workPieceManufacturesToolStripMenuItem.Name = "workPieceManufacturesToolStripMenuItem";
workPieceManufacturesToolStripMenuItem.Size = new Size(310, 26);
workPieceManufacturesToolStripMenuItem.Text = "Заготовки по изделиям";
workPieceManufacturesToolStripMenuItem.Click += WorkPieceManufacturesToolStripMenuItem_Click;
//
// buttonSellManufacture
//
buttonSellManufacture.Location = new Point(1014, 440);
buttonSellManufacture.Name = "buttonSellManufacture";
buttonSellManufacture.Size = new Size(233, 29);
buttonSellManufacture.TabIndex = 7;
buttonSellManufacture.Text = "Продажа изделий";
buttonSellManufacture.UseVisualStyleBackColor = true;
buttonSellManufacture.Click += ButtonSellManufacture_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1297, 496);
Controls.Add(buttonSellManufacture);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
Text = "Кузнечная мастерская";
Load += FormMain_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private MenuStrip menuStrip;
private ToolStripMenuItem toolStripMenuItem;
private ToolStripMenuItem workPieceToolStripMenuItem;
private ToolStripMenuItem manufactureToolStripMenuItem;
private ToolStripMenuItem shopToolStripMenuItem;
private ToolStripMenuItem addManufactureToolStripMenuItem;
private Button buttonSellManufacture;
private ToolStripMenuItem reportToolStripMenuItem;
private ToolStripMenuItem groupedOrdersReportToolStripMenuItem;
private ToolStripMenuItem ordersReportToolStripMenuItem;
private ToolStripMenuItem workloadStoresReportToolStripMenuItem;
private ToolStripMenuItem shopsReportToolStripMenuItem;
private ToolStripMenuItem reportManufactureToolStripMenuItem;
private ToolStripMenuItem workPieceManufacturesToolStripMenuItem;
}
}

View File

@ -0,0 +1,286 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopDataModels.Enums;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ManufactureId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void WorkPieceToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPieces));
if (service is FormWorkPieces form)
{
form.ShowDialog();
}
}
private void ManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactures));
if (service is FormManufactures form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonSellManufacture_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellManufacture));
if (service is FormSellManufacture form)
{
form.ShowDialog();
LoadData();
}
}
private void ShopToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void AddManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormAddManufacture));
if (service is FormAddManufacture form)
{
form.ShowDialog();
LoadData();
}
}
private void GroupedOrdersReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders));
if (service is FormReportGroupedOrders form)
{
form.ShowDialog();
}
}
private void OrdersReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void WorkloadStoresReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopManufactures));
if (service is FormReportShopManufactures form)
{
form.ShowDialog();
}
}
private void ShopsReportToolStripMenuItem_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 ReportManufactureToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveManufacturesToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void WorkPieceManufacturesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportManufactureWorkPieces));
if (service is FormReportManufactureWorkPieces form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,66 @@
<root>
<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>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>63</value>
</metadata>
</root>

View File

@ -0,0 +1,232 @@
namespace BlacksmithWorkshop
{
partial class FormManufacture
{
/// <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.labelName = new System.Windows.Forms.Label();
this.labelCost = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxPrice = new System.Windows.Forms.TextBox();
this.groupBoxWorkPiece = new System.Windows.Forms.GroupBox();
this.buttonRef = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.ColumnID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnPrice = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.groupBoxWorkPiece.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(23, 30);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(80, 20);
this.labelName.TabIndex = 0;
this.labelName.Text = "Название:";
//
// labelCost
//
this.labelCost.AutoSize = true;
this.labelCost.Location = new System.Drawing.Point(23, 84);
this.labelCost.Name = "labelCost";
this.labelCost.Size = new System.Drawing.Size(86, 20);
this.labelCost.TabIndex = 1;
this.labelCost.Text = "Стоимость:";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(133, 27);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(332, 27);
this.textBoxName.TabIndex = 2;
//
// textBoxPrice
//
this.textBoxPrice.Location = new System.Drawing.Point(133, 81);
this.textBoxPrice.Name = "textBoxPrice";
this.textBoxPrice.Size = new System.Drawing.Size(196, 27);
this.textBoxPrice.TabIndex = 3;
//
// groupBoxWorkPiece
//
this.groupBoxWorkPiece.Controls.Add(this.buttonRef);
this.groupBoxWorkPiece.Controls.Add(this.buttonDel);
this.groupBoxWorkPiece.Controls.Add(this.buttonUpd);
this.groupBoxWorkPiece.Controls.Add(this.buttonAdd);
this.groupBoxWorkPiece.Controls.Add(this.dataGridView);
this.groupBoxWorkPiece.Location = new System.Drawing.Point(23, 126);
this.groupBoxWorkPiece.Name = "groupBoxWorkPiece";
this.groupBoxWorkPiece.Size = new System.Drawing.Size(567, 300);
this.groupBoxWorkPiece.TabIndex = 4;
this.groupBoxWorkPiece.TabStop = false;
this.groupBoxWorkPiece.Text = "Заготовки";
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(454, 196);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(94, 29);
this.buttonRef.TabIndex = 4;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(454, 145);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(94, 29);
this.buttonDel.TabIndex = 3;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(454, 95);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(94, 29);
this.buttonUpd.TabIndex = 2;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(454, 43);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnID,
this.ColumnName,
this.ColumnPrice});
this.dataGridView.Location = new System.Drawing.Point(6, 26);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(436, 268);
this.dataGridView.TabIndex = 0;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(340, 448);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(95, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(458, 448);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// ColumnID
//
this.ColumnID.HeaderText = "Id";
this.ColumnID.MinimumWidth = 6;
this.ColumnID.Name = "ColumnID";
this.ColumnID.Visible = false;
this.ColumnID.Width = 125;
//
// ColumnName
//
this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnName.HeaderText = "Название";
this.ColumnName.MinimumWidth = 6;
this.ColumnName.Name = "ColumnName";
//
// ColumnPrice
//
this.ColumnPrice.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnPrice.HeaderText = "Количество";
this.ColumnPrice.MinimumWidth = 6;
this.ColumnPrice.Name = "ColumnPrice";
//
// FormManufacture
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(619, 500);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.groupBoxWorkPiece);
this.Controls.Add(this.textBoxPrice);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelCost);
this.Controls.Add(this.labelName);
this.Name = "FormManufacture";
this.Text = "Изделие";
this.Load += new System.EventHandler(this.FormManufacture_Load);
this.groupBoxWorkPiece.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelName;
private Label labelCost;
private TextBox textBoxName;
private TextBox textBoxPrice;
private GroupBox groupBoxWorkPiece;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
private Button buttonSave;
private Button buttonCancel;
private DataGridViewTextBoxColumn ColumnID;
private DataGridViewTextBoxColumn ColumnName;
private DataGridViewTextBoxColumn ColumnPrice;
}
}

View File

@ -0,0 +1,246 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormManufacture : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logic;
private int? _id;
private Dictionary<int, (IWorkPieceModel, int)> _manufactureWorkPieces;
public int Id { set { _id = value; } }
public FormManufacture(ILogger<FormManufacture> logger, IManufactureLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_manufactureWorkPieces = new Dictionary<int, (IWorkPieceModel, int)>();
}
private void FormManufacture_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка изделия");
try
{
var view = _logic.ReadElement(new ManufactureSearchModel { Id = _id.Value });
if(view != null)
{
textBoxName.Text = view.ManufactureName;
textBoxPrice.Text = view.Price.ToString();
_manufactureWorkPieces = view.ManufactureWorkPieces ?? new Dictionary<int, (IWorkPieceModel, int)>();
LoadData();
}
}
catch(Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка заготовок для изделия");
try
{
if(_manufactureWorkPieces != null)
{
dataGridView.Rows.Clear();
foreach(var awp in _manufactureWorkPieces)
{
dataGridView.Rows.Add(new object[] { awp.Key, awp.Value.Item1.WorkPieceName, awp.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch(Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заготовки для изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece));
if (service is FormManufactureWorkPiece form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.WorkPieceModel == null)
{
return;
}
_logger.LogInformation("Добавление новой заготовки:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count);
if (_manufactureWorkPieces.ContainsKey(form.Id))
{
_manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count);
}
else
{
_manufactureWorkPieces.Add(form.Id, (form.WorkPieceModel, form.Count));
}
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactureWorkPiece));
if (service is FormManufactureWorkPiece form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _manufactureWorkPieces[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.WorkPieceModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента:{WorkPieceName} - {Count}", form.WorkPieceModel.WorkPieceName, form.Count);
_manufactureWorkPieces[form.Id] = (form.WorkPieceModel, form.Count);
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление заготовки:{WorkPieceName} - {Count}", dataGridView.SelectedRows[0].Cells[1].Value);
_manufactureWorkPieces?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPrice.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_manufactureWorkPieces == null || _manufactureWorkPieces.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new ManufactureBindingModel
{
Id = _id ?? 0,
ManufactureName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
ManufactureWorkPieces = _manufactureWorkPieces
};
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);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
//в конце умножить на 1.1, так как прибавляем к итоговой стоимости некоторый процент (в данном случае 10%)
private double CalcPrice()
{
double price = 0;
foreach (var elem in _manufactureWorkPieces)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

View File

@ -0,0 +1,69 @@
<root>
<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>
<metadata name="ColumnID.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnPrice.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,119 @@
namespace BlacksmithWorkshop
{
partial class FormManufactureWorkPiece
{
/// <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.labelWorkPiece = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.comboBoxWorkPiece = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelWorkPiece
//
this.labelWorkPiece.AutoSize = true;
this.labelWorkPiece.Location = new System.Drawing.Point(31, 33);
this.labelWorkPiece.Name = "labelWorkPiece";
this.labelWorkPiece.Size = new System.Drawing.Size(81, 20);
this.labelWorkPiece.TabIndex = 0;
this.labelWorkPiece.Text = "Заготовка:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(31, 79);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// comboBoxWorkPiece
//
this.comboBoxWorkPiece.FormattingEnabled = true;
this.comboBoxWorkPiece.Location = new System.Drawing.Point(156, 30);
this.comboBoxWorkPiece.Name = "comboBoxWorkPiece";
this.comboBoxWorkPiece.Size = new System.Drawing.Size(320, 28);
this.comboBoxWorkPiece.TabIndex = 2;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(156, 76);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(320, 27);
this.textBoxCount.TabIndex = 3;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(235, 118);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 4;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(353, 118);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormManufactureWorkPiece
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(526, 168);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxWorkPiece);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelWorkPiece);
this.Name = "FormManufactureWorkPiece";
this.Text = "Заготовки для изделия";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelWorkPiece;
private Label labelCount;
private ComboBox comboBoxWorkPiece;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,89 @@
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BlacksmithWorkshop
{
public partial class FormManufactureWorkPiece : Form
{
private readonly List<WorkPieceViewModel>? _list;
public int Id { get { return Convert.ToInt32(comboBoxWorkPiece.SelectedValue); }
set { comboBoxWorkPiece.SelectedValue = value; } }
public IWorkPieceModel? WorkPieceModel
{
get
{
if(_list == null)
{
return null;
}
foreach(var elem in _list)
{
if(elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count { get { return Convert.ToInt32(textBoxCount.Text); } set {
textBoxCount.Text = value.ToString(); } }
public FormManufactureWorkPiece(IWorkPieceLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if(_list != null)
{
comboBoxWorkPiece.DisplayMember = "WorkPieceName";
comboBoxWorkPiece.ValueMember = "Id";
comboBoxWorkPiece.DataSource = _list;
comboBoxWorkPiece.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxWorkPiece.SelectedValue == null)
{
MessageBox.Show("Выберите заготовку", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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 BlacksmithWorkshop
{
partial class FormManufactures
{
/// <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.buttonAdd = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(653, 36);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 0;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(653, 92);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(94, 29);
this.buttonUpd.TabIndex = 1;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(653, 151);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(94, 29);
this.buttonDelete.TabIndex = 2;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click);
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(653, 203);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(94, 29);
this.buttonRef.TabIndex = 3;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(604, 426);
this.dataGridView.TabIndex = 4;
//
// FormManufactures
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(781, 450);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Name = "FormManufactures";
this.Text = "Изделия";
this.Load += new System.EventHandler(this.FormManufactures_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonAdd;
private Button buttonUpd;
private Button buttonDelete;
private Button buttonRef;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,126 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormManufactures : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logic;
public FormManufactures(ILogger<FormManufactures> logger, IManufactureLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormManufactures_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ManufactureWorkPieces"].Visible = false;
dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка изделий");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufacture));
if (service is FormManufacture form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufacture));
if (service is FormManufacture form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDelete_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 ManufactureBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,92 @@
namespace BlacksmithWorkshop
{
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()
{
panel = new Panel();
buttonToPdf = new Button();
buttonMake = new Button();
panel.SuspendLayout();
SuspendLayout();
//
// panel
//
panel.Controls.Add(buttonToPdf);
panel.Controls.Add(buttonMake);
panel.Dock = DockStyle.Top;
panel.Location = new Point(0, 0);
panel.Margin = new Padding(4, 3, 4, 3);
panel.Name = "panel";
panel.Size = new Size(1031, 40);
panel.TabIndex = 0;
//
// buttonToPdf
//
buttonToPdf.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonToPdf.Location = new Point(878, 8);
buttonToPdf.Margin = new Padding(4, 3, 4, 3);
buttonToPdf.Name = "buttonToPdf";
buttonToPdf.Size = new Size(139, 27);
buttonToPdf.TabIndex = 5;
buttonToPdf.Text = "В Pdf";
buttonToPdf.UseVisualStyleBackColor = true;
buttonToPdf.Click += ButtonToPdf_Click;
//
// buttonMake
//
buttonMake.Location = new Point(476, 8);
buttonMake.Margin = new Padding(4, 3, 4, 3);
buttonMake.Name = "buttonMake";
buttonMake.Size = new Size(139, 27);
buttonMake.TabIndex = 4;
buttonMake.Text = "Сформировать";
buttonMake.UseVisualStyleBackColor = true;
buttonMake.Click += ButtonMake_Click;
//
// FormReportOrders
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1031, 647);
Controls.Add(panel);
Margin = new Padding(4, 3, 4, 3);
Name = "FormReportOrders";
StartPosition = FormStartPosition.CenterScreen;
Text = "Заказы";
panel.ResumeLayout(false);
panel.PerformLayout();
ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonToPdf;
private Button buttonMake;
}
}

View File

@ -0,0 +1,87 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
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 BlacksmithWorkshop
{
public partial class FormReportGroupedOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportGroupedOrders(ILogger<FormReportGroupedOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\Programmist73\\Desktop\\Практика\\2-й курс\\4-й семестр\\PIbd-21_Eliseev_E.E._BlacksmithWorkshop\\BlacksmithWorkshop\\BlacksmithWorkshop\\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,119 @@
namespace BlacksmithWorkshop
{
partial class FormReportManufactureWorkPieces
{
/// <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();
buttonSaveToExcel = new Button();
ColumnManufacture = new DataGridViewTextBoxColumn();
ColumnWorkPiece = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToOrderColumns = true;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnManufacture, ColumnWorkPiece, ColumnCount });
dataGridView.Dock = DockStyle.Bottom;
dataGridView.Location = new Point(0, 63);
dataGridView.Margin = new Padding(4, 5, 4, 5);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.Size = new Size(704, 680);
dataGridView.TabIndex = 0;
//
// buttonSaveToExcel
//
buttonSaveToExcel.Location = new Point(16, 18);
buttonSaveToExcel.Margin = new Padding(4, 5, 4, 5);
buttonSaveToExcel.Name = "buttonSaveToExcel";
buttonSaveToExcel.Size = new Size(212, 35);
buttonSaveToExcel.TabIndex = 1;
buttonSaveToExcel.Text = "Сохранить в Excel";
buttonSaveToExcel.UseVisualStyleBackColor = true;
buttonSaveToExcel.Click += ButtonSaveToExcel_Click;
//
// ColumnManufacture
//
ColumnManufacture.HeaderText = "Изделие";
ColumnManufacture.MinimumWidth = 6;
ColumnManufacture.Name = "ColumnManufacture";
ColumnManufacture.ReadOnly = true;
ColumnManufacture.Width = 200;
//
// ColumnWorkPiece
//
ColumnWorkPiece.HeaderText = "Заготовка";
ColumnWorkPiece.MinimumWidth = 6;
ColumnWorkPiece.Name = "ColumnWorkPiece";
ColumnWorkPiece.ReadOnly = true;
ColumnWorkPiece.Width = 200;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
ColumnCount.Width = 125;
//
// FormReportManufactureWorkPieces
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(704, 743);
Controls.Add(buttonSaveToExcel);
Controls.Add(dataGridView);
Margin = new Padding(4, 5, 4, 5);
Name = "FormReportManufactureWorkPieces";
Text = "Заготовки по изделиям";
Load += FormReportManufactureWorkPieces_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonSaveToExcel;
private DataGridViewTextBoxColumn ColumWorkPiece;
private DataGridViewTextBoxColumn ColumnManufacture;
private DataGridViewTextBoxColumn ColumnWorkPiece;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,94 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormReportManufactureWorkPieces : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportManufactureWorkPieces(ILogger<FormReportManufactureWorkPieces> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportManufactureWorkPieces_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetManufactureWorkPiece();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ManufactureName, "", "" });
foreach (var listElem in elem.WorkPieces)
{
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.SaveManufactureWorkPieceToExcelFile(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,78 @@
<root>
<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>
<metadata name="ColumWorkPiece.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnManufacture.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumWorkPiece.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnManufacture.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,147 @@
namespace BlacksmithWorkshop
{
partial class FormReportOrders
{
/// <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.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.dateTimePickerTo = new System.Windows.Forms.DateTimePicker();
this.labelTo = new System.Windows.Forms.Label();
this.dateTimePickerFrom = new System.Windows.Forms.DateTimePicker();
this.labelFrom = new System.Windows.Forms.Label();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonToPdf);
this.panel.Controls.Add(this.buttonMake);
this.panel.Controls.Add(this.label2);
this.panel.Controls.Add(this.label1);
this.panel.Controls.Add(this.dateTimePickerTo);
this.panel.Controls.Add(this.labelTo);
this.panel.Controls.Add(this.dateTimePickerFrom);
this.panel.Controls.Add(this.labelFrom);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(1031, 40);
this.panel.TabIndex = 0;
//
// buttonToPdf
//
this.buttonToPdf.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonToPdf.Location = new System.Drawing.Point(878, 8);
this.buttonToPdf.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.buttonToPdf.Name = "buttonToPdf";
this.buttonToPdf.Size = new System.Drawing.Size(139, 27);
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(476, 8);
this.buttonMake.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.buttonMake.Name = "buttonMake";
this.buttonMake.Size = new System.Drawing.Size(139, 27);
this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true;
this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click);
//
// dateTimePickerTo
//
this.dateTimePickerTo.Location = new System.Drawing.Point(237, 7);
this.dateTimePickerTo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.dateTimePickerTo.Name = "dateTimePickerTo";
this.dateTimePickerTo.Size = new System.Drawing.Size(163, 23);
this.dateTimePickerTo.TabIndex = 3;
//
// labelTo
//
this.labelTo.AutoSize = true;
this.labelTo.Location = new System.Drawing.Point(208, 10);
this.labelTo.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelTo.Name = "labelTo";
this.labelTo.Size = new System.Drawing.Size(21, 15);
this.labelTo.TabIndex = 2;
this.labelTo.Text = "по";
//
// dateTimePickerFrom
//
this.dateTimePickerFrom.Location = new System.Drawing.Point(37, 7);
this.dateTimePickerFrom.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.dateTimePickerFrom.Name = "dateTimePickerFrom";
this.dateTimePickerFrom.Size = new System.Drawing.Size(163, 23);
this.dateTimePickerFrom.TabIndex = 1;
//
// labelFrom
//
this.labelFrom.AutoSize = true;
this.labelFrom.Location = new System.Drawing.Point(14, 10);
this.labelFrom.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.labelFrom.Name = "labelFrom";
this.labelFrom.Size = new System.Drawing.Size(15, 15);
this.labelFrom.TabIndex = 0;
this.labelFrom.Text = "С";
//
// FormReportOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1031, 647);
this.Controls.Add(this.panel);
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.Name = "FormReportOrders";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Заказы";
this.panel.ResumeLayout(false);
this.panel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonToPdf;
private Button buttonMake;
private Label label2;
private Label label1;
private DateTimePicker dateTimePickerTo;
private Label labelTo;
private DateTimePicker dateTimePickerFrom;
private Label labelFrom;
}
}

View File

@ -0,0 +1,115 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
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 BlacksmithWorkshop
{
//форма с отчётом
public partial class FormReportOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportOrders(ILogger<FormReportOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\Programmist73\\Desktop\\Практика\\2-й курс\\4-й семестр\\PIbd-21_Eliseev_E.E._BlacksmithWorkshop\\BlacksmithWorkshop\\BlacksmithWorkshop\\ReportOrders.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void ButtonMake_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var dataSource = _logic.GetOrders(new ReportBindingModel
{
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
var parameters = new[] { new ReportParameter("ReportParameterPeriod",
$"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") };
reportViewer.LocalReport.SetParameters(parameters);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString());
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonToPdf_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName,
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
_logger.LogInformation("Сохранение списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString());
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,119 @@
<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,118 @@
namespace BlacksmithWorkshop
{
partial class FormReportShopManufactures
{
/// <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();
buttonSaveToExcel = new Button();
ColumnShop = new DataGridViewTextBoxColumn();
ColumnManufacture = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToOrderColumns = true;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnShop, ColumnManufacture, ColumnCount });
dataGridView.Dock = DockStyle.Bottom;
dataGridView.Location = new Point(0, 63);
dataGridView.Margin = new Padding(4, 5, 4, 5);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.Size = new Size(704, 680);
dataGridView.TabIndex = 0;
//
// buttonSaveToExcel
//
buttonSaveToExcel.Location = new Point(16, 18);
buttonSaveToExcel.Margin = new Padding(4, 5, 4, 5);
buttonSaveToExcel.Name = "buttonSaveToExcel";
buttonSaveToExcel.Size = new Size(212, 35);
buttonSaveToExcel.TabIndex = 1;
buttonSaveToExcel.Text = "Сохранить в Excel";
buttonSaveToExcel.UseVisualStyleBackColor = true;
buttonSaveToExcel.Click += ButtonSaveToExcel_Click;
//
// ColumnShop
//
ColumnShop.HeaderText = "Магазин";
ColumnShop.MinimumWidth = 6;
ColumnShop.Name = "ColumnShop";
ColumnShop.ReadOnly = true;
ColumnShop.Width = 200;
//
// ColumnManufacture
//
ColumnManufacture.HeaderText = "Изделие";
ColumnManufacture.MinimumWidth = 6;
ColumnManufacture.Name = "ColumnManufacture";
ColumnManufacture.ReadOnly = true;
ColumnManufacture.Width = 200;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
ColumnCount.Width = 125;
//
// FormReportShopManufactures
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(704, 743);
Controls.Add(buttonSaveToExcel);
Controls.Add(dataGridView);
Margin = new Padding(4, 5, 4, 5);
Name = "FormReportShopManufactures";
Text = "Загруженность магазинов";
Load += FormReportShopManufactures_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonSaveToExcel;
private DataGridViewTextBoxColumn ColumnShop;
private DataGridViewTextBoxColumn ColumnManufacture;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,86 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormReportShopManufactures : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShopManufactures(ILogger<FormReportShopManufactures> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportShopManufactures_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShopManufactures();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" });
foreach (var listElem in elem.Manufactures)
{
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.SaveShopManufacturesToExcelFile(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,60 @@
<root>
<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,121 @@
namespace BlacksmithWorkshop
{
partial class FormSellManufacture
{
/// <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.labelManufacture = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.comboBoxManufacture = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelManufacture
//
this.labelManufacture.AutoSize = true;
this.labelManufacture.Location = new System.Drawing.Point(32, 32);
this.labelManufacture.Name = "labelManufacture";
this.labelManufacture.Size = new System.Drawing.Size(71, 20);
this.labelManufacture.TabIndex = 0;
this.labelManufacture.Text = "Изделие:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(34, 85);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// comboBoxManufacture
//
this.comboBoxManufacture.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxManufacture.FormattingEnabled = true;
this.comboBoxManufacture.Location = new System.Drawing.Point(170, 32);
this.comboBoxManufacture.Name = "comboBoxManufacture";
this.comboBoxManufacture.Size = new System.Drawing.Size(262, 28);
this.comboBoxManufacture.TabIndex = 3;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(170, 85);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(262, 27);
this.textBoxCount.TabIndex = 4;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(239, 141);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 6;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(339, 141);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormSellManufacture
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(440, 180);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxManufacture);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelManufacture);
this.Name = "FormSellManufacture";
this.Text = "Продажа изделий";
this.Load += new System.EventHandler(this.FormSellManufacture_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelManufacture;
private Label labelCount;
private ComboBox comboBoxManufacture;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,100 @@
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormSellManufacture : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logicI;
private readonly IShopLogic _logicS;
public FormSellManufacture(ILogger<FormAddManufacture> logger, IManufactureLogic logicI, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicI = logicI;
_logicS = logicS;
}
private void FormSellManufacture_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка списка изделий для продажи");
try
{
var list = _logicI.ReadList(null);
if (list != null)
{
comboBoxManufacture.DisplayMember = "ManufactureName";
comboBoxManufacture.ValueMember = "Id";
comboBoxManufacture.DataSource = list;
comboBoxManufacture.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxManufacture.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Продажа изделия");
try
{
var operationResult = _logicS.SellManufatures(_logicI.ReadElement(new ManufactureSearchModel()
{
Id = Convert.ToInt32(comboBoxManufacture.SelectedValue)
})!, Convert.ToInt32(textBoxCount.Text));
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);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,229 @@
namespace BlacksmithWorkshop
{
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()
{
this.labelName = new System.Windows.Forms.Label();
this.labelAddress = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.groupBoxIceCreams = new System.Windows.Forms.GroupBox();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnManufactureName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelDate = new System.Windows.Forms.Label();
this.dateTimePickerDate = new System.Windows.Forms.DateTimePicker();
this.labelCount = new System.Windows.Forms.Label();
this.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
this.groupBoxIceCreams.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(21, 13);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(80, 20);
this.labelName.TabIndex = 0;
this.labelName.Text = "Название:";
//
// labelAddress
//
this.labelAddress.AutoSize = true;
this.labelAddress.Location = new System.Drawing.Point(304, 12);
this.labelAddress.Name = "labelAddress";
this.labelAddress.Size = new System.Drawing.Size(54, 20);
this.labelAddress.TabIndex = 1;
this.labelAddress.Text = "Адрес:";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(107, 10);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(157, 27);
this.textBoxName.TabIndex = 2;
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(364, 9);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(157, 27);
this.textBoxAddress.TabIndex = 3;
//
// groupBoxIceCreams
//
this.groupBoxIceCreams.Controls.Add(this.dataGridView);
this.groupBoxIceCreams.Location = new System.Drawing.Point(14, 94);
this.groupBoxIceCreams.Name = "groupBoxIceCreams";
this.groupBoxIceCreams.Size = new System.Drawing.Size(823, 275);
this.groupBoxIceCreams.TabIndex = 4;
this.groupBoxIceCreams.TabStop = false;
this.groupBoxIceCreams.Text = "Изделия";
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ID,
this.ColumnManufactureName,
this.ColumnCount});
this.dataGridView.Location = new System.Drawing.Point(6, 27);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(810, 243);
this.dataGridView.TabIndex = 0;
//
// ID
//
this.ID.HeaderText = "ID";
this.ID.MinimumWidth = 6;
this.ID.Name = "ID";
this.ID.Visible = false;
this.ID.Width = 125;
//
// ColumnManufactureName
//
this.ColumnManufactureName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnManufactureName.HeaderText = "Изделие";
this.ColumnManufactureName.MinimumWidth = 6;
this.ColumnManufactureName.Name = "ColumnManufactureName";
this.ColumnManufactureName.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// ColumnCount
//
this.ColumnCount.HeaderText = "Количество";
this.ColumnCount.MinimumWidth = 6;
this.ColumnCount.Name = "ColumnCount";
this.ColumnCount.Width = 125;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(470, 381);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(155, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(662, 381);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(155, 29);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// labelDate
//
this.labelDate.AutoSize = true;
this.labelDate.Location = new System.Drawing.Point(562, 12);
this.labelDate.Name = "labelDate";
this.labelDate.Size = new System.Drawing.Size(113, 20);
this.labelDate.TabIndex = 7;
this.labelDate.Text = "Дата открытия:";
//
// dateTimePickerDate
//
this.dateTimePickerDate.Location = new System.Drawing.Point(681, 9);
this.dateTimePickerDate.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.dateTimePickerDate.Name = "dateTimePickerDate";
this.dateTimePickerDate.Size = new System.Drawing.Size(145, 27);
this.dateTimePickerDate.TabIndex = 9;
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(21, 55);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(173, 20);
this.labelCount.TabIndex = 10;
this.labelCount.Text = "Вместимость магазина:";
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(200, 53);
this.numericUpDownCount.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(145, 27);
this.numericUpDownCount.TabIndex = 11;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(850, 425);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.dateTimePickerDate);
this.Controls.Add(this.labelDate);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.groupBoxIceCreams);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelAddress);
this.Controls.Add(this.labelName);
this.Name = "FormShop";
this.Text = "Магазин";
this.Load += new System.EventHandler(this.FormShop_Load);
this.groupBoxIceCreams.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelName;
private Label labelAddress;
private TextBox textBoxName;
private TextBox textBoxAddress;
private GroupBox groupBoxIceCreams;
private DataGridView dataGridView;
private Button buttonSave;
private Button buttonCancel;
private Label labelDate;
private DateTimePicker dateTimePickerDate;
private DataGridViewTextBoxColumn ID;
private DataGridViewTextBoxColumn ColumnManufactureName;
private DataGridViewTextBoxColumn ColumnCount;
private Label labelCount;
private NumericUpDown numericUpDownCount;
}
}

View File

@ -0,0 +1,138 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
private int? _id;
private Dictionary<int, (IManufactureModel, int)> _shopManufactures;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopManufactures = new Dictionary<int, (IManufactureModel, int)>();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var view = _logic.ReadElement(new ShopSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address.ToString();
dateTimePickerDate.Value = view.DateOpen;
numericUpDownCount.Value = view.MaxCountManufactures;
_shopManufactures = view.ShopManufactures ?? new Dictionary<int, (IManufactureModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка изделий в магазине");
try
{
if (_shopManufactures != null)
{
dataGridView.Rows.Clear();
foreach (var element in _shopManufactures)
{
dataGridView.Rows.Add(new object[] { element.Key, element.Value.Item1.ManufactureName, element.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий в магазине");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
DateOpen = dateTimePickerDate.Value.Date,
MaxCountManufactures = (int)numericUpDownCount.Value
};
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);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,121 @@
namespace BlacksmithWorkshop
{
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()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(10, 9);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(444, 320);
this.dataGridView.TabIndex = 1;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(465, 37);
this.buttonAdd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(133, 22);
this.buttonAdd.TabIndex = 2;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(465, 119);
this.buttonUpd.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(133, 22);
this.buttonUpd.TabIndex = 3;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(465, 197);
this.buttonDel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(133, 22);
this.buttonDel.TabIndex = 4;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(465, 274);
this.buttonRef.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(133, 22);
this.buttonRef.TabIndex = 5;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// FormShops
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(610, 338);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonDel);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "FormShops";
this.Text = "Магазины";
this.Load += new System.EventHandler(this.FormShops_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpd;
private Button buttonDel;
private Button buttonRef;
}
}

View File

@ -0,0 +1,119 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
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 FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopManufactures"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_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 ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDel_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);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,119 @@
namespace BlacksmithWorkshop
{
partial class FormWorkPiece
{
/// <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.labelName = new System.Windows.Forms.Label();
this.labelPrice = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxCost = new System.Windows.Forms.TextBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(30, 24);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(80, 20);
this.labelName.TabIndex = 0;
this.labelName.Text = "Название:";
//
// labelPrice
//
this.labelPrice.AutoSize = true;
this.labelPrice.Location = new System.Drawing.Point(30, 65);
this.labelPrice.Name = "labelPrice";
this.labelPrice.Size = new System.Drawing.Size(48, 20);
this.labelPrice.TabIndex = 1;
this.labelPrice.Text = "Цена:";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(127, 21);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(293, 27);
this.textBoxName.TabIndex = 2;
//
// textBoxCost
//
this.textBoxCost.Location = new System.Drawing.Point(127, 62);
this.textBoxCost.Name = "textBoxCost";
this.textBoxCost.Size = new System.Drawing.Size(179, 27);
this.textBoxCost.TabIndex = 3;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(326, 104);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(212, 104);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 5;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// FormWorkPiece
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(464, 153);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.textBoxCost);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelPrice);
this.Controls.Add(this.labelName);
this.Name = "FormWorkPiece";
this.Text = "Заготовка";
this.Load += new System.EventHandler(this.FormWorkPiece_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelName;
private Label labelPrice;
private TextBox textBoxName;
private TextBox textBoxCost;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,104 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace BlacksmithWorkshop
{
//ôîðìà "Çàãîòîâêà"
public partial class FormWorkPiece : Form
{
private readonly ILogger _logger;
private readonly IWorkPieceLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
//êîíñòðóêòîð
public FormWorkPiece(ILogger<FormWorkPiece> logger, IWorkPieceLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
//ïðè çàãðóçêå ôîðìû
private void FormWorkPiece_Load(object sender, EventArgs e)
{
//ïðîâåðêà íà çàïîëíåíèå ïîëÿ id. Åñëè îíî çàïîëíåíî, òî ïðîáóåì ïîëó÷èòü çàïèñü è âûåñòè å¸ íà ýêðàí
if (_id.HasValue)
{
try
{
_logger.LogInformation("Ïîëó÷åíèå çàãîòîâêè");
var view = _logic.ReadElement(new WorkPieceSearchModel { Id = _id.Value });
if(view != null)
{
textBoxName.Text = view.WorkPieceName;
textBoxCost.Text = view.Cost.ToString();
}
}
catch(Exception ex)
{
_logger.LogError(ex, "Îøèáêà ïîëó÷åíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//îáðàáîòêà íàæàòèÿ êíîïêè Ñîõðàíèòü. Ëèáî ïååðäà¸ò äàííûå äëÿ ñîçäàíèÿ çàãîòîâêè, ëèáî å¸ îáíîâëåíèÿ
private void ButtonSave_Click(object sender, EventArgs e)
{
//ïðîâåðêà íà çàïîëíåíèå ïîëÿ ñ íàçâàíèåì çàãîòîâêè
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Çàïîëíèòå íàçâàíèå", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Ñîõðàíåíèå çàãîòîâêè");
try
{
var model = new WorkPieceBindingModel
{
Id = _id ?? 0,
WorkPieceName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.Text)
};
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);
}
}
//îáðàáîòêà íàæàòèÿ êíîïêè Îòìåíà. Ïðè íàæàòèè ïðîñòî çàêðûâàåì ôîðìó
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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 BlacksmithWorkshop
{
partial class FormWorkPieces
{
/// <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.buttonAdd = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(653, 36);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 0;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(653, 92);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(94, 29);
this.buttonUpd.TabIndex = 1;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(653, 151);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(94, 29);
this.buttonDelete.TabIndex = 2;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click);
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(653, 203);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(94, 29);
this.buttonRef.TabIndex = 3;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(604, 426);
this.dataGridView.TabIndex = 4;
//
// FormWorkPieces
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(781, 450);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Name = "FormWorkPieces";
this.Text = "Заготовки";
this.Load += new System.EventHandler(this.FormWorkPiece_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonAdd;
private Button buttonUpd;
private Button buttonDelete;
private Button buttonRef;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,126 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
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 BlacksmithWorkshop
{
public partial class FormWorkPieces : Form
{
private readonly ILogger _logger;
private readonly IWorkPieceLogic _logic;
public FormWorkPieces(ILogger<FormWorkPieces> logger, IWorkPieceLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormWorkPiece_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
//растягиваем колонку Название на всю ширину, колонку Id скрываем
if(list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["WorkPieceName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заготовок");
}
catch(Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заготовок");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece));
if (service is FormWorkPiece form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
//проверяем наличие выделенной строки
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormWorkPiece));
if (service is FormWorkPiece form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDelete_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 WorkPieceBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -1,17 +1,74 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopBusinessLogic.OfficePackage.Implements;
using BlacksmithWorkshopBusinessLogic.OfficePackage;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace BlacksmithWorkshop
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// To customize application configuration such as set high DPI settings or default font;
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IWorkPieceStorage, WorkPieceStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IManufactureStorage, ManufactureStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IWorkPieceLogic, WorkPieceLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IManufactureLogic, ManufactureLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>();
services.AddTransient<FormWorkPiece>();
services.AddTransient<FormWorkPieces>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormManufacture>();
services.AddTransient<FormManufactures>();
services.AddTransient<FormManufactureWorkPiece>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormAddManufacture>();
services.AddTransient<FormSellManufacture>();
services.AddTransient<FormReportManufactureWorkPieces>();
services.AddTransient<FormReportShopManufactures>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportGroupedOrders>();
}
}
}

View File

@ -0,0 +1,410 @@
<?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="BlacksmithWorkshopContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>10791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetGroupedOrders">
<Query>
<DataSourceName>BlacksmithWorkshopContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="DateCreate">
<DataField>DateCreate</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="Count">
<DataField>Count</DataField>
<rd:TypeName>System.Int32</rd:TypeName>
</Field>
<Field Name="Sum">
<DataField>Sum</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>BlacksmithWorkshopContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportGroupedOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>BlacksmithWorkshopContracts.ViewModels.ReportGroupedOrdersViewModel, BlacksmithWorkshopContracts, 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>
<FontSize>16pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>1cm</Height>
<Width>10.19559cm</Width>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>3.21438cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.21438cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.21438cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Textbox1">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата создания</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox1</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="Textbox3">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Количество заказов</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox3</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="Textbox2">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Сумма по заказам</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox2</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>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="DateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!DateCreate.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>DateCreate</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="Count">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Count.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Count</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="Sum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Sum.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Sum</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>2.48391cm</Top>
<Left>0.55245cm</Left>
<Height>1.2cm</Height>
<Width>9.64314cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>Double</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxTotalSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Итого:</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>5.19559cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="SumTotal">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!Sum.Value, "DataSetGroupedOrders")</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>7.69559cm</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>
</ReportItems>
<Height>5.62292cm</Height>
<Style />
</Body>
<Width>10.23146cm</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>
<ReportParametersLayout>
<GridLayoutDefinition>
<NumberOfColumns>4</NumberOfColumns>
<NumberOfRows>2</NumberOfRows>
</GridLayoutDefinition>
</ReportParametersLayout>
<rd:ReportUnitType>Cm</rd:ReportUnitType>
<rd:ReportID>2de0031a-4d17-449d-922d-d9fc54572312</rd:ReportID>
</Report>

View File

@ -0,0 +1,599 @@
<?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="BlacksmithWorkshopContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>10791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetOrders">
<Query>
<DataSourceName>BlacksmithWorkshopContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="Id">
<DataField>Id</DataField>
<rd:TypeName>System.Int32</rd:TypeName>
</Field>
<Field Name="DateCreate">
<DataField>DateCreate</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="ManufactureName">
<DataField>ManufactureName</DataField>
<rd:TypeName>System.String</rd:TypeName>
</Field>
<Field Name="Sum">
<DataField>Sum</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
<Field Name="OrderStatus">
<DataField>OrderStatus</DataField>
<rd:TypeName>System.String</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>BlacksmithWorkshopContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>BlacksmithWorkshopContracts.ViewModels.ReportOrdersViewModel, BlacksmithWorkshopContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="ReportParameterPeriod">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Parameters!ReportParameterPeriod.Value</Value>
<Style>
<FontSize>14pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<rd:DefaultName>ReportParameterPeriod</rd:DefaultName>
<Top>1cm</Top>
<Height>1cm</Height>
<Width>21cm</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="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Заказы</Value>
<Style>
<FontSize>16pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>1cm</Height>
<Width>21cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>2.5cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.21438cm</Width>
</TablixColumn>
<TablixColumn>
<Width>8.23317cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.21438cm</Width>
</TablixColumn>
<TablixColumn>
<Width>2.5cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Textbox5">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Номер</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox5</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="Textbox1">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата создания</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox1</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="Textbox3">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Изделие</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox3</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="Textbox2">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Статус заказа</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox2</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="Textbox7">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Сумма</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox7</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>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Id">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Id.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Id</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="DateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!DateCreate.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>DateCreate</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="ManufactureName">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!ManufactureName.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>ManufactureName</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="OrderStatus">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!OrderStatus.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>OrderStatus</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="Sum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Sum.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Sum</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 />
<TablixMember />
<TablixMember />
</TablixMembers>
</TablixColumnHierarchy>
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
</TablixMember>
<TablixMember>
<Group Name="Подробности" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
<DataSetName>DataSetOrders</DataSetName>
<Top>2.48391cm</Top>
<Left>0.55245cm</Left>
<Height>1.2cm</Height>
<Width>19.66193cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>Double</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxTotalSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Итого:</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>15.21438cm</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="SumTotal">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!Sum.Value, "DataSetOrders")</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>17.71438cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</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>5.72875cm</Height>
<Style />
</Body>
<Width>21cm</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>2de0031a-4d17-449d-922d-d9fc54572312</rd:ReportID>
</Report>

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="MigraDocCore.DocumentObjectModel" Version="1.3.49" />
<PackageReference Include="MigraDocCore.Rendering" Version="1.3.49" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="PdfSharp.MigraDoc.Standard.DocumentObjectModel" Version="1.51.15" />
<PackageReference Include="PdfSharpStand.MigraDoc.DocumentObjectModel.NetStandard" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,160 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
public class ClientLogic : IClientLogic
{
private readonly ILogger _logger;
private readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage)
{
_logger = logger;
_clientStorage = clientStorage;
}
public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{
_logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model?.ClientFIO, model?.Id);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ClientViewModel? ReadElement(ClientSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. ClientFIO:{ClientFIO}. Id:{Id}", model.ClientFIO, model?.Id);
var element = _clientStorage.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(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ClientBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_clientStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
//проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(ClientBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
//так как при удалении передаём как параметр false
if (!withParams)
{
return;
}
//проверка на наличие ФИО
if (string.IsNullOrEmpty(model.ClientFIO))
{
throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ClientFIO));
}
//проверка на наличие почты
if (string.IsNullOrEmpty(model.Email))
{
throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.Email));
}
//проверка на наличие пароля
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
}
_logger.LogInformation("WorkPiece. ClientFIO:{ClientFIO}. Email:{Email}. Password:{Password}. Id:{Id}",
model.ClientFIO, model.Email, model.Password, model.Id);
//для проверка на наличие такого же аккаунта
var element = _clientStorage.GetElement(new ClientSearchModel
{
Email = model.Email,
});
//если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Аккаунт с таким логином уже есть");
}
}
}
}

View File

@ -0,0 +1,160 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
public class ManufactureLogic : IManufactureLogic
{
private readonly ILogger _logger;
private readonly IManufactureStorage _manufactureStorage;
//конструктор
public ManufactureLogic(ILogger<ManufactureLogic> logger, IManufactureStorage manufactureStorage)
{
_logger = logger;
_manufactureStorage = manufactureStorage;
}
//вывод отфильтрованного списка
public List<ManufactureViewModel>? ReadList(ManufactureSearchModel? model)
{
_logger.LogInformation("ReadList. ManufactureName:{ManufactureName}. Id:{Id}", model?.ManufactureName, model?.Id);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _manufactureStorage.GetFullList() : _manufactureStorage.GetFilteredList(model);
if(list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
//вывод конкретного изделия
public ManufactureViewModel? ReadElement(ManufactureSearchModel model)
{
if(model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ManufactureName:{ManufactureName}. Id:{Id}", model.ManufactureName, model.Id);
var element = _manufactureStorage.GetElement(model);
if(element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", model.Id);
return element;
}
//Создание изделия
public bool Create(ManufactureBindingModel model)
{
CheckModel(model);
if(_manufactureStorage.Insert(model) == null)
{
_logger.LogWarning("Create operation failed");
return false;
}
return true;
}
//обновление изделия
public bool Update(ManufactureBindingModel model)
{
CheckModel(model);
if(_manufactureStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
//удаление изделия
public bool Delete(ManufactureBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if(_manufactureStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
//проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(ManufactureBindingModel model, bool withParams = true)
{
if(model == null)
{
throw new ArgumentNullException(nameof(model));
}
//так как при удалении параметром withParams передаём false
if (!withParams)
{
return;
}
//проверка на наличие названия изделия
if (string.IsNullOrEmpty(model.ManufactureName))
{
throw new ArgumentNullException("Нет названия изделия", nameof(model.ManufactureName));
}
//проверка на наличие нормальной цены у изделия
if(model.Price <= 0)
{
throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Manufacture. ManufactureName:{ManufactureName}. Price:{Price}. Id:{Id}",
model.ManufactureName, model.Price, model.Id);
//проверка на наличие такого же изделия в списке
var element = _manufactureStorage.GetElement(new ManufactureSearchModel
{
ManufactureName = model.ManufactureName,
});
//если элемент найден и его Id не совпадает с Id объекта, переданного на вход
if(element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Изделие с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,196 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopLogic _shopLogic;
private readonly IManufactureStorage _manufactureStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IManufactureStorage manufactureStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_manufactureStorage = manufactureStorage;
}
//вывод отфильтрованного списка компонентов
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{Id}", model?.Id);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if(list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
//создание чека
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if(model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Insert operation failed, incorrect order status");
return false;
}
model.Status = OrderStatus.Принят;
if(_orderStorage.Insert(model) == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool FinishOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выдан);
}
//проверка на пустоту входного параметра
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if(model == null)
{
throw new ArgumentNullException(nameof(model));
}
//так как при удалении параметром withParams передаём false
if (!withParams)
{
return;
}
//проверка на наличие товаров в заказе
if(model.Count <= 0)
{
throw new ArgumentNullException("В заказе не может быть 0 изделий", nameof(model.Count));
}
//проверка на наличие нормальной суммарной стоимости чека
if(model.Sum <= 0)
{
throw new ArgumentNullException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum));
}
//проверка корректности id у изделий
if (model.ManufactureId < 0)
{
throw new ArgumentNullException("Некорректный id у изделия", nameof(model.ManufactureId));
}
//проверка корректности дат
if(model.DateCreate > model.DateImplement)
{
throw new InvalidOperationException("Дата создания должна быть более ранней, нежели дата завершения");
}
if (model.ClientId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.ClientId));
}
_logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}. ClientId:{ClientId}. ManufactureId:{Id}", model.Id, model.Sum, model.ClientId, model.ManufactureId);
}
//обновление статуса заказа
public bool StatusUpdate(OrderBindingModel model, OrderStatus newOrderStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
//если не смогли найти указанный заказ по его Id
if (viewModel == null)
{
throw new ArgumentNullException(nameof(model));
}
//проверка на возможность обновления статуса на следующий
if (viewModel.Status + 1 != newOrderStatus)
{
_logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect");
return false;
}
model.Status = newOrderStatus;
//проверка на выдачу
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
var manufacture = _manufactureStorage.GetElement(new() { Id = viewModel.ManufactureId });
if (manufacture == null)
{
throw new ArgumentNullException(nameof(manufacture));
}
if (!_shopLogic.AddManufactures(manufacture, viewModel.Count))
{
throw new Exception($"AddManufactures operation failed. Shop is full.");
}
}
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
//финальная проверка на возможность обновления
if (_orderStorage.Update(model) == null)
{
model.Status--;
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,197 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using BlacksmithWorkshopBusinessLogic.OfficePackage;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
//Реализация бизнес-логики отчётов
public class ReportLogic : IReportLogic
{
private readonly IManufactureStorage _manufactureStorage;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IManufactureStorage manufactureStorage, IOrderStorage orderStorage, IShopStorage shopStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_manufactureStorage = manufactureStorage;
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
//Получение списка заготовок с указанием, в каких изделиях используются
public List<ReportManufactureWorkPieceViewModel> GetManufactureWorkPiece()
{
var manufactures = _manufactureStorage.GetFullList();
var list = new List<ReportManufactureWorkPieceViewModel>();
foreach (var manufacture in manufactures)
{
var record = new ReportManufactureWorkPieceViewModel
{
ManufactureName = manufacture.ManufactureName,
WorkPieces = new List<(string, int)>(),
TotalCount = 0
};
foreach (var workPiece in manufacture.ManufactureWorkPieces)
{
record.WorkPieces.Add(new(workPiece.Value.Item1.WorkPieceName, workPiece.Value.Item2));
record.TotalCount += workPiece.Value.Item2;
}
list.Add(record);
}
return list;
}
//Получение списка изделий с указанием, в каких магазинах в наличии
public List<ReportShopManufacturesViewModel> GetShopManufactures()
{
var shops = _shopStorage.GetFullList();
var list = new List<ReportShopManufacturesViewModel>();
foreach (var shop in shops)
{
var record = new ReportShopManufacturesViewModel
{
ShopName = shop.ShopName,
Manufactures = new List<(string, int)>(),
TotalCount = 0
};
foreach (var manufacture in shop.ShopManufactures)
{
record.Manufactures.Add(new(manufacture.Value.Item1.ManufactureName, manufacture.Value.Item2));
record.TotalCount += manufacture.Value.Item2;
}
list.Add(record);
}
return list;
}
//Получение списка заказов за определенный период
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
{
return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo })
.Select(x => new ReportOrdersViewModel
{
Id = x.Id,
DateCreate = x.DateCreate,
ManufactureName = x.ManufactureName,
Sum = x.Sum,
OrderStatus = x.Status.ToString()
})
.ToList();
}
//Получение списка заказов за весь период
public List<ReportGroupedOrdersViewModel> GetGroupedOrders()
{
return _orderStorage.GetFullList()
.GroupBy(x => x.DateCreate.Date)
.Select(x => new ReportGroupedOrdersViewModel
{
DateCreate = x.Key,
Count = x.Count(),
Sum = x.Sum(x => x.Sum)
})
.ToList();
}
//Сохранение изделий в файл-Word
public void SaveManufacturesToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список изделий",
Manufactures = _manufactureStorage.GetFullList()
});
}
//Сохранение магазинов в файл-Word
public void SaveShopsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateTable(new WordInfo
{
FileName = model.FileName,
Title = "Таблица магазинов",
Shops = _shopStorage.GetFullList()
});
}
//Сохранение изделий с указаеним заготовок в файл-Excel
public void SaveManufactureWorkPieceToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список заготовок",
ManufactureWorkPieces = GetManufactureWorkPiece()
});
}
//Сохранение магазинов с указанием изделий в файл-Excel
public void SaveShopManufacturesToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateShopReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список магазинов",
ShopManufactures = GetShopManufactures()
});
}
//Сохранение заказов в файл-Pdf
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список заказов",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
Orders = GetOrders(model)
});
}
//Сохранение заказов за весь период в файл-Pdf
public void SaveGroupedOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateGroupedDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список заказов",
GroupedOrders = GetGroupedOrders()
});
}
}
}

View File

@ -0,0 +1,250 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
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 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 AddManufacture(ShopSearchModel model, IManufactureModel manufacture, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (count <= 0)
{
throw new ArgumentNullException("Количество добавляемых изделий должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddManufacture. ShopName:{ShopName}. Id: {Id}", model?.ShopName, model?.Id);
var shop = _shopStorage.GetElement(model);
if (shop == null)
{
_logger.LogWarning("Add Manufacture operation failed");
return false;
}
if (shop.MaxCountManufactures - shop.ShopManufactures.Select(x => x.Value.Item2).Sum() < count)
{
throw new ArgumentNullException("Слишком много изделий для одного магазина", nameof(count));
}
if (!shop.ShopManufactures.ContainsKey(manufacture.Id))
{
shop.ShopManufactures[manufacture.Id] = (manufacture, count);
}
else
{
shop.ShopManufactures[manufacture.Id] = (manufacture, shop.ShopManufactures[manufacture.Id].Item2 + count);
}
_shopStorage.Update(new ShopBindingModel()
{
Id = shop.Id,
ShopName = shop.ShopName,
Address = shop.Address,
DateOpen = shop.DateOpen,
MaxCountManufactures = shop.MaxCountManufactures,
ShopManufactures = shop.ShopManufactures
});
return true;
}
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.ShopName))
{
throw new ArgumentNullException("Отсутствует названия магазина", nameof(model.ShopName));
}
if (string.IsNullOrEmpty(model.Address))
{
throw new ArgumentNullException("Отсутствует адреса магазина", nameof(model.Address));
}
_logger.LogInformation("Shop. ShopName:{ShopName}. Address:{Address}. Id: {Id}", model.ShopName, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool AddManufactures(IManufactureModel model, int count)
{
if (count <= 0)
{
throw new ArgumentNullException("Количество добавляемых изделий должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddManufactures. Manufacture: {Manufacture}. Count: {Count}", model?.ManufactureName, count);
var capacity = _shopStorage.GetFullList().Select(x => x.MaxCountManufactures - x.ShopManufactures.Select(x => x.Value.Item2).Sum()).Sum() - count;
if (capacity < 0)
{
_logger.LogWarning("AddManufactures operation failed. Sell {count} Manufactures ", -capacity);
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
if (shop.MaxCountManufactures - shop.ShopManufactures.Select(x => x.Value.Item2).Sum() < count)
{
if (!AddManufacture(new() { Id = shop.Id }, model, shop.MaxCountManufactures - shop.ShopManufactures.Select(x => x.Value.Item2).Sum()))
{
_logger.LogWarning("AddManufactures operation failed.");
return false;
}
count -= shop.MaxCountManufactures - shop.ShopManufactures.Select(x => x.Value.Item2).Sum();
}
else
{
if (!AddManufacture(new() { Id = shop.Id }, model, count))
{
_logger.LogWarning("AddManufactures operation failed.");
return false;
}
count -= count;
}
if (count == 0)
{
return true;
}
}
return true;
}
public bool SellManufatures(IManufactureModel model, int count)
{
return _shopStorage.SellManufactures(model, count);
}
}
}

View File

@ -0,0 +1,160 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
//класс, реализующий логику для заготовок
public class WorkPieceLogic : IWorkPieceLogic
{
private readonly ILogger _logger;
private readonly IWorkPieceStorage _workPieceStorage;
//конструктор
public WorkPieceLogic(ILogger<WorkPieceLogic> logger, IWorkPieceStorage workPieceStorage)
{
_logger = logger;
_workPieceStorage = workPieceStorage;
}
//вывод отфильтрованного списка компонентов
public List<WorkPieceViewModel>? ReadList(WorkPieceSearchModel? model)
{
_logger.LogInformation("ReadList. WorkPieceName:{WorkPieceName}. Id:{Id}", model?.WorkPieceName, model?.Id);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _workPieceStorage.GetFullList() : _workPieceStorage.GetFilteredList(model);
if(list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
//вывод конкретного заготовки
public WorkPieceViewModel? ReadElement(WorkPieceSearchModel model)
{
if(model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. WorkPieceName:{WorkPieceName}. Id:{Id}", model.WorkPieceName, model.Id);
var element = _workPieceStorage.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(WorkPieceBindingModel model)
{
CheckModel(model);
if(_workPieceStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
//обновление заготовки
public bool Update(WorkPieceBindingModel model)
{
CheckModel(model);
if(_workPieceStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
//удаление заготовки
public bool Delete(WorkPieceBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_workPieceStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
//проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(WorkPieceBindingModel model, bool withParams = true)
{
if(model == null)
{
throw new ArgumentNullException(nameof(model));
}
//так как при удалении передаём как параметр false
if (!withParams)
{
return;
}
//проверка на наличие названия заготовки
if (string.IsNullOrEmpty(model.WorkPieceName)){
throw new ArgumentNullException("Нет названия заготовки", nameof(model.WorkPieceName));
}
//проверка на наличие нормальной цены у заготовки
if(model.Cost <= 0)
{
throw new ArgumentNullException("Цена заготовки должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("WorkPiece. WorkPieceName:{WorkPieceName}. Cost:{Cost}. Id:{Id}",
model.WorkPieceName, model.Cost, model.Id);
//проверка на наличие такой же заготовки в списке
var element = _workPieceStorage.GetElement(new WorkPieceSearchModel
{
WorkPieceName = model.WorkPieceName,
});
//если элемент найден и его Id не совпадает с Id переданного объекта
if(element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Заготовка с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,176 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
//Создание отчета
public void CreateReport(ExcelInfo info)
{
CreateExcel(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 mwp in info.ManufactureWorkPieces)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = mwp.ManufactureName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (WorkPiece, Count) in mwp.WorkPieces)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = WorkPiece,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = mwp.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
public void CreateShopReport(ExcelInfo info)
{
CreateExcel(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 sm in info.ShopManufactures)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = sm.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Manufacture, Count) in sm.Manufactures)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Manufacture,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = sm.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
//Создание excel-файла
protected abstract void CreateExcel(ExcelInfo info);
//Добавляем новую ячейку в лист
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
//Объединение ячеек
protected abstract void MergeCells(ExcelMergeParameters excelParams);
//Сохранение файла
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -0,0 +1,91 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
//публичный метод создания документа. Описание методов ниже
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер", "Дата заказа", "Изделие", "Статус заказа", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.Orders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.ManufactureName, order.OrderStatus, order.Sum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right });
SavePdf(info);
}
public void CreateGroupedDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "3cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата заказа", "Количество заказов", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.GroupedOrders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.DateCreate.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupedOrders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
SavePdf(info);
}
//Создание doc-файла
protected abstract void CreatePdf(PdfInfo info);
//Создание параграфа с текстом
protected abstract void CreateParagraph(PdfParagraph paragraph);
//Создание таблицы
protected abstract void CreateTable(List<string> columns);
//Создание и заполнение строки
protected abstract void CreateRow(PdfRowParameters rowParameters);
//Сохранение файла
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,109 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
//метод создания документа
public void CreateDoc(WordInfo 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
}
});
//заполнение абзацев текстом
foreach (var manufacture in info.Manufactures)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (manufacture.ManufactureName + " ", new WordTextProperties { Bold = true, Size = "24" }),
(manufacture.Price.ToString(), new WordTextProperties { Size = "24" }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
public void CreateTable(WordInfo 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
}
});
List<List<(string, WordTextProperties)>> rowList = new()
{
new()
{
new("Название", new WordTextProperties { Bold = true, Size = "24" } ),
new("Адрес", new WordTextProperties { Bold = true, Size = "24" } ),
new("Дата открытия", new WordTextProperties { Bold = true, Size = "24" } )
}
};
foreach (var shop in info.Shops)
{
List<(string, WordTextProperties)> cellList = new()
{
new(shop.ShopName, new WordTextProperties { Size = "24" }),
new(shop.Address, new WordTextProperties { Size = "24" }),
new(shop.DateOpen.ToShortDateString(), new WordTextProperties { Size = "24"})
};
rowList.Add(cellList);
}
CreateTable(new WordParagraph
{
RowTexts = rowList,
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
SaveWord(info);
}
//Создание doc-файла
protected abstract void CreateWord(WordInfo info);
//Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph);
//Создание таблицы
protected abstract void CreateTable(WordParagraph paragraph);
//Сохранение файла
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums
{
//вспомогательное перечисление для оформления exel
public enum ExcelStyleInfoType
{
//заголовок
Title,
//просто текст
Text,
TextWithBorder
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums
{
//вспомогательное перечисление для оформления pdf документа
public enum PdfParagraphAlignmentType
{
//либо по центру
Center,
//либо с левого края
Left,
//либо с правого края
Right
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums
{
//вспомогательное перечисление для настройки формата word документа
public enum WordJustificationType
{
//выравниваем либо по центру
Center,
//либо на всю ширину
Both
}
}

View File

@ -0,0 +1,28 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//информация по ячейке в таблице excel
public class ExcelCellParameters
{
//название колонки
public string ColumnName { get; set; } = string.Empty;
//строка
public uint RowIndex { get; set; }
//тект в ячейке
public string Text { get; set; } = string.Empty;
//геттер для того, чтобы не искать каждый раз
public string CellReference => $"{ColumnName}{RowIndex}";
//в каком стиле выводить информацию
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -0,0 +1,31 @@
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//информация по excel файлу, который хотим создать
public class ExcelInfo
{
//название файла
public string FileName { get; set; } = string.Empty;
//заголовок
public string Title { get; set; } = string.Empty;
public List<ReportManufactureWorkPieceViewModel> ManufactureWorkPieces
{
get;
set;
} = new();
public List<ReportShopManufacturesViewModel> ShopManufactures
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//информация для объединения ячеек
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
//гетер для указания диапазона для объединения, чтобы каждый раз его не вычислять
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,26 @@
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//общая информация по pdf файлу
public class PdfInfo
{
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<ReportOrdersViewModel> Orders { get; set; } = new();
public List<ReportGroupedOrdersViewModel> GroupedOrders { get; set; } = new();
}
}

View File

@ -0,0 +1,20 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//информация п параграфу в pdf документе
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
//информация по выравниванию текста в параграфе
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//информация по параметрам строк таблицы
public class PdfRowParameters
{
//набор текстов
public List<string> Texts { get; set; } = new();
//стиль к текстам
public string Style { get; set; } = string.Empty;
//как выравниваем
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//общая информация по документу
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
//список заготовок для вывода и сохранения
public List<ManufactureViewModel> Manufactures { get; set; } = new();
public List<ShopViewModel> Shops { get; set; } = new();
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//модель параграфов, которые есть в тексте
public class WordParagraph
{
//набор текстов в абзаце (для случая, если в абзаце текст разных стилей)
public List<(string, WordTextProperties)> Texts { get; set; } = new();
//свойства параграфа, если они есть
public WordTextProperties? TextProperties { get; set; }
public List<List<(string, WordTextProperties)>> RowTexts { get; set; } = new();
}
}

View File

@ -0,0 +1,22 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
//модель свойств текста, которые нам нужны в word документе
public class WordTextProperties
{
//размере текста
public string Size { get; set; } = string.Empty;
//надо ли делать его жирным
public bool Bold { get; set; }
//выравнивание
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,393 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Office2016.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
//Настройка стилей для файла
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
//настройка шрифта простого текста
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
//настройка шрифта заголока
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
//добавление созданных шрифтов
fonts.Append(fontUsual);
fonts.Append(fontTitle);
//создание заливки
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
//стиль границ ячейки - незакрашенный (для заголовка) и закрашенный
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorder = new RightBorder()
{
Style = BorderStyleValues.Thin
};
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder()
{
Style = BorderStyleValues.Thin
};
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
//формирование CellFormat из комбинаций шрифтов, заливок и т. д.
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true
};
//по итогу создали 3 стиля
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle = "TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle = "SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
//Получение номера стиля (одного из 3-х нами созданных) из типа
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBorder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfo info)
{
//создаём документ Excel
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
: _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
//метод вставки в лист книги
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
// нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference = excelParams.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
//метод объединения ячеек
protected override void MergeCells(ExcelMergeParameters excelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells mergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
mergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
protected override void SaveExcel(ExcelInfo info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Close();
}
}
}

View File

@ -0,0 +1,131 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
{
//реализация астрактного класса создания pdf документа
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
private Section? _section;
private Table? _table;
//преобразование необходимого типа выравнивания в соотвествующее выравнивание в MigraDoc
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
//Создание стилей для документа
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo info)
{
//создаём документ
_document = new Document();
//передаём для него стили
DefineStyles(_document);
//получение первой секции документа
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
//добавляем таблицу в документ как последнюю секцию (?)
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
//добавление строки в таблицу
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
//ячейка добавляется добавлением параграфа
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,222 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
{
//реализация абстрактного класса сохранения в word
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
//Получение типа выравнивания
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
//выравнивание слева будет в том случае, если передаётся неизвестный тип выравнивания
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
//Настройки страницы
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
//прописываем портретную ориентацию
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
//Задание форматирования для абзаца
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
//вытаскиваем выравнивание текста
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size });
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateWord(WordInfo info)
{
//создаём документ word
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
//вытаскиваем главную часть из вордовского документа
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
//генерируем тело основной части документа
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph paragraph)
{
//проверка на то, был ли вызван WordprocessingDocument.Create (создался ли документ) и есть ли вообще параграф для вставки
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
//добавляем свойства параграфа
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
//вставляем блоки текста (их называют Run)
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);
}
_docBody.AppendChild(docParagraph);
}
//метод сохранения документа
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
//вставляем информацию по секциям (смотри, что является входным параметром)
_docBody.AppendChild(CreateSectionProperties());
//сохраняем документ
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close();
}
protected override void CreateTable(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
Table table = 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 });
table.AppendChild(tableProp);
TableGrid tableGrid = new TableGrid();
for (int j = 0; j < paragraph.RowTexts[0].Count; ++j)
{
tableGrid.AppendChild(new GridColumn() { Width = "3000" });
}
table.AppendChild(tableGrid);
for (int i = 0; i < paragraph.RowTexts.Count; ++i)
{
TableRow docRow = new TableRow();
for (int j = 0; j < paragraph.RowTexts[i].Count; ++j)
{
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.RowTexts[i][j].Item2));
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = paragraph.RowTexts[i][j].Item2.Size });
if (paragraph.RowTexts[i][j].Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = paragraph.RowTexts[i][j].Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
TableCell docCell = new TableCell();
docCell.AppendChild(docParagraph);
docRow.AppendChild(docCell);
}
table.AppendChild(docRow);
}
_docBody.AppendChild(table);
}
}
}

View File

@ -0,0 +1,55 @@
using BlacksmithWorkshopContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace BlacksmithWorkshopClientApp
{
//класс, который общается с RestAPI. Под клиентом тут подразумевается клиент, общающийся с API, а не созданный нами
public class APIClient
{
private static readonly HttpClient _client = new();
//поле, хранящее клиента, которого необходимо авторизовать
public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
//Get-запрос
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
//Post-запрос
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,178 @@
using BlacksmithWorkshopClientApp.Models;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace BlacksmithWorkshopClientApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
//вытаскивает через API клиента Get-запросом список его собственных заказов
public IActionResult Index()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}"));
}
//изменемение ланных Get-ом
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Client);
}
//изменение данных Post-ом
[HttpPost]
public void Privacy(string login, string password, string fio)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как сюда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/updatedata", new ClientBindingModel
{
Id = APIClient.Client.Id,
ClientFIO = fio,
Email = login,
Password = password
});
APIClient.Client.ClientFIO = fio;
APIClient.Client.Email = login;
APIClient.Client.Password = password;
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
//просто открытие вьюхи
[HttpGet]
public IActionResult Enter()
{
return View();
}
//отсылаем указанные данные на проверку
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}");
if (APIClient.Client == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
//просто открытие вьюхи
[HttpGet]
public IActionResult Register()
{
return View();
}
//Post-запрос по созданию нового пользователя
[HttpPost]
public void Register(string login, string password, string fio)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/register", new ClientBindingModel
{
ClientFIO = fio,
Email = login,
Password = password
});
//переход на вкладку "Enter", чтобы пользователь сразу смог зайти
Response.Redirect("Enter");
return;
}
//создание заказа. Получаем и передаём список изделий во вьюху?
[HttpGet]
public IActionResult Create()
{
ViewBag.Manufactures = APIClient.GetRequest<List<ManufactureViewModel>>("api/main/getmanufacturelist");
return View();
}
//создание заказа Post-запросом
[HttpPost]
public void Create(int manufacture, int count)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как сюда попали? Суда вход только авторизованным");
}
if (count <= 0)
{
throw new Exception("Количество и сумма должны быть больше 0");
}
APIClient.PostRequest("api/main/createorder", new OrderBindingModel
{
ClientId = APIClient.Client.Id,
ManufactureId = manufacture,
Count = count,
Sum = Calc(count, manufacture)
});
Response.Redirect("Index");
}
//подсчёт стоимости заказа
[HttpPost]
public double Calc(int count, int manufacture)
{
var manuf =APIClient.GetRequest<ManufactureViewModel>($"api/main/getmanufacture?manufactureId={manufacture}"
);
return count * (manuf?.Price ?? 1);
}
}
}

View File

@ -0,0 +1,9 @@
namespace BlacksmithWorkshopClientApp.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

View File

@ -0,0 +1,31 @@
using BlacksmithWorkshopClientApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51337",
"sslPort": 44340
}
},
"profiles": {
"BlacksmithWorkshopClientApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7147;http://localhost:5287",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,58 @@
@{
ViewData["Title"] = "Create";
}
<div class="text-center">
<h2 class="display-4">Создание заказа</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Изделие:</div>
<div class="col-8">
<select id="manufacture" name="manufacture" class="form-control" asp-items="@(new SelectList(@ViewBag.Manufactures,"Id", "ManufactureName"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Количество:</div>
<div class="col-8">
<input type="text" name="count" id="count"/>
</div>
</div>
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="text" id="sum" name="sum" readonly/>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Создать" class="btn btn-primary" />
</div>
</div>
</form>
<script>
$('#manufacture').on('change', function () {
check();
});
$('#count').on('change', function () {
check();
});
function check() {
var count = $('#count').val();
var manufacture = $('#manufacture').val();
if (count && manufacture) {
$.ajax({
method: "POST",
url: "/Home/Calc",
data: { count: count, manufacture: manufacture },
success: function (result) {
$("#sum").val(result);
}
});
};
}
</script>

View File

@ -0,0 +1,27 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Вход в приложение</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login" /
</div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Вход" class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -0,0 +1,74 @@
@using BlacksmithWorkshopContracts.ViewModels
@model List<OrderViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="Create">Создать заказ</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Изделие
</th>
<th>
Дата создания
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
<th>
Статус
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.ManufactureName)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateCreate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Count)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sum)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,29 @@
@using BlacksmithWorkshopContracts.ViewModels
@model ClientViewModel
@{
ViewData["Title"] = "Privacy Policy";
}
<div class="text-center">
<h2 class="display-4">Личные данные</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" value="@Model.Email"/></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" value="@Model.Password"/></div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8"><input type="text" name="fio" value="@Model.ClientFIO"/></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,34 @@
@{
ViewData["Title"] = "Register";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login" />
</div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password" />
</div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8">
<input type="text" name="fio" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Регистрация" class="btn btn-primary" />
</div>
</div>
</form>

Some files were not shown because too many files have changed in this diff Show More