Compare commits

..

194 Commits

Author SHA1 Message Date
efd2b1aecc ДА НЕУЖЕЛИ сработало?! 2023-04-30 23:10:21 +04:00
8d1b564e59 Оно заработало... 2023-04-30 22:51:52 +04:00
d2e6b8b6f2 Промежуточное сохранение. 2023-04-30 20:35:03 +04:00
a4e6186104 ПОЧТИ ГОТОВАЯ 7-Я ХАРД!!! 2023-04-30 19:38:24 +04:00
6ca35bcd5d Этап с модернизацией писем. 2023-04-30 18:16:40 +04:00
4e78fd4c3e Пагинация для декстопа. 2023-04-30 15:41:31 +04:00
24b5dad676 Вроде исправил косяки. Это был писец. 2023-04-30 15:33:03 +04:00
cdc858faff Мелкие правки. 2023-04-30 15:00:02 +04:00
529391792b Мелкая правка. 2023-04-30 14:54:18 +04:00
08a81cffa0 Merge LabWork07 into LabWork07_Hard. 2023-04-30 14:47:26 +04:00
ea2eb5160b Устранение конфликта. 2023-04-26 13:07:44 +04:00
1ed003dd75 Разрешение конфликта. 2023-04-26 13:05:59 +04:00
ce977c9d9b Точно мелкие правки. 2023-04-25 20:26:54 +04:00
7f22488043 Микро правки. 2023-04-25 20:25:54 +04:00
34a1b5a80e Сданная LabWork06_Hard. 2023-04-25 14:15:01 +04:00
0420bddf00 Сданная LabWork07. 2023-04-25 12:43:24 +04:00
9931a4508c Мелкая правка для возможно более корректной работы. 2023-04-22 10:22:12 +04:00
a637330a3a Мелкое исправление. 2023-04-21 20:44:56 +04:00
d82537bb74 Вроде как рабочий LabWork06_Hard. 2023-04-21 20:23:44 +04:00
4faa4cd16b Некоторые правки. 2023-04-21 18:24:38 +04:00
80c29c8e5c Изменения для работы лабы. 2023-04-21 16:21:48 +04:00
bfb6dca8e7 Merge LabWork06 in LabWork06_Hard. 2023-04-21 12:01:40 +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
52af687507 Вроде рабочая 7-я лаба. 2023-04-21 01:37:39 +04:00
05caea12b2 Очередные правки. 2023-04-21 00:38:51 +04:00
2d3c64b425 Новая миграция. 2023-04-21 00:16:47 +04:00
593ecd9c08 Правки пл 7-й лабораторной. 2023-04-21 00:14:44 +04:00
8ace60f3cb Письма отсылаются, но проблем полно. 2023-04-20 19:42:51 +04:00
b21d4ec176 Промежуточное сохранение. 2023-04-20 16:22:11 +04:00
cb666bdee5 Вроде как осталась только самостоятельная работа. 2023-04-20 11:41:35 +04:00
e2179954bb Корректный файл Program.cs. 2023-04-20 11:24:27 +04:00
6192ee4188 Промежуточное сохранение. 2023-04-20 11:17:55 +04:00
fcf6650356 Готовый слой Contracts. 2023-04-20 11:05:57 +04:00
c0d9a93150 Добавление файла конфигурации. 2023-04-20 10:53:15 +04:00
f0709f4007 Начало 7-й лабы. 2023-04-20 10:48:29 +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
d3b3460047 Меклие праки для корректной работы. 2023-04-11 12:49:02 +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
f0d488c7d2 Мелкая правка. 2023-04-10 21:44:08 +04:00
2e5747230c Ура, вроде теперь готово. 2023-04-06 00:33:29 +04:00
f1567788b9 Вроде как всё работает. 2023-04-06 00:03:07 +04:00
0bd6db4935 Создание форм. 2023-04-05 20:38:30 +04:00
8eb0058613 Работа над финальной формой. 2023-04-05 12:16:01 +04:00
de0494e834 Успешная миграция. 2023-04-05 11:16:20 +04:00
52d5d17600 Implementer и Order для всех вариантов хранения данных. 2023-04-05 11:00:15 +04:00
d15a6c79ee FileImplements для Implementer. 2023-04-05 10:15:33 +04:00
df19ccae5e ListImplement для Implementer. 2023-04-05 10:01:27 +04:00
d346fa4966 BusinessLogic для Implementer. 2023-04-05 09:51:42 +04:00
061b7fed2d Implementer в Contracts. 2023-04-05 09:34:46 +04:00
2fe9574509 Отмена ужасного коммита. 2023-04-05 09:03:17 +04:00
90e721c135 Revert "Промежуточные сохранения. Это капец"
This reverts commit 1d73cccb0d.
2023-04-04 15:17:26 +04:00
1d73cccb0d Промежуточные сохранения. Это капец 2023-04-04 15:05:52 +04:00
62be959e63 Вроде финальные правки по видео. 2023-04-04 14:30:03 +04:00
a721ca0925 Правильное добавление зависимостей. 2023-04-04 14:21:13 +04:00
10d45bf847 LabWork06 по ТЗ. 2023-04-04 13:44:54 +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
426 changed files with 176118 additions and 53 deletions

1
.gitignore vendored
View File

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

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,98 @@
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;
private readonly IMessageInfoLogic _mailLogic;
public int pageSize = 3;
public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController> logger)
{
_logger = logger;
_logic = logic;
_mailLogic = mailLogic;
}
[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;
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId, int page)
{
try
{
return _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId,
Page = page,
PageSize = pageSize
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

View File

@ -0,0 +1,112 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace BlacksmithWorkshopRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ImplementerController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly IImplementerLogic _logic;
public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger<ImplementerController> logger)
{
_logger = logger;
_order = order;
_logic = logic;
}
[HttpGet]
public ImplementerViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new ImplementerSearchModel
{
ImplementerFIO = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка авторизации сотрудника");
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetNewOrders()
{
try
{
return _order.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения новых заказов");
throw;
}
}
[HttpGet]
public OrderViewModel? GetImplementerOrder(int implementerId)
{
try
{
return _order.ReadElement(new OrderSearchModel
{
ImplementerId = implementerId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения текущего заказа исполнителя");
throw;
}
}
[HttpPost]
public void TakeOrderInWork(OrderBindingModel model)
{
try
{
_order.TakeOrderInWork(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id);
throw;
}
}
[HttpPost]
public void FinishOrder(OrderBindingModel model)
{
try
{
_order.FinishOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа с №{ Id}", model.Id);
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,72 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BindingModels;
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<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IManufactureLogic, ManufactureLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
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();
var mailSender = app.Services.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty,
PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
});
// 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,16 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "uveselchak99@gmail.com",
"MailPassword": "nqkv jzzq fryi leao"
}

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

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.gmail.com" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="uveselchak99@gmail.com" />
<add key="MailPassword" value="nqkv jzzq fryi leao" />
</appSettings>
</configuration>

View File

@ -8,4 +8,29 @@
<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>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</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,140 @@
namespace BlacksmithWorkshop
{
partial class FormAnswerMail
{
/// <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()
{
buttonSave = new Button();
buttonCancel = new Button();
textBoxHead = new TextBox();
textBoxBody = new TextBox();
labelHead = new Label();
labelBody = new Label();
labelAnswer = new Label();
textBoxAnswer = new TextBox();
SuspendLayout();
//
// buttonSave
//
buttonSave.Location = new Point(203, 227);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(125, 29);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(350, 227);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(123, 29);
buttonCancel.TabIndex = 1;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// textBoxHead
//
textBoxHead.Location = new Point(151, 34);
textBoxHead.Name = "textBoxHead";
textBoxHead.Size = new Size(322, 27);
textBoxHead.TabIndex = 2;
//
// textBoxBody
//
textBoxBody.Location = new Point(151, 98);
textBoxBody.Name = "textBoxBody";
textBoxBody.Size = new Size(322, 27);
textBoxBody.TabIndex = 3;
//
// labelHead
//
labelHead.AutoSize = true;
labelHead.Location = new Point(30, 37);
labelHead.Name = "labelHead";
labelHead.Size = new Size(84, 20);
labelHead.TabIndex = 4;
labelHead.Text = "Заголовок:";
//
// labelBody
//
labelBody.AutoSize = true;
labelBody.Location = new Point(30, 101);
labelBody.Name = "labelBody";
labelBody.Size = new Size(94, 20);
labelBody.TabIndex = 5;
labelBody.Text = "Сообщение:";
//
// labelAnswer
//
labelAnswer.AutoSize = true;
labelAnswer.Location = new Point(30, 163);
labelAnswer.Name = "labelAnswer";
labelAnswer.Size = new Size(51, 20);
labelAnswer.TabIndex = 6;
labelAnswer.Text = "Ответ:";
//
// textBoxAnswer
//
textBoxAnswer.Location = new Point(151, 160);
textBoxAnswer.Name = "textBoxAnswer";
textBoxAnswer.Size = new Size(322, 27);
textBoxAnswer.TabIndex = 7;
//
// FormAnswerMail
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(512, 284);
Controls.Add(textBoxAnswer);
Controls.Add(labelAnswer);
Controls.Add(labelBody);
Controls.Add(labelHead);
Controls.Add(textBoxBody);
Controls.Add(textBoxHead);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormAnswerMail";
Text = "Просмотр письма";
Load += FormAnswerMail_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private TextBox textBoxHead;
private TextBox textBoxBody;
private Label labelHead;
private Label labelBody;
private Label labelAnswer;
private TextBox textBoxAnswer;
}
}

View File

@ -0,0 +1,98 @@
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
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 FormAnswerMail : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
private readonly AbstractMailWorker _mailWorker;
private MessageInfoViewModel _message;
public string MessageId { get; set; } = string.Empty;
public FormAnswerMail(ILogger<FormAnswerMail> logger, AbstractMailWorker mailWorker, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_mailWorker = mailWorker;
_logic = logic;
}
private void FormAnswerMail_Load(object sender, EventArgs e)
{
try
{
_logger.LogInformation("Получение письма");
_message = _logic.ReadElement(new MessageInfoSearchModel { MessageId = MessageId });
if (_message != null)
{
Text += $"для {_message.SenderName}";
textBoxHead.Text = _message.Subject;
textBoxBody.Text = _message.Body;
}
if (_message.IsRead is false)
{
_logic.Update(new() { MessageId = MessageId, IsRead = true, Answer = _message.Answer });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения письма");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
//отправка письма с ответом
_mailWorker.MailSendAsync(new()
{
MailAddress = _message.SenderName,
Subject = _message.Subject,
Text = textBoxAnswer.Text,
});
_logic.Update(new()
{
MessageId = MessageId,
Answer = textBoxAnswer.Text,
IsRead = true,
});
MessageBox.Show("Успешная отправка письма", "Отправка письма", MessageBoxButtons.OK);
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,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,162 @@
namespace BlacksmithWorkshop
{
partial class FormImplementer
{
/// <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()
{
labelFIO = new Label();
labelPassword = new Label();
labelWorkExperience = new Label();
labelQualification = new Label();
textBoxImplementerFIO = new TextBox();
textBoxPassword = new TextBox();
textBoxWorkExperience = new TextBox();
textBoxQualification = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelFIO
//
labelFIO.AutoSize = true;
labelFIO.Location = new Point(38, 27);
labelFIO.Name = "labelFIO";
labelFIO.Size = new Size(45, 20);
labelFIO.TabIndex = 0;
labelFIO.Text = "ФИО:";
//
// labelPassword
//
labelPassword.AutoSize = true;
labelPassword.Location = new Point(38, 79);
labelPassword.Name = "labelPassword";
labelPassword.Size = new Size(65, 20);
labelPassword.TabIndex = 1;
labelPassword.Text = "Пароль:";
//
// labelWorkExperience
//
labelWorkExperience.AutoSize = true;
labelWorkExperience.Location = new Point(38, 136);
labelWorkExperience.Name = "labelWorkExperience";
labelWorkExperience.Size = new Size(102, 20);
labelWorkExperience.TabIndex = 2;
labelWorkExperience.Text = "Стаж работы:";
//
// labelQualification
//
labelQualification.AutoSize = true;
labelQualification.Location = new Point(319, 136);
labelQualification.Name = "labelQualification";
labelQualification.Size = new Size(114, 20);
labelQualification.TabIndex = 3;
labelQualification.Text = "Квалификация:";
//
// textBoxImplementerFIO
//
textBoxImplementerFIO.Location = new Point(160, 24);
textBoxImplementerFIO.Name = "textBoxImplementerFIO";
textBoxImplementerFIO.Size = new Size(436, 27);
textBoxImplementerFIO.TabIndex = 4;
//
// textBoxPassword
//
textBoxPassword.Location = new Point(160, 76);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.Size = new Size(436, 27);
textBoxPassword.TabIndex = 5;
//
// textBoxWorkExperience
//
textBoxWorkExperience.Location = new Point(160, 133);
textBoxWorkExperience.Name = "textBoxWorkExperience";
textBoxWorkExperience.Size = new Size(126, 27);
textBoxWorkExperience.TabIndex = 6;
//
// textBoxQualification
//
textBoxQualification.Location = new Point(444, 133);
textBoxQualification.Name = "textBoxQualification";
textBoxQualification.Size = new Size(152, 27);
textBoxQualification.TabIndex = 7;
//
// buttonSave
//
buttonSave.Location = new Point(387, 178);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(502, 178);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 9;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(662, 224);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxQualification);
Controls.Add(textBoxWorkExperience);
Controls.Add(textBoxPassword);
Controls.Add(textBoxImplementerFIO);
Controls.Add(labelQualification);
Controls.Add(labelWorkExperience);
Controls.Add(labelPassword);
Controls.Add(labelFIO);
Name = "FormImplementer";
Text = "Исполнитель";
Load += FormImplementer_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelFIO;
private Label labelPassword;
private Label labelWorkExperience;
private Label labelQualification;
private TextBox textBoxImplementerFIO;
private TextBox textBoxPassword;
private TextBox textBoxWorkExperience;
private TextBox textBoxQualification;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,138 @@
using BlacksmithWorkshopContracts.BindingModels;
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 FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
//конструктор
public FormImplementer(ILogger<FormImplementer> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
//при загрузке формы
private void FormImplementer_Load(object sender, EventArgs e)
{
//проверка на заполнение поля id. Если оно заполнено, то пробуем получить запись и выести её на экран
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel { Id = _id.Value });
if (view != null)
{
textBoxImplementerFIO.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
textBoxWorkExperience.Text = view.WorkExperience.ToString();
textBoxQualification.Text = view.Qualification.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(textBoxImplementerFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//проверка на заполнение поля с паролем
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Введите пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//проверка на заполнение поля со стажем
if (string.IsNullOrEmpty(textBoxWorkExperience.Text))
{
MessageBox.Show("Введите ваш стаж", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//проверка на заполнение поля с квалификацией
if (string.IsNullOrEmpty(textBoxQualification.Text))
{
MessageBox.Show("Введите свою квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxImplementerFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt16(textBoxWorkExperience.Text),
Qualification = Convert.ToInt16(textBoxQualification.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,114 @@
namespace BlacksmithWorkshop
{
partial class FormImplementers
{
/// <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();
buttonCreate = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonUpdate = 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(768, 426);
dataGridView.TabIndex = 0;
//
// buttonCreate
//
buttonCreate.Location = new Point(805, 22);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(160, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// buttonChange
//
buttonChange.Location = new Point(805, 90);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(160, 29);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonChange_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(805, 153);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(160, 29);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(805, 218);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(160, 29);
buttonUpdate.TabIndex = 4;
buttonUpdate.Text = "Обновить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(991, 450);
Controls.Add(buttonUpdate);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonCreate);
Controls.Add(dataGridView);
Name = "FormImplementers";
Text = "Исполнители";
Load += FormImplementers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonCreate;
private Button buttonChange;
private Button buttonDelete;
private Button buttonUpdate;
}
}

View File

@ -0,0 +1,127 @@
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 FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormWorkPieces> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementers_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["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonChange_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer 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 ImplementerBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonUpdate_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,101 @@
namespace BlacksmithWorkshop
{
partial class FormMails
{
/// <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();
buttonForward = new Button();
buttonBack = new Button();
buttonAnswer = 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(781, 393);
dataGridView.TabIndex = 0;
//
// buttonForward
//
buttonForward.Location = new Point(155, 416);
buttonForward.Name = "buttonForward";
buttonForward.Size = new Size(175, 29);
buttonForward.TabIndex = 1;
buttonForward.Text = "Вперёд";
buttonForward.UseVisualStyleBackColor = true;
buttonForward.Click += ButtonForward_Click;
//
// buttonBack
//
buttonBack.Location = new Point(468, 416);
buttonBack.Name = "buttonBack";
buttonBack.Size = new Size(173, 29);
buttonBack.TabIndex = 2;
buttonBack.Text = "Назад";
buttonBack.UseVisualStyleBackColor = true;
buttonBack.Click += ButtonBack_Click;
//
// buttonAnswer
//
buttonAnswer.Location = new Point(806, 34);
buttonAnswer.Name = "buttonAnswer";
buttonAnswer.Size = new Size(136, 29);
buttonAnswer.TabIndex = 3;
buttonAnswer.Text = "Ответить";
buttonAnswer.UseVisualStyleBackColor = true;
buttonAnswer.Click += ButtonAnswer_Click;
//
// FormMails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(963, 457);
Controls.Add(buttonAnswer);
Controls.Add(buttonBack);
Controls.Add(buttonForward);
Controls.Add(dataGridView);
Name = "FormMails";
Text = "Письма";
Load += FormMails_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonForward;
private Button buttonBack;
private Button buttonAnswer;
}
}

View File

@ -0,0 +1,134 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.ViewModels;
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 FormMails : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _messageLogic;
private int currentPage = 1;
public int pageSize = 5;
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic messageLogic)
{
InitializeComponent();
_logger = logger;
_messageLogic = messageLogic;
buttonBack.Enabled = false;
}
private void FormMails_Load(object sender, EventArgs e)
{
LoadData();
}
private bool LoadData()
{
_logger.LogInformation("Загрузка писем");
try
{
var list = _messageLogic.ReadList(new()
{
Page = currentPage,
PageSize = pageSize,
});
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка списка писем");
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private void ButtonForward_Click(object sender, EventArgs e)
{
currentPage++;
if (!LoadData() || ((List<MessageInfoViewModel>)dataGridView.DataSource).Count == 0)
{
_logger.LogWarning("Обращение к несуществующему письму");
currentPage--;
LoadData();
buttonForward.Enabled = false;
}
else
{
buttonBack.Enabled = true;
}
}
private void ButtonBack_Click(object sender, EventArgs e)
{
if (currentPage == 1)
{
_logger.LogWarning("Неккоректный номер страницы {page}", currentPage - 1);
return;
}
currentPage--;
if (LoadData())
{
buttonForward.Enabled = true;
if (currentPage == 1)
{
buttonBack.Enabled = false;
}
}
}
private void ButtonAnswer_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormAnswerMail));
if (service is FormAnswerMail form)
{
form.MessageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString();
if (form.ShowDialog() == DialogResult.OK)
{
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,295 @@
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();
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();
workWithImplementerToolStripMenuItem = new ToolStripMenuItem();
implementerToolStripMenuItem = new ToolStripMenuItem();
работаСКлиентамиToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem();
startWorkToolStripMenuItem = new ToolStripMenuItem();
buttonSellManufacture = new Button();
messageToolStripMenuItem = new ToolStripMenuItem();
((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;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1014, 141);
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, 214);
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, workWithImplementerToolStripMenuItem, работаСКлиентамиToolStripMenuItem, startWorkToolStripMenuItem });
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;
//
// workWithImplementerToolStripMenuItem
//
workWithImplementerToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { implementerToolStripMenuItem });
workWithImplementerToolStripMenuItem.Name = "workWithImplementerToolStripMenuItem";
workWithImplementerToolStripMenuItem.Size = new Size(196, 24);
workWithImplementerToolStripMenuItem.Text = "Работа с исполнителями";
//
// implementerToolStripMenuItem
//
implementerToolStripMenuItem.Name = "implementerToolStripMenuItem";
implementerToolStripMenuItem.Size = new Size(185, 26);
implementerToolStripMenuItem.Text = "Исполнители";
implementerToolStripMenuItem.Click += ImplementerToolStripMenuItem_Click_1;
//
// работаСКлиентамиToolStripMenuItem
//
работаСКлиентамиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { clientsToolStripMenuItem, messageToolStripMenuItem });
работаСКлиентамиToolStripMenuItem.Name = "работаСКлиентамиToolStripMenuItem";
работаСКлиентамиToolStripMenuItem.Size = new Size(161, 24);
работаСКлиентамиToolStripMenuItem.Text = "Работа с клиентами";
//
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(224, 26);
clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click_1;
//
// startWorkToolStripMenuItem
//
startWorkToolStripMenuItem.Name = "startWorkToolStripMenuItem";
startWorkToolStripMenuItem.Size = new Size(114, 24);
startWorkToolStripMenuItem.Text = "Запуск работ";
startWorkToolStripMenuItem.Click += StartWorkToolStripMenuItem_Click;
//
// buttonSellManufacture
//
buttonSellManufacture.Location = new Point(1014, 285);
buttonSellManufacture.Name = "buttonSellManufacture";
buttonSellManufacture.Size = new Size(233, 29);
buttonSellManufacture.TabIndex = 7;
buttonSellManufacture.Text = "Продажа изделий";
buttonSellManufacture.UseVisualStyleBackColor = true;
buttonSellManufacture.Click += ButtonSellManufacture_Click;
//
// messageToolStripMenuItem
//
messageToolStripMenuItem.Name = "messageToolStripMenuItem";
messageToolStripMenuItem.Size = new Size(224, 26);
messageToolStripMenuItem.Text = "Письма";
messageToolStripMenuItem.Click += MessageToolStripMenuItem_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(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 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;
private ToolStripMenuItem workWithImplementerToolStripMenuItem;
private ToolStripMenuItem implementerToolStripMenuItem;
private ToolStripMenuItem работаСКлиентамиToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem startWorkToolStripMenuItem;
private ToolStripMenuItem messageToolStripMenuItem;
}
}

View File

@ -0,0 +1,273 @@
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;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
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;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_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 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 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 WorkPieceManufacturesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportManufactureWorkPieces));
if (service is FormReportManufactureWorkPieces form)
{
form.ShowDialog();
}
}
private void ImplementerToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
private void StartWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
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 OrdersReportToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void MessageToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMails));
if (service is FormMails 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,117 @@
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;
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BindingModels;
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();
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
// ñîçäàåì òàéìåð
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
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<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IWorkPieceLogic, WorkPieceLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IManufactureLogic, ManufactureLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
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>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormMails>();
services.AddTransient<FormAnswerMail>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
}

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,24 @@
<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="MailKit" Version="4.0.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,171 @@
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.Text.RegularExpressions;
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));
}
if (!Regex.IsMatch(model.Email, @"^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$", RegexOptions.IgnoreCase))
{
throw new ArgumentException("Некорректная почта", nameof(model.Email));
}
if (!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase) && model.Password.Length < 10 && model.Password.Length > 50)
{
throw new ArgumentException("Необходимо придумать другой пароль", nameof(model.Password));
}
_logger.LogInformation("Client. 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,167 @@
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 ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model.ImplementerFIO, model?.Id);
var element = _implementerStorage.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(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
//проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
//так как при удалении передаём как параметр false
if (!withParams)
{
return;
}
//проверка на наличие ФИО
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO));
}
//проверка на наличие пароля
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
}
//проверка на наличие квалификации
if (model.Qualification <= 0)
{
throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification));
}
//проверка на наличие квалификации
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Указан некоректный стаж работы", nameof(model.WorkExperience));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " +
"Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}",
model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id);
//для проверка на наличие такого же аккаунта
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO,
});
//если элемент найден и его 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,92 @@
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 MessageInfoLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageInfoStorage;
public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageInfoStorage)
{
_logger = logger;
_messageInfoStorage = messageInfoStorage;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList. MessageId:{MessageId}", model?.MessageId);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
MessageInfoViewModel? IMessageInfoLogic.ReadElement(MessageInfoSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. ClientId:{ClientId}. MessageId:{MessageId}", model.ClientId, model?.MessageId);
var element = _messageInfoStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.MessageId);
return element;
}
public bool Create(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Update(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,261 @@
using BlacksmithWorkshopBusinessLogic.MailWorker;
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;
private readonly IClientLogic _clientLogic;
private readonly AbstractMailWorker _mailWorker;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IManufactureStorage manufactureStorage, IClientLogic clientLogic, AbstractMailWorker mailWorker)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_manufactureStorage = manufactureStorage;
_clientLogic = clientLogic;
_mailWorker = mailWorker;
}
//вывод отфильтрованного списка компонентов
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 OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{Id}", model?.Id);
var element = _orderStorage.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 CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if(model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Insert operation failed, incorrect order status");
return false;
}
model.Status = OrderStatus.Принят;
var result = _orderStorage.Insert(model);
if (result == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
SendOrderMessage(result.ClientId, $"Кузнечная мастерская, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят");
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 && viewModel.Status != OrderStatus.Ожидание)
{
_logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect");
return false;
}
model.Status = newOrderStatus;
//не забываем положить id работника
if (viewModel.ImplementerId.HasValue)
{
model.ImplementerId = viewModel.ImplementerId;
}
//проверка на выдачу
if (model.Status == OrderStatus.Готов || viewModel.Status == OrderStatus.Ожидание)
{
var manufacture = _manufactureStorage.GetElement(new() { Id = viewModel.ManufactureId });
if (manufacture == null)
{
throw new ArgumentNullException(nameof(manufacture));
}
if (!_shopLogic.AddManufactures(manufacture, viewModel.Count))
{
model.Status = OrderStatus.Ожидание;
_logger.LogWarning($"AddManufactures operation failed. Shop is full.");
}
else
{
model.DateImplement = DateTime.Now;
}
}
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
var result = _orderStorage.Update(model);
//финальная проверка на возможность обновления
if (result == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
SendOrderMessage(result.ClientId, $"Кузнечаня мастерская, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}");
return true;
}
private bool SendOrderMessage(int clientId, string subject, string text)
{
var client = _clientLogic.ReadElement(new() { Id = clientId });
if (client == null)
{
return false;
}
_mailWorker.MailSendAsync(new()
{
MailAddress = client.Email,
Subject = subject,
Text = text
});
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,246 @@
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("AddIceCreams 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("AddIceCreams 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,196 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
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 WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> logger)
{
_logger = logger;
_rnd = new Random(1000);
}
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic)
{
_orderLogic = orderLogic;
var implementers = implementerLogic.ReadList(null);
if (implementers == null)
{
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new() { Status = OrderStatus.Принят });
if (orders == null)
{
_logger.LogWarning("DoWork. Orders is null or empty");
return;
}
_logger.LogDebug("DoWork for {Count} orders", orders.Count);
foreach (var implementer in implementers)
{
Task.Run(() => WorkerWorkAsync(implementer, orders));
}
}
// Иммитация работы исполнителя
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{
if (_orderLogic == null || implementer == null)
{
return;
}
await Task.Run(() =>
{
try
{
var runOrder = _orderLogic.ReadList(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Ожидание
});
if (runOrder == null)
{
return;
}
foreach(var order in runOrder)
{
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id
});
// отдыхаем
//Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
});
await RunOrderInWork(implementer);
await Task.Run(() =>
{
foreach (var order in orders)
{
try
{
_logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id);
// пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
// делаем работу
Thread.Sleep(implementer.WorkExperience * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id,
});
// отдыхаем
Thread.Sleep(implementer.Qualification);
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
});
}
//Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = runOrder.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification);
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
}
}

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,107 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly IMessageInfoLogic _messageInfoLogic;
private readonly IClientLogic _clientLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic)
{
_logger = logger;
_messageInfoLogic = messageInfoLogic;
_clientLogic = clientLogic;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, { popHost}, { popPort}",
_mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{
return;
}
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
public async void MailCheck()
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_popHost) || _popPort == 0)
{
return;
}
if (_messageInfoLogic == null)
{
return;
}
var list = await ReceiveMailAsync();
_logger.LogDebug("Check Mail: {Count} new mails", list.Count);
foreach (var mail in list)
{
mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id;
_messageInfoLogic.Create(mail);
}
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailAsync();
}
}

View File

@ -0,0 +1,91 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Pop3;
using MailKit.Security;
namespace BlacksmithWorkshopBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic)
: base(logger, messageInfoLogic, clientLogic) { }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
protected override async Task<List<MessageInfoBindingModel>> ReceiveMailAsync()
{
var list = new List<MessageInfoBindingModel>();
using var client = new Pop3Client();
await Task.Run(() =>
{
try
{
client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect);
client.Authenticate(_mailLogin, _mailPassword);
for (int i = 0; i < client.Count; i++)
{
var message = client.GetMessage(i);
foreach (var mail in message.From.Mailboxes)
{
list.Add(new MessageInfoBindingModel
{
DateDelivery = message.Date.DateTime,
MessageId = message.MessageId,
SenderName = mail.Address,
Subject = message.Subject,
Body = message.TextBody
});
}
}
}
catch (AuthenticationException)
{ }
finally
{
client.Disconnect(true);
}
});
return list;
}
}
}

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}";
}
}

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