Compare commits

...

4 Commits

Author SHA1 Message Date
Arkadiy Radaev
d55e8566fa res 3 hard 2024-05-18 18:03:56 +04:00
Arkadiy Radaev
89ae0da92a res3 2024-04-07 10:15:40 +04:00
Arkadiy Radaev
7b2d5744f9 res2 2024-04-07 10:14:11 +04:00
Arkadiy Radaev
f31982e59f res1 2024-02-06 12:37:25 +04:00
117 changed files with 8889 additions and 324 deletions

View File

@ -1,9 +1,21 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34202.233
VisualStudioVersion = 17.4.33205.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GiftShop", "GiftShop\GiftShop.csproj", "{1AF43BDD-A676-4353-A97D-8195C7C40405}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GiftShopView", "GiftShopView\GiftShopView.csproj", "{D9DB6CD0-80AE-4E15-905A-C65E5B5E5C6F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GiftShopDataModels", "GiftShopDataModels\GiftShopDataModels.csproj", "{CC3AC359-F8C1-47C1-959D-804D8DF1F681}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GiftShopContracts", "GiftShopContracts\GiftShopContracts.csproj", "{3800C66D-1BCD-4A8B-A9E1-1C578A49DF00}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GiftShopListImplement", "GiftShopListImplement\GiftShopListImplement.csproj", "{5B83AC94-55AC-45CA-8C44-0D0F34E17666}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GiftShopBusinessLogic", "GiftShopBusinessLogic\GiftShopBusinessLogic.csproj", "{07C14020-5905-4CCC-9DAC-53507C8F28F8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GiftShopFileImplement", "GiftShopFileImplement\GiftShopFileImplement.csproj", "{05AE2E86-5464-4B1F-BE91-60FA43CE69F1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GiftShopDatabaseImplement", "GiftShopDatabaseImplement\GiftShopDatabaseImplement.csproj", "{50B7E5D7-A58E-4E36-8A5C-F7E78BB526B0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,15 +23,39 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1AF43BDD-A676-4353-A97D-8195C7C40405}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1AF43BDD-A676-4353-A97D-8195C7C40405}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1AF43BDD-A676-4353-A97D-8195C7C40405}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1AF43BDD-A676-4353-A97D-8195C7C40405}.Release|Any CPU.Build.0 = Release|Any CPU
{D9DB6CD0-80AE-4E15-905A-C65E5B5E5C6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D9DB6CD0-80AE-4E15-905A-C65E5B5E5C6F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D9DB6CD0-80AE-4E15-905A-C65E5B5E5C6F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D9DB6CD0-80AE-4E15-905A-C65E5B5E5C6F}.Release|Any CPU.Build.0 = Release|Any CPU
{CC3AC359-F8C1-47C1-959D-804D8DF1F681}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CC3AC359-F8C1-47C1-959D-804D8DF1F681}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CC3AC359-F8C1-47C1-959D-804D8DF1F681}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CC3AC359-F8C1-47C1-959D-804D8DF1F681}.Release|Any CPU.Build.0 = Release|Any CPU
{3800C66D-1BCD-4A8B-A9E1-1C578A49DF00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3800C66D-1BCD-4A8B-A9E1-1C578A49DF00}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3800C66D-1BCD-4A8B-A9E1-1C578A49DF00}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3800C66D-1BCD-4A8B-A9E1-1C578A49DF00}.Release|Any CPU.Build.0 = Release|Any CPU
{5B83AC94-55AC-45CA-8C44-0D0F34E17666}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5B83AC94-55AC-45CA-8C44-0D0F34E17666}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5B83AC94-55AC-45CA-8C44-0D0F34E17666}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5B83AC94-55AC-45CA-8C44-0D0F34E17666}.Release|Any CPU.Build.0 = Release|Any CPU
{07C14020-5905-4CCC-9DAC-53507C8F28F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07C14020-5905-4CCC-9DAC-53507C8F28F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07C14020-5905-4CCC-9DAC-53507C8F28F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07C14020-5905-4CCC-9DAC-53507C8F28F8}.Release|Any CPU.Build.0 = Release|Any CPU
{05AE2E86-5464-4B1F-BE91-60FA43CE69F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{05AE2E86-5464-4B1F-BE91-60FA43CE69F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{05AE2E86-5464-4B1F-BE91-60FA43CE69F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{05AE2E86-5464-4B1F-BE91-60FA43CE69F1}.Release|Any CPU.Build.0 = Release|Any CPU
{50B7E5D7-A58E-4E36-8A5C-F7E78BB526B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{50B7E5D7-A58E-4E36-8A5C-F7E78BB526B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{50B7E5D7-A58E-4E36-8A5C-F7E78BB526B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{50B7E5D7-A58E-4E36-8A5C-F7E78BB526B0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CF09581E-BE79-49D5-8E3E-55A1240E6B73}
SolutionGuid = {85720FB6-8B83-49DA-BADD-9B6722F2E765}
EndGlobalSection
EndGlobal

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

View File

@ -1,40 +0,0 @@
namespace GiftShop
{
partial class Form1
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </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,20 +0,0 @@
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 GiftShop
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

View File

@ -1,80 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{1AF43BDD-A676-4353-A97D-8195C7C40405}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>GiftShop</RootNamespace>
<AssemblyName>GiftShop</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GiftShop
{
internal static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

View File

@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанных со сборкой.
[assembly: AssemblyTitle("GiftShop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GiftShop")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, следует установить атрибут ComVisible в TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("1af43bdd-a676-4353-a97d-8195c7c40405")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -1,71 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программным средством.
// Версия среды выполнения: 4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
// код создан повторно.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GiftShop.Properties
{
/// <summary>
/// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
/// </summary>
// Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
// класс с помощью таких средств, как ResGen или Visual Studio.
// Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
// с параметром /str или заново постройте свой VS-проект.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GiftShop.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Переопределяет свойство CurrentUICulture текущего потока для всех
/// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@ -1,30 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GiftShop.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@ -1,7 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,109 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace GiftShopBusinessLogic.BusinessLogics
{
public class ComponentLogic : IComponentLogic
{
private readonly ILogger _logger;
private readonly IComponentStorage _componentStorage;
public ComponentLogic(ILogger<ComponentLogic> logger, IComponentStorage componentStorage)
{
_logger = logger;
_componentStorage = componentStorage;
}
public List<ComponentViewModel>? ReadList(ComponentSearchModel? model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{ Id}", model?.ComponentName, model?.Id);
var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ComponentViewModel? ReadElement(ComponentSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ComponentName:{ComponentName}. Id:{ Id}", model.ComponentName, model.Id);
var element = _componentStorage.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(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ComponentBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_componentStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ComponentBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ComponentName))
{
throw new ArgumentNullException("Нет названия компонента",
nameof(model.ComponentName));
}
if (model.Cost <= 0)
{
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id: { Id} ", model.ComponentName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new ComponentSearchModel
{
ComponentName = model.ComponentName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,137 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace GiftShopBusinessLogic.BusinessLogics
{
public class GiftLogic : IGiftLogic
{
private readonly ILogger _logger;
private readonly IGiftStorage _giftStorage;
public GiftLogic(ILogger<GiftLogic> logger, IGiftStorage giftStorage)
{
_logger = logger;
_giftStorage = giftStorage;
}
public bool Create(GiftBindingModel model)
{
CheckModel(model);
if (_giftStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(GiftBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_giftStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public GiftViewModel? ReadElement(GiftSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. GiftName:{GiftName}.Id:{ Id}", model.GiftName, model.Id);
var element = _giftStorage.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<GiftViewModel>? ReadList(GiftSearchModel? model)
{
_logger.LogInformation("ReadList. GiftName:{GiftName}.Id:{ Id}", model?.GiftName, model?.Id);
var list = model == null ? _giftStorage.GetFullList() : _giftStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(GiftBindingModel model)
{
CheckModel(model);
if (_giftStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(GiftBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.GiftName))
{
throw new ArgumentNullException("Нет названия изделия", nameof(model.GiftName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Gift. GiftName:{GiftName}.Price:{ Cost}. Id: { Id}", model.GiftName, model.Price, model.Id);
var element = _giftStorage.GetElement(new GiftSearchModel
{
GiftName = model.GiftName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Изделие с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,197 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Enums;
using GiftShopDataModels.Models;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace GiftShopBusinessLogic.BusinessLogics
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IGiftStorage _giftStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IGiftStorage giftStorage, IShopLogic shopLogic, IShopStorage shopStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_giftStorage = giftStorage;
_shopLogic = shopLogic;
_shopStorage = shopStorage;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Insert operation failed. Order status incorrect.");
return false;
}
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool CheckSupply(IGiftModel gift, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. Gift count < 0.");
return false;
}
int sumCapacity = 0;
int sumCount = 0;
sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum();
sumCount = _shopStorage.GetFullList().Select(x => x.ShopGifts.Select(y => y.Value.Item2).Sum()).Sum();
int freeSpace = sumCapacity - sumCount;
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new Gift in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCapacity;
foreach (var doc in shop.ShopGifts)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id }, gift, count))
count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.MakeSupply(new() { Id = shop.Id }, gift, freeSpace))
count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
public bool StatusUpdate(OrderBindingModel model, OrderStatus status)
{
CheckModel(model);
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
}
if (element.Status != status - 1)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
if (element.Status == OrderStatus.Готов)
{
var gift = _giftStorage.GetElement(new GiftSearchModel() { Id = model.GiftId });
if (gift == null)
{
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found.");
return false;
}
if (CheckSupply(gift, model.Count) == false)
{
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error.");
return false;
}
}
model.Status = status;
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Готов);
}
public bool FinishOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выдан);
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("Order. OrderId:{Id}", model?.Id);
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;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
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));
}
_logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. EngineId: { EngineId}", model.Id, model.Sum, model.GiftId);
}
}
}

View File

@ -0,0 +1,236 @@
using Microsoft.Extensions.Logging;
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopBusinessLogic.BusinessLogics
{
public class ShopLogic: IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage ShopStorage)
{
_logger = logger;
_shopStorage = ShopStorage;
}
public bool AddGift(ShopSearchModel model, IGiftModel gift, int quantity)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (quantity <= 0)
{
throw new ArgumentException("Количество добавляемого изделия должно быть больше 0", nameof(quantity));
}
_logger.LogInformation("AddGiftInShop. ShopName:{ShopName}.Id:{Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("AddGiftInShop element not found");
return false;
}
if (element.MaxCapacity - element.ShopGifts.Select(x => x.Value.Item2).Sum() < quantity)
{
throw new ArgumentNullException("Магазин переполнен", nameof(quantity));
}
_logger.LogInformation("AddGiftInShop find. Id:{Id}", element.Id);
if (element.ShopGifts.TryGetValue(gift.Id, out var pair))
{
element.ShopGifts[gift.Id] = (gift, quantity + pair.Item2);
_logger.LogInformation("AddGiftInShop. Has been added {quantity} {gift} in {ShopName}", quantity, gift.GiftName, element.ShopName);
}
else
{
element.ShopGifts[gift.Id] = (gift, quantity);
_logger.LogInformation("AddGiftInShop. Has been added {quantity} new gift {gift} in {ShopName}", quantity, gift.GiftName, element.ShopName);
}
_shopStorage.Update(new()
{
Id = element.Id,
ShopAdress = element.ShopAdress,
ShopName = element.ShopName,
OpeningDate = element.OpeningDate,
ShopGifts = element.ShopGifts
});
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 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;
}
public bool MakeSell(IGiftModel gift, int count)
{
return _shopStorage.SellGifts(gift, count);
}
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 MakeSupply(ShopSearchModel model, IGiftModel gift, int count)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (gift == null)
throw new ArgumentNullException(nameof(gift));
if (count <= 0)
throw new ArgumentNullException("Количество должно быть положительным числом");
ShopViewModel curModel = _shopStorage.GetElement(model);
if (curModel == null)
throw new ArgumentNullException(nameof(curModel));
var countItems = curModel.ShopGifts.Select(x => x.Value.Item2).Sum();
if (curModel.MaxCapacity - countItems >= count)
{
if (curModel.ShopGifts.TryGetValue(gift.Id, out var sameDocument))
{
curModel.ShopGifts[gift.Id] = (gift, sameDocument.Item2 + count);
_logger.LogInformation("Same gift found by supply. Added {0} of {1} in {2} shop", count, gift.GiftName, curModel.ShopName);
}
else
{
curModel.ShopGifts[gift.Id] = (gift, count);
_logger.LogInformation("New gift added by supply. Added {0} of {1} in {2} shop", count, gift.GiftName, curModel.ShopName);
}
_shopStorage.Update(new()
{
Id = curModel.Id,
ShopName = curModel.ShopName,
ShopAdress = curModel.ShopAdress,
OpeningDate = curModel.OpeningDate,
ShopGifts = curModel.ShopGifts,
MaxCapacity = curModel.MaxCapacity
});
}
else
{
_logger.LogWarning("Required shop is overflowed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model, false);
if (string.IsNullOrEmpty(model.ShopName))
{
throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName));
}
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update 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.ShopAdress))
{
throw new ArgumentNullException("Нет адресса магазина", nameof(model.ShopAdress));
}
if (model.OpeningDate == null)
{
throw new ArgumentNullException("Нет даты открытия магазина", nameof(model.OpeningDate));
}
_logger.LogInformation("Shop. ShopName:{0}.ShopAddress:{1}. Id: {2}", model.ShopName, model.ShopAdress, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id && element.ShopName == model.ShopName)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GiftShopContracts\GiftShopContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
using GiftShopDataModels.Models;
namespace GiftShopContracts.BindingModels
{
public class ComponentBindingModel : IComponentModel
{
public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using GiftShopDataModels.Models;
namespace GiftShopContracts.BindingModels
{
public class GiftBindingModel : IGiftModel
{
public int Id { get; set; }
public string GiftName { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> GiftComponents { get; set; } = new();
}
}

View File

@ -0,0 +1,24 @@
using GiftShopDataModels.Enums;
using GiftShopDataModels.Models;
namespace GiftShopContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id {get; set;}
public int GiftId { get; set; }
public string GiftName { get; set; } = string.Empty;
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GiftShopDataModels.Models;
namespace GiftShopContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; } = string.Empty;
public string ShopAdress { get; set; } = string.Empty;
public DateTime OpeningDate { get; set; } = DateTime.Now;
public int MaxCapacity { get; set; }
public Dictionary<int, (IGiftModel, int)> ShopGifts { get; set; } = new();
}
}

View File

@ -0,0 +1,17 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
namespace GiftShopContracts.BusinessLogicsContracts
{
public interface IComponentLogic
{
List<ComponentViewModel>? ReadList(ComponentSearchModel? model);
ComponentViewModel? ReadElement(ComponentSearchModel model);
bool Create(ComponentBindingModel model);
bool Update(ComponentBindingModel model);
bool Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,17 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
namespace GiftShopContracts.BusinessLogicsContracts
{
public interface IGiftLogic
{
List<GiftViewModel>? ReadList(GiftSearchModel? model);
GiftViewModel? ReadElement(GiftSearchModel model);
bool Create(GiftBindingModel model);
bool Update(GiftBindingModel model);
bool Delete(GiftBindingModel model);
}
}

View File

@ -0,0 +1,19 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
namespace GiftShopContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
}
}

View File

@ -0,0 +1,24 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopContracts.SearchModels;
using GiftShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopContracts.BusinessLogicsContracts
{
public interface IShopLogic
{
List<ShopViewModel>? ReadList(ShopSearchModel? model);
ShopViewModel? ReadElement(ShopSearchModel model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool AddGift(ShopSearchModel model, IGiftModel gift, int quantity);
bool MakeSupply(ShopSearchModel model, IGiftModel gift, int count);
bool MakeSell(IGiftModel gift, int count);
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\GiftShopDataModels\GiftShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,9 @@
namespace GiftShopContracts.SearchModels
{
public class ComponentSearchModel
{
public int? Id { get; set; }
public string? ComponentName { get; set; }
}
}

View File

@ -0,0 +1,9 @@
namespace GiftShopContracts.SearchModels
{
public class GiftSearchModel
{
public int? Id { get; set; }
public string? GiftName { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace GiftShopContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? ShopName { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
namespace GiftShopContracts.StoragesContracts
{
public interface IComponentStorage
{
List<ComponentViewModel> GetFullList();
List<ComponentViewModel> GetFilteredList(ComponentSearchModel model);
ComponentViewModel? GetElement(ComponentSearchModel model);
ComponentViewModel? Insert(ComponentBindingModel model);
ComponentViewModel? Update(ComponentBindingModel model);
ComponentViewModel? Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
namespace GiftShopContracts.StoragesContracts
{
public interface IGiftStorage
{
List<GiftViewModel> GetFullList();
List<GiftViewModel> GetFilteredList(GiftSearchModel model);
GiftViewModel? GetElement(GiftSearchModel model);
GiftViewModel? Insert(GiftBindingModel model);
GiftViewModel? Update(GiftBindingModel model);
GiftViewModel? Delete(GiftBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
namespace GiftShopContracts.StoragesContracts
{
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopContracts.StoragesContracts
{
public interface IShopStorage
{
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? GetElement(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
public bool SellGifts(IGiftModel model, int count);
}
}

View File

@ -0,0 +1,17 @@
using GiftShopDataModels.Models;
using System.ComponentModel;
namespace GiftShopContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
[DisplayName("Название компонента")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using GiftShopDataModels.Models;
using System.ComponentModel;
namespace GiftShopContracts.ViewModels
{
public class GiftViewModel : IGiftModel
{
public int Id { get; set; }
[DisplayName("Название изделия")]
public string GiftName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> GiftComponents { get; set; } = new();
}
}

View File

@ -0,0 +1,38 @@
using GiftShopDataModels.Enums;
using GiftShopDataModels.Models;
using System.ComponentModel;
namespace GiftShopContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
public int Id { get; set; }
public int GiftId { get; set; }
[DisplayName("Изделие")]
public string GiftName { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GiftShopDataModels.Models;
namespace GiftShopContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
public Dictionary<int, (IGiftModel, int)> ShopGifts { get; set; } = new();
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string ShopAdress { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime OpeningDate { get; set; } = DateTime.Now;
[DisplayName("Вместимость")]
public int MaxCapacity { get; set; }
}
}

View File

@ -0,0 +1,15 @@
namespace GiftShopDataModels.Enums
{
public enum OrderStatus
{
Неизвестен = -1,
Принят = 0,
Выполняется = 1,
Готов = 2,
Выдан = 3
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,7 @@
namespace GiftShopDataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -0,0 +1,9 @@
namespace GiftShopDataModels.Models
{
public interface IComponentModel : IId
{
string ComponentName { get; }
double Cost { get; }
}
}

View File

@ -0,0 +1,11 @@
namespace GiftShopDataModels.Models
{
public interface IGiftModel : IId
{
string GiftName { get; }
double Price { get; }
Dictionary<int, (IComponentModel, int)> GiftComponents { get; }
}
}

View File

@ -0,0 +1,19 @@
using GiftShopDataModels.Enums;
namespace GiftShopDataModels.Models
{
public interface IOrderModel : IId
{
int GiftId { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopDataModels.Models
{
public interface IShopModel : IId
{
public int Id { get; set; }
public string ShopName { get; }
public string ShopAdress { get; }
DateTime OpeningDate { get; }
Dictionary<int, (IGiftModel, int)> ShopGifts { get; }
int MaxCapacity { get; }
}
}

View File

@ -0,0 +1,29 @@
using GiftShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace GiftShopDatabaseImplement
{
public class GiftShopDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-Arkad1y;Initial Catalog=GiftShopDataBaseHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Gift> Gifts { set; get; }
public virtual DbSet<GiftComponent> GiftComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopGift> ShopGifts { set; get;}
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GiftShopContracts\GiftShopContracts.csproj" />
<ProjectReference Include="..\GiftShopDataModels\GiftShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,85 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDatabaseImplement.Models;
namespace GiftShopDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var context = new GiftShopDatabase();
return context.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new GiftShopDatabase();
return context.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
using var context = new GiftShopDatabase();
return context.Components
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new GiftShopDatabase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new GiftShopDatabase();
var component = context.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new GiftShopDatabase();
var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,107 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace GiftShopDatabaseImplement.Implements
{
public class GiftStorage : IGiftStorage
{
public List<GiftViewModel> GetFullList()
{
using var context = new GiftShopDatabase();
return context.Gifts
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<GiftViewModel> GetFilteredList(GiftSearchModel model)
{
if (string.IsNullOrEmpty(model.GiftName))
{
return new();
}
using var context = new GiftShopDatabase();
return context.Gifts
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.GiftName.Contains(model.GiftName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public GiftViewModel? GetElement(GiftSearchModel model)
{
if (string.IsNullOrEmpty(model.GiftName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new GiftShopDatabase();
return context.Gifts
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.GiftName) &&
x.GiftName == model.GiftName) || (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public GiftViewModel? Insert(GiftBindingModel model)
{
using var context = new GiftShopDatabase();
var newGift = Gift.Create(context, model);
if (newGift == null)
{
return null;
}
context.Gifts.Add(newGift);
context.SaveChanges();
return newGift.GetViewModel;
}
public GiftViewModel? Update(GiftBindingModel model)
{
using var context = new GiftShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var gift = context.Gifts.FirstOrDefault(rec => rec.Id == model.Id);
if (gift == null)
{
return null;
}
gift.Update(model);
context.SaveChanges();
gift.UpdateComponents(context, model);
transaction.Commit();
return gift.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public GiftViewModel? Delete(GiftBindingModel model)
{
using var context = new GiftShopDatabase();
var element = context.Gifts
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Gifts.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,76 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDatabaseImplement.Models;
namespace GiftShopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new GiftShopDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new GiftShopDatabase();
return context.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new GiftShopDatabase();
return context.Orders.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new GiftShopDatabase();
return context.Orders.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new GiftShopDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new GiftShopDatabase();
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
}
}

View File

@ -0,0 +1,148 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using GiftShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace GiftShopDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new GiftShopDatabase();
var element = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
using var context = new GiftShopDatabase();
return context.Shops
.Include(x => x.Gifts)
.ThenInclude(x => x.Gift)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
using var context = new GiftShopDatabase();
return context.Shops
.Include(x => x.Gifts)
.ThenInclude(x => x.Gift)
.Select(x => x.GetViewModel)
.Where(x => x.ShopName.Contains(model.ShopName ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
using var context = new GiftShopDatabase();
return context.Shops
.Include(x => x.Gifts)
.ThenInclude(x => x.Gift)
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new GiftShopDatabase();
try
{
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
if (context.Shops.Any(x => x.ShopName == newShop.ShopName))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
context.Shops.Add(newShop);
context.SaveChanges();
return newShop.GetViewModel;
}
catch
{
throw;
}
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new GiftShopDatabase();
var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
try
{
if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id)))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
shop.Update(model);
shop.UpdateGifts(context, model);
context.SaveChanges();
return shop.GetViewModel;
}
catch
{
throw;
}
}
public bool SellGifts(IGiftModel model, int count)
{
if (model == null)
return false;
using var context = new GiftShopDatabase();
using var transaction = context.Database.BeginTransaction();
List<ShopGift> lst = new List<ShopGift>();
foreach(var el in context.ShopGifts.Where(x => x.GiftId == model.Id))
{
int dif = count;
if (el.Count < dif)
dif = el.Count;
el.Count -= dif;
count -= dif;
if(el.Count == 0)
{
lst.Add(el);
}
if (count == 0)
break;
}
if (count > 0)
{
transaction.Rollback();
return false;
}
foreach(var el in lst)
{
context.ShopGifts.Remove(el);
}
context.SaveChanges();
transaction.Commit();
return true;
}
}
}

View File

@ -0,0 +1,252 @@
// <auto-generated />
using System;
using GiftShopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace GiftShopDatabaseImplement.Migrations
{
[DbContext(typeof(GiftShopDatabase))]
[Migration("20240511053931_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("GiftName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Gifts");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("GiftId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("GiftId");
b.ToTable("GiftComponents");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("GiftId")
.HasColumnType("int");
b.Property<string>("GiftName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("GiftId");
b.ToTable("Orders");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("MaxCapacity")
.HasColumnType("int");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.Property<string>("ShopAdress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.ShopGift", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("GiftId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("GiftId");
b.HasIndex("ShopId");
b.ToTable("ShopGifts");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b =>
{
b.HasOne("GiftShopDatabaseImplement.Models.Component", "Component")
.WithMany("GiftComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift")
.WithMany("Components")
.HasForeignKey("GiftId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Gift");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift")
.WithMany("Orders")
.HasForeignKey("GiftId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Gift");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.ShopGift", b =>
{
b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift")
.WithMany()
.HasForeignKey("GiftId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GiftShopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Gifts")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Gift");
b.Navigation("Shop");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b =>
{
b.Navigation("GiftComponents");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Gifts");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,185 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace GiftShopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ComponentName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Gifts",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
GiftName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Gifts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShopName = table.Column<string>(type: "nvarchar(max)", nullable: false),
ShopAdress = table.Column<string>(type: "nvarchar(max)", nullable: false),
OpeningDate = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCapacity = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "GiftComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
GiftId = table.Column<int>(type: "int", nullable: false),
ComponentId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_GiftComponents", x => x.Id);
table.ForeignKey(
name: "FK_GiftComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_GiftComponents_Gifts_GiftId",
column: x => x.GiftId,
principalTable: "Gifts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
GiftId = table.Column<int>(type: "int", nullable: false),
GiftName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Gifts_GiftId",
column: x => x.GiftId,
principalTable: "Gifts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ShopGifts",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
GiftId = table.Column<int>(type: "int", nullable: false),
ShopId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopGifts", x => x.Id);
table.ForeignKey(
name: "FK_ShopGifts_Gifts_GiftId",
column: x => x.GiftId,
principalTable: "Gifts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopGifts_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_GiftComponents_ComponentId",
table: "GiftComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_GiftComponents_GiftId",
table: "GiftComponents",
column: "GiftId");
migrationBuilder.CreateIndex(
name: "IX_Orders_GiftId",
table: "Orders",
column: "GiftId");
migrationBuilder.CreateIndex(
name: "IX_ShopGifts_GiftId",
table: "ShopGifts",
column: "GiftId");
migrationBuilder.CreateIndex(
name: "IX_ShopGifts_ShopId",
table: "ShopGifts",
column: "ShopId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "GiftComponents");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ShopGifts");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Gifts");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -0,0 +1,249 @@
// <auto-generated />
using System;
using GiftShopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace GiftShopDatabaseImplement.Migrations
{
[DbContext(typeof(GiftShopDatabase))]
partial class GiftShopDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("GiftName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Gifts");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("GiftId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("GiftId");
b.ToTable("GiftComponents");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("GiftId")
.HasColumnType("int");
b.Property<string>("GiftName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("GiftId");
b.ToTable("Orders");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("MaxCapacity")
.HasColumnType("int");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.Property<string>("ShopAdress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.ShopGift", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("GiftId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("GiftId");
b.HasIndex("ShopId");
b.ToTable("ShopGifts");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.GiftComponent", b =>
{
b.HasOne("GiftShopDatabaseImplement.Models.Component", "Component")
.WithMany("GiftComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift")
.WithMany("Components")
.HasForeignKey("GiftId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Gift");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift")
.WithMany("Orders")
.HasForeignKey("GiftId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Gift");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.ShopGift", b =>
{
b.HasOne("GiftShopDatabaseImplement.Models.Gift", "Gift")
.WithMany()
.HasForeignKey("GiftId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GiftShopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Gifts")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Gift");
b.Navigation("Shop");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Component", b =>
{
b.Navigation("GiftComponents");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Gift", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Gifts");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,63 @@
using GiftShopDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using GiftShopContracts.ViewModels;
using GiftShopContracts.BindingModels;
namespace GiftShopDatabaseImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
[Required]
public string ComponentName { get; private set; } = string.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("ComponentId")]
public virtual List<GiftComponent> GiftComponents { get; set; } = new();
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component Create(ComponentViewModel model)
{
return new Component
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,99 @@
using GiftShopDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
namespace GiftShopDatabaseImplement.Models
{
public class Gift : IGiftModel
{
public int Id { get; set; }
[Required]
public string GiftName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _giftComponents = null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> GiftComponents
{
get
{
if (_giftComponents == null)
{
_giftComponents = Components.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _giftComponents;
}
}
[ForeignKey("GiftId")]
public virtual List<GiftComponent> Components { get; set; } = new();
[ForeignKey("GiftId")]
public virtual List<Order> Orders { get; set; } = new();
public static Gift Create(GiftShopDatabase context, GiftBindingModel model)
{
return new Gift()
{
Id = model.Id,
GiftName = model.GiftName,
Price = model.Price,
Components = model.GiftComponents.Select(x => new GiftComponent
{
Component = context.Components.First(y => y.Id == x.Key), Count = x.Value.Item2
}).ToList()
};
}
public void Update(GiftBindingModel model)
{
GiftName = model.GiftName;
Price = model.Price;
}
public GiftViewModel GetViewModel => new()
{
Id = Id,
GiftName = GiftName,
Price = Price,
GiftComponents = GiftComponents
};
public void UpdateComponents(GiftShopDatabase context, GiftBindingModel model)
{
var giftComponents = context.GiftComponents.Where(rec => rec.GiftId == model.Id).ToList();
if (giftComponents != null && giftComponents.Count > 0)
{ // удалили те, которых нет в модели
context.GiftComponents.RemoveRange(giftComponents.Where
(rec => !model.GiftComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in giftComponents)
{
updateComponent.Count = model.GiftComponents[updateComponent.ComponentId].Item2;
model.GiftComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var gift = context.Gifts.First(x => x.Id == Id);
foreach (var pc in model.GiftComponents)
{
context.GiftComponents.Add(new GiftComponent
{
Gift = gift,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_giftComponents = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace GiftShopDatabaseImplement.Models
{
public class GiftComponent
{
public int Id { get; set; }
[Required]
public int GiftId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();
public virtual Gift Gift { get; set; } = new();
}
}

View File

@ -0,0 +1,75 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Enums;
using GiftShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace GiftShopDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int GiftId { get; private set; }
public string GiftName { get; private set; } = string.Empty;
[Required]
public int Count { get; private set; }
[Required]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required]
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public virtual Gift Gift { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
GiftId = model.GiftId,
GiftName = model.GiftName,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
GiftId = GiftId,
GiftName = GiftName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}

View File

@ -0,0 +1,115 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string ShopName { get; private set; }
[Required]
public string ShopAdress { get; private set; }
[Required]
public DateTime OpeningDate { get; private set; }
[Required]
public int MaxCapacity { get; private set; }
private Dictionary<int, (IGiftModel, int)>? _shopGifts =
null;
[NotMapped]
public Dictionary<int, (IGiftModel, int)> ShopGifts
{
get
{
if (_shopGifts == null)
{
_shopGifts = Gifts
.ToDictionary(x => x.GiftId, x =>
(x.Gift as IGiftModel, x.Count));
}
return _shopGifts;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopGift> Gifts { get; set; } = new();
public static Shop? Create(GiftShopDatabase context, ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
ShopAdress = model.ShopAdress,
OpeningDate = model.OpeningDate,
MaxCapacity = model.MaxCapacity,
Gifts = model.ShopGifts.Select(x => new ShopGift
{
Gift = context.Gifts.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
ShopAdress = model.ShopAdress;
OpeningDate = model.OpeningDate;
MaxCapacity = model.MaxCapacity;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
ShopAdress = ShopAdress,
OpeningDate = OpeningDate,
ShopGifts = ShopGifts,
MaxCapacity = MaxCapacity
};
public void UpdateGifts(GiftShopDatabase context, ShopBindingModel model)
{
var shopGifts = context.ShopGifts.Where(rec =>
rec.ShopId == model.Id).ToList();
if (shopGifts != null && shopGifts.Count > 0)
{
context.ShopGifts.RemoveRange(shopGifts.Where(rec => !model.ShopGifts.ContainsKey(rec.GiftId)));
context.SaveChanges();
foreach (var updateGift in shopGifts)
{
updateGift.Count =
model.ShopGifts[updateGift.GiftId].Item2;
model.ShopGifts.Remove(updateGift.GiftId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var pc in model.ShopGifts)
{
context.ShopGifts.Add(new ShopGift
{
Shop = shop,
Gift = context.Gifts.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_shopGifts = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopDatabaseImplement.Models
{
public class ShopGift
{
public int Id { get; set; }
[Required]
public int GiftId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Gift Gift { get; set; } = new();
}
}

View File

@ -0,0 +1,68 @@
using GiftShopFileImplement.Models;
using System.Xml.Linq;
namespace GiftShopFileImplement
{
internal class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string GiftFileName = "Gift.xml";
private readonly string ShopFileName = "Shops.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Gift> Gifts { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveGifts() => SaveData(Gifts, GiftFileName, "Gifts", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, OrderFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Gifts = LoadData(GiftFileName, "Gift", x => Gift.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename,
string xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\GiftShopContracts\GiftShopContracts.csproj" />
<ProjectReference Include="..\GiftShopDataModels\GiftShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,86 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopFileImplement.Models;
namespace GiftShopFileImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataFileSingleton source;
public ComponentStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
return source.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
return source.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
return source.Components
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName)
&& x.ComponentName == model.ComponentName) || (model.Id.HasValue
&& x.Id == model.Id)) ?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
source.Components.Add(newComponent);
source.SaveComponents();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
var component = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveComponents();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
var element = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Components.Remove(element);
source.SaveComponents();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,92 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopFileImplement.Models;
namespace GiftShopFileImplement.Implements
{
public class GiftStorage : IGiftStorage
{
private readonly DataFileSingleton source;
public GiftStorage()
{
source = DataFileSingleton.GetInstance();
}
public GiftViewModel? Delete(GiftBindingModel model)
{
var element = source.Gifts.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Gifts.Remove(element);
source.SaveGifts();
return element.GetViewModel;
}
return null;
}
public GiftViewModel? GetElement(GiftSearchModel model)
{
if (string.IsNullOrEmpty(model.GiftName) && !model.Id.HasValue)
{
return null;
}
return source.Gifts.FirstOrDefault(x => (!string.IsNullOrEmpty(model.GiftName) && x.GiftName == model.GiftName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<GiftViewModel> GetFilteredList(GiftSearchModel model)
{
if (string.IsNullOrEmpty(model.GiftName))
{
return new();
}
return source.Gifts
.Where(x => x.GiftName
.Contains(model.GiftName))
.Select(x => x.GetViewModel).ToList();
}
public List<GiftViewModel> GetFullList()
{
return source.Gifts.Select(x => x.GetViewModel).ToList();
}
public GiftViewModel? Insert(GiftBindingModel model)
{
model.Id = source.Gifts.Count > 0 ? source.Gifts.Max(x => x.Id) + 1 : 1;
var newGift = Gift.Create(model);
if (newGift == null)
{
return null;
}
source.Gifts.Add(newGift);
source.SaveGifts();
return newGift.GetViewModel;
}
public GiftViewModel? Update(GiftBindingModel model)
{
var gift = source.Gifts.FirstOrDefault(x => x.Id == model.Id);
if (gift == null)
{
return null;
}
gift.Update(model);
source.SaveGifts();
return gift.GetViewModel;
}
}
}

View File

@ -0,0 +1,89 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopFileImplement.Models;
namespace GiftShopFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var element = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Orders.Remove(element);
source.SaveOrders();
return element.GetViewModel;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return order.GetViewModel;
}
}
}

View File

@ -0,0 +1,128 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using GiftShopFileImplement;
using GiftShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton _source;
public ShopStorage()
{
_source = DataFileSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
return _source.Shops.Select(x => x.GetViewModel).ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return _source.Shops.Where(x => x.ShopName.Contains(model.ShopName)).Select(x => x.GetViewModel).ToList(); ;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return _source.Shops.FirstOrDefault(x =>(!string.IsNullOrEmpty(model.ShopName) && x.ShopName ==model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x =>x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
_source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var component = _source.Shops.FirstOrDefault(x => x.Id ==model.Id);
if (component == null)
{
return null;
}
component.Update(model);
_source.SaveShops();
return component.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = _source.Shops.FirstOrDefault(x => x.Id ==
model.Id);
if (element != null)
{
_source.Shops.Remove(element);
_source.SaveShops();
return element.GetViewModel;
}
return null;
}
public bool CheckAvailability(int giftId, int count)
{
int minus = _source.Shops.Select(x => x.ShopGifts.Select(y => (y.Value.Item1.Id == giftId ? y.Value.Item2 : 0)).Sum()).Sum();
count -= minus;
return count <= 0;
}
public bool SellGifts(IGiftModel model, int count)
{
var gift = _source.Gifts.FirstOrDefault(x => x.Id == model.Id);
if (gift == null || !CheckAvailability(gift.Id, count))
{
return false;
}
for (int i = 0; i < _source.Shops.Count; i++)
{
var shop = _source.Shops[i];
var gifts = shop.ShopGifts;
foreach (var gifty in gifts.Where(x => x.Value.Item1.Id == gift.Id))
{
var min = Math.Min(gifty.Value.Item2, count);
gifts[gifty.Value.Item1.Id] = (gifty.Value.Item1, gifty.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
ShopAdress = shop.ShopAdress,
OpeningDate = shop.OpeningDate,
MaxCapacity = shop.MaxCapacity,
ShopGifts = gifts
});
}
_source.SaveShops();
return true;
}
}
}

View File

@ -0,0 +1,66 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using System.Xml.Linq;
namespace GiftShopFileImplement.Models
{
internal class Component : IComponentModel
{
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Component()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComponentName = element.Element("ComponentName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
public XElement GetXElement => new("Component",
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -0,0 +1,95 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using System.Xml.Linq;
namespace GiftShopFileImplement.Models
{
internal class Gift : IGiftModel
{
public int Id { get; private set; }
public string GiftName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _giftComponents = null;
public Dictionary<int, (IComponentModel, int)> GiftComponents
{
get
{
if (_giftComponents == null)
{
var source = DataFileSingleton.GetInstance();
_giftComponents = Components.ToDictionary(x => x.Key,
y => ((source.Components.FirstOrDefault(z => z.Id == y.Key)
as IComponentModel)!, y.Value));
}
return _giftComponents;
}
}
public static Gift? Create(GiftBindingModel? model)
{
if (model == null)
{
return null;
}
return new Gift()
{
Id = model.Id,
GiftName = model.GiftName,
Price = model.Price,
Components = model.GiftComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Gift? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Gift()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
GiftName = element.Element("GiftName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("GiftComponents")!.Elements("GiftComponent").ToDictionary
(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(GiftBindingModel? model)
{
if (model == null)
{
return;
}
GiftName = model.GiftName;
Price = model.Price;
Components = model.GiftComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_giftComponents = null;
}
public GiftViewModel GetViewModel => new()
{
Id = Id,
GiftName = GiftName,
Price = Price,
GiftComponents = GiftComponents
};
public XElement GetXElement => new("Gift",
new XAttribute("Id", Id),
new XElement("GiftName", GiftName),
new XElement("Price", Price.ToString()),
new XElement("GiftComponents", Components.Select(x => new XElement("GiftComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -0,0 +1,99 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Enums;
using GiftShopDataModels.Models;
using System.Xml.Linq;
namespace GiftShopFileImplement.Models
{
internal class Order : IOrderModel
{
public int GiftId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
GiftId = model.GiftId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public static Order? Create(XElement element)
{
if (element == null)
{
return null;
}
var order = new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
GiftId = Convert.ToInt32(element.Element("GiftId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null)
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl;
return order;
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
GiftId = model.GiftId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
GiftId = GiftId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("GiftId", GiftId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString()));
}
}

View File

@ -0,0 +1,104 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using System.Xml.Linq;
namespace GiftShopFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
public string ShopName { get; private set; }
public string ShopAdress { get; private set; }
public DateTime OpeningDate { get; private set; }
public Dictionary<int, int> Gifts { get; private set; } = new();
private Dictionary<int, (IGiftModel, int)>? _shopGifts = null;
public Dictionary<int, (IGiftModel, int)> ShopGifts
{
get
{
if (_shopGifts == null)
{
var source = DataFileSingleton.GetInstance();
_shopGifts = Gifts.ToDictionary(x => x.Key, y =>
((source.Gifts.FirstOrDefault(z => z.Id == y.Key) as IGiftModel)!,
y.Value));
}
return _shopGifts;
}
}
public int MaxCapacity { get; private set; }
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
ShopAdress = model.ShopAdress,
OpeningDate = model.OpeningDate,
MaxCapacity = model.MaxCapacity,
Gifts = model.ShopGifts.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
ShopAdress = element.Element("ShopAdress")!.Value,
MaxCapacity = Convert.ToInt32(element.Element("MaxCapacity")!.Value),
OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value),
Gifts = element.Element("ShopGifts")!.Elements("ShopGifts").ToDictionary(x =>Convert.ToInt32(x.Element("Key")?.Value), x =>Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
ShopAdress = model.ShopAdress;
OpeningDate = model.OpeningDate;
MaxCapacity = model.MaxCapacity;
if (model.ShopGifts.Count > 0)
{
Gifts = model.ShopGifts.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopGifts = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
ShopAdress = ShopAdress,
OpeningDate = OpeningDate,
MaxCapacity = MaxCapacity,
ShopGifts = ShopGifts
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("ShopAdress", ShopAdress),
new XElement("OpeningDate", OpeningDate),
new XElement("MaxCapacity", MaxCapacity),
new XElement("Gifts", Gifts.Select(x => new XElement("Gifts",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}

View File

@ -0,0 +1,29 @@
using GiftShopListImplement.Models;
namespace GiftShopListImplement
{
internal class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Gift> Gifts { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Gifts = new List<Gift>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\GiftShopContracts\GiftShopContracts.csproj" />
<ProjectReference Include="..\GiftShopDataModels\GiftShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,102 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopListImplement.Models;
namespace GiftShopListImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataListSingleton _source;
public ComponentStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
var result = new List<ComponentViewModel>();
foreach (var component in _source.Components)
{
result.Add(component.GetViewModel);
}
return result;
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
var result = new List<ComponentViewModel>();
if (string.IsNullOrEmpty(model.ComponentName))
{
return result;
}
foreach (var component in _source.Components)
{
if (component.ComponentName.Contains(model.ComponentName))
{
result.Add(component.GetViewModel);
}
}
return result;
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
foreach (var component in _source.Components)
{
if ((!string.IsNullOrEmpty(model.ComponentName) &&
component.ComponentName == model.ComponentName) ||
(model.Id.HasValue && component.Id == model.Id))
{
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = 1;
foreach (var component in _source.Components)
{
if (model.Id <= component.Id)
{
model.Id = component.Id + 1;
}
}
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
_source.Components.Add(newComponent);
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
foreach (var component in _source.Components)
{
if (component.Id == model.Id)
{
component.Update(model);
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
for (int i = 0; i < _source.Components.Count; ++i)
{
if (_source.Components[i].Id == model.Id)
{
var element = _source.Components[i];
_source.Components.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,121 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopListImplement.Models;
namespace GiftShopListImplement.Implements
{
public class GiftStorage : IGiftStorage
{
private readonly DataListSingleton _source;
public GiftStorage()
{
_source = DataListSingleton.GetInstance();
}
public GiftViewModel? Delete(GiftBindingModel model)
{
for (int i = 0; i < _source.Gifts.Count; ++i)
{
if (_source.Gifts[i].Id == model.Id)
{
var element = _source.Gifts[i];
_source.Gifts.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public GiftViewModel? GetElement(GiftSearchModel model)
{
if (string.IsNullOrEmpty(model.GiftName) && !model.Id.HasValue)
{
return null;
}
foreach (var package in _source.Gifts)
{
if ((!string.IsNullOrEmpty(model.GiftName) && package.GiftName == model.GiftName) || (model.Id.HasValue && package.Id == model.Id))
{
return package.GetViewModel;
}
}
return null;
}
public List<GiftViewModel> GetFilteredList(GiftSearchModel model)
{
var result = new List<GiftViewModel>();
if (string.IsNullOrEmpty(model.GiftName))
{
return result;
}
foreach (var package in _source.Gifts)
{
if (package.GiftName.Contains(model.GiftName))
{
result.Add(package.GetViewModel);
}
}
return result;
}
public List<GiftViewModel> GetFullList()
{
var result = new List<GiftViewModel>();
foreach (var package in _source.Gifts)
{
result.Add(package.GetViewModel);
}
return result;
}
public GiftViewModel? Insert(GiftBindingModel model)
{
model.Id = 1;
foreach (var package in _source.Gifts)
{
if (model.Id <= package.Id)
{
model.Id = package.Id + 1;
}
}
var newGift = Gift.Create(model);
if (newGift == null)
{
return null;
}
_source.Gifts.Add(newGift);
return newGift.GetViewModel;
}
public GiftViewModel? Update(GiftBindingModel model)
{
foreach (var package in _source.Gifts)
{
if (package.Id == model.Id)
{
package.Update(model);
return package.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,119 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopListImplement.Models;
namespace GiftShopListImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
{
if (_source.Orders[i].Id == model.Id)
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return order.GetViewModel;
}
}
return null;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
result.Add(order.GetViewModel);
}
}
return result;
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(order.GetViewModel);
}
return result;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = 1;
foreach (var order in _source.Orders)
{
if (model.Id <= order.Id)
{
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
order.Update(model);
return order.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,170 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopListImplement.Models;
using GiftShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace GiftShopListImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) || (model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.ShopName))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.ShopName.Contains(model.ShopName))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
public bool CheckAvailability(int giftId, int count)
{
int minus = _source.Shops.Select(x => x.ShopGifts.Select(y => (y.Value.Item1.Id == giftId ? y.Value.Item2 : 0)).Sum()).Sum();
count -= minus;
return count <= 0;
}
public bool SellGifts(IGiftModel model, int count)
{
var gift = _source.Gifts.FirstOrDefault(x => x.Id == model.Id);
if (gift == null || !CheckAvailability(gift.Id, count))
{
return false;
}
for (int i = 0; i < _source.Shops.Count; i++)
{
var shop = _source.Shops[i];
var gifts = shop.ShopGifts;
foreach (var shopgift in gifts.Where(x => x.Value.Item1.Id == gift.Id))
{
var min = Math.Min(shopgift.Value.Item2, count);
gifts[shopgift.Value.Item1.Id] = (shopgift.Value.Item1, shopgift.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
ShopAdress = shop.ShopAdress,
OpeningDate = shop.OpeningDate,
MaxCapacity = shop.MaxCapacity,
ShopGifts = gifts
});
}
return true;
}
}
}

View File

@ -0,0 +1,41 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
namespace GiftShopListImplement.Models
{
internal class Component : IComponentModel
{
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,51 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
namespace GiftShopListImplement.Models
{
internal class Gift : IGiftModel
{
public int Id { get; private set; }
public string GiftName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, (IComponentModel, int)> GiftComponents { get; private set; } = new Dictionary<int, (IComponentModel, int)>();
public static Gift? Create(GiftBindingModel? model)
{
if (model == null)
{
return null;
}
return new Gift()
{
Id = model.Id,
GiftName = model.GiftName,
Price = model.Price,
GiftComponents = model.GiftComponents
};
}
public void Update(GiftBindingModel? model)
{
if (model == null)
{
return;
}
GiftName = model.GiftName;
Price = model.Price;
GiftComponents = model.GiftComponents;
}
public GiftViewModel GetViewModel => new()
{
Id = Id,
GiftName = GiftName,
Price = Price,
GiftComponents = GiftComponents
};
}
}

View File

@ -0,0 +1,67 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Enums;
using GiftShopDataModels.Models;
namespace GiftShopListImplement.Models
{
internal class Order : IOrderModel
{
public int GiftId { get; private set; }
public string GiftName { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
GiftId = model.GiftId,
GiftName = model.GiftName,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
GiftId = GiftId,
GiftName = GiftName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
}

View File

@ -0,0 +1,64 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GiftShopListImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
public string ShopName { get; private set; } = string.Empty;
public string ShopAdress { get; private set; } = string.Empty;
public DateTime OpeningDate { get; private set; }
public int MaxCapacity { get; private set; }
public Dictionary<int, (IGiftModel, int)> ShopGifts { get; private set; } = new();
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
ShopAdress = model.ShopAdress,
OpeningDate = model.OpeningDate,
MaxCapacity = model.MaxCapacity,
ShopGifts = new()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
ShopAdress = model.ShopAdress;
OpeningDate = model.OpeningDate;
MaxCapacity = model.MaxCapacity;
ShopGifts = model.ShopGifts;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
ShopAdress = ShopAdress,
OpeningDate = OpeningDate,
MaxCapacity = MaxCapacity,
ShopGifts = ShopGifts
};
}
}

View File

@ -0,0 +1,117 @@
namespace GiftShopView
{
partial class FormComponent
{
/// <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();
labelName = new Label();
labelCost = new Label();
textBoxName = new TextBox();
textBoxCost = new TextBox();
SuspendLayout();
//
// buttonSave
//
buttonSave.Location = new Point(140, 130);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(119, 45);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(287, 130);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(119, 45);
buttonCancel.TabIndex = 1;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(61, 25);
labelName.Name = "labelName";
labelName.Size = new Size(80, 20);
labelName.TabIndex = 2;
labelName.Text = "Название:";
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Location = new Point(61, 83);
labelCost.Name = "labelCost";
labelCost.Size = new Size(86, 20);
labelCost.TabIndex = 3;
labelCost.Text = "Стоимость:";
//
// textBoxName
//
textBoxName.Location = new Point(186, 22);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(220, 27);
textBoxName.TabIndex = 4;
//
// textBoxCost
//
textBoxCost.Location = new Point(186, 80);
textBoxCost.Name = "textBoxCost";
textBoxCost.Size = new Size(220, 27);
textBoxCost.TabIndex = 5;
//
// FormComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(483, 205);
Controls.Add(textBoxCost);
Controls.Add(textBoxName);
Controls.Add(labelCost);
Controls.Add(labelName);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormComponent";
Text = "Компонент";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private Label labelName;
private Label labelCost;
private TextBox textBoxName;
private TextBox textBoxCost;
}
}

View File

@ -0,0 +1,93 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
public partial class FormComponent : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormComponent(ILogger<FormComponent> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormComponent_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение компонента");
var view = _logic.ReadElement(new ComponentSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ComponentName;
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 ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = 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 GiftShopView
{
partial class FormComponents
{
/// <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();
buttonAdd = new Button();
buttonUpd = new Button();
buttonDel = new Button();
buttonRef = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(407, 456);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(457, 63);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(165, 51);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(457, 153);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(165, 51);
buttonUpd.TabIndex = 2;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonDel
//
buttonDel.Location = new Point(457, 245);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(165, 51);
buttonDel.TabIndex = 3;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonRef
//
buttonRef.Location = new Point(457, 336);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(165, 51);
buttonRef.TabIndex = 4;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// FormComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(660, 489);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormComponents";
Text = "Компоненты";
Load += FormComponents_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,114 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
public partial class FormComponents : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
public FormComponents(ILogger<FormComponents> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormComponents_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["ComponentName"].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(FormComponent));
if (service is FormComponent 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(FormComponent));
if (service is FormComponent 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 ComponentBindingModel
{
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,145 @@
namespace GiftShopView
{
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()
{
labelGift = new Label();
labelCount = new Label();
labelSum = new Label();
comboBoxGift = new ComboBox();
textBoxCount = new TextBox();
textBoxSum = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelGift
//
labelGift.AutoSize = true;
labelGift.Location = new Point(34, 44);
labelGift.Name = "labelGift";
labelGift.Size = new Size(71, 20);
labelGift.TabIndex = 0;
labelGift.Text = "Изделие:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(34, 112);
labelCount.Name = "labelCount";
labelCount.Size = new Size(93, 20);
labelCount.TabIndex = 1;
labelCount.Text = "Количество:";
//
// labelSum
//
labelSum.AutoSize = true;
labelSum.Location = new Point(34, 171);
labelSum.Name = "labelSum";
labelSum.Size = new Size(58, 20);
labelSum.TabIndex = 2;
labelSum.Text = "Сумма:";
//
// comboBoxGift
//
comboBoxGift.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxGift.FormattingEnabled = true;
comboBoxGift.Location = new Point(141, 41);
comboBoxGift.Name = "comboBoxGift";
comboBoxGift.Size = new Size(369, 28);
comboBoxGift.TabIndex = 3;
comboBoxGift.SelectedIndexChanged += ComboBoxGift_SelectedIndexChanged;
//
// textBoxCount
//
textBoxCount.Location = new Point(141, 109);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(369, 27);
textBoxCount.TabIndex = 4;
textBoxCount.TextChanged += TextBoxCount_TextChanged;
//
// textBoxSum
//
textBoxSum.Location = new Point(141, 171);
textBoxSum.Name = "textBoxSum";
textBoxSum.ReadOnly = true;
textBoxSum.Size = new Size(369, 27);
textBoxSum.TabIndex = 5;
//
// buttonSave
//
buttonSave.Location = new Point(197, 245);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(144, 45);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(384, 245);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(126, 45);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormCreateOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(539, 308);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxSum);
Controls.Add(textBoxCount);
Controls.Add(comboBoxGift);
Controls.Add(labelSum);
Controls.Add(labelCount);
Controls.Add(labelGift);
Name = "FormCreateOrder";
Text = "Заказ";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelGift;
private Label labelCount;
private Label labelSum;
private ComboBox comboBoxGift;
private TextBox textBoxCount;
private TextBox textBoxSum;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,127 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IGiftLogic _logicP;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IGiftLogic logicP, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка изделий для заказа");
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка изделий для заказа");
try
{
var list = _logicP.ReadList(null);
if (list != null)
{
comboBoxGift.DisplayMember = "GiftName";
comboBoxGift.ValueMember = "ID";
comboBoxGift.DataSource = list;
comboBoxGift.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CalcSum()
{
if (comboBoxGift.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
{
try
{
int id = Convert.ToInt32(comboBoxGift.SelectedValue);
var product = _logicP.ReadElement(new GiftSearchModel
{
Id = id
});
int count = Convert.ToInt32(textBoxCount.Text);
textBoxSum.Text = Math.Round(count * (product?.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 ComboBoxGift_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 (comboBoxGift.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
GiftId = Convert.ToInt32(comboBoxGift.SelectedValue),
GiftName = comboBoxGift.Text,
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>

238
GiftShop/GiftShopView/FormGift.Designer.cs generated Normal file
View File

@ -0,0 +1,238 @@
namespace GiftShopView
{
partial class FormGift
{
/// <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()
{
labelName = new Label();
labelPrice = new Label();
textBoxName = new TextBox();
textBoxPrice = new TextBox();
groupBoxComponents = new GroupBox();
dataGridView = new DataGridView();
ColumnId = new DataGridViewTextBoxColumn();
ColumnName = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
buttonSave = new Button();
buttonCancel = new Button();
groupBoxComponents.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(86, 18);
labelName.Name = "labelName";
labelName.Size = new Size(80, 20);
labelName.TabIndex = 0;
labelName.Text = "Название:";
//
// labelPrice
//
labelPrice.AutoSize = true;
labelPrice.Location = new Point(86, 74);
labelPrice.Name = "labelPrice";
labelPrice.Size = new Size(86, 20);
labelPrice.TabIndex = 1;
labelPrice.Text = "Стоимость:";
//
// textBoxName
//
textBoxName.Location = new Point(185, 18);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(253, 27);
textBoxName.TabIndex = 2;
//
// textBoxPrice
//
textBoxPrice.Enabled = false;
textBoxPrice.Location = new Point(185, 74);
textBoxPrice.Name = "textBoxPrice";
textBoxPrice.Size = new Size(253, 27);
textBoxPrice.TabIndex = 3;
//
// groupBoxComponents
//
groupBoxComponents.Controls.Add(dataGridView);
groupBoxComponents.Controls.Add(buttonRef);
groupBoxComponents.Controls.Add(buttonDel);
groupBoxComponents.Controls.Add(buttonUpd);
groupBoxComponents.Controls.Add(buttonAdd);
groupBoxComponents.Location = new Point(12, 121);
groupBoxComponents.Name = "groupBoxComponents";
groupBoxComponents.Size = new Size(636, 299);
groupBoxComponents.TabIndex = 4;
groupBoxComponents.TabStop = false;
groupBoxComponents.Text = "Компонент";
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnName, ColumnCount });
dataGridView.Location = new Point(12, 25);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(414, 268);
dataGridView.TabIndex = 5;
//
// ColumnId
//
ColumnId.HeaderText = "Id";
ColumnId.MinimumWidth = 6;
ColumnId.Name = "ColumnId";
ColumnId.ReadOnly = true;
ColumnId.Visible = false;
ColumnId.Width = 125;
//
// ColumnName
//
ColumnName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnName.HeaderText = "Компонент";
ColumnName.MinimumWidth = 6;
ColumnName.Name = "ColumnName";
ColumnName.ReadOnly = true;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
ColumnCount.Width = 125;
//
// buttonRef
//
buttonRef.Location = new Point(462, 218);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(155, 39);
buttonRef.TabIndex = 4;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// buttonDel
//
buttonDel.Location = new Point(462, 159);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(155, 39);
buttonDel.TabIndex = 3;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(462, 102);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(155, 39);
buttonUpd.TabIndex = 2;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(462, 42);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(155, 39);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonSave
//
buttonSave.Location = new Point(311, 438);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(127, 39);
buttonSave.TabIndex = 5;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(474, 438);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(115, 39);
buttonCancel.TabIndex = 6;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormGift
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(660, 502);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(groupBoxComponents);
Controls.Add(textBoxPrice);
Controls.Add(textBoxName);
Controls.Add(labelPrice);
Controls.Add(labelName);
Name = "FormGift";
Text = "Изделие";
groupBoxComponents.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelPrice;
private TextBox textBoxName;
private TextBox textBoxPrice;
private DataGridView dataGridView;
private GroupBox groupBoxComponents;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private Button buttonSave;
private Button buttonCancel;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnName;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,221 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using GiftShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
public partial class FormGift : Form
{
private readonly ILogger _logger;
private readonly IGiftLogic _logic;
private int? _id;
private Dictionary<int, (IComponentModel, int)> _giftComponents;
public int Id { set { _id = value; } }
public FormGift(ILogger<FormGift> logger, IGiftLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_giftComponents = new Dictionary<int, (IComponentModel, int)>();
}
private void FormGift_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка изделия");
try
{
var view = _logic.ReadElement(new GiftSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.GiftName;
textBoxPrice.Text = view.Price.ToString();
_giftComponents = view.GiftComponents ?? new
Dictionary<int, (IComponentModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонент изделия");
try
{
if (_giftComponents != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _giftComponents)
{
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.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(FormGiftComponent));
if (service is FormGiftComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
if (_giftComponents.ContainsKey(form.Id))
{
_giftComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_giftComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormGiftComponent));
if (service is FormGiftComponent form)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _giftComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
_giftComponents[form.Id] = (form.ComponentModel, 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("Удаление компонента: { ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value);
_giftComponents?.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 (_giftComponents == null || _giftComponents.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new GiftBindingModel
{
Id = _id ?? 0,
GiftName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
GiftComponents = _giftComponents
};
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();
}
private double CalcPrice()
{
double price = 0;
foreach (var elem in _giftComponents)
{
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="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,119 @@
namespace GiftShopView
{
partial class FormGiftComponent
{
/// <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()
{
labelComponent = new Label();
labelCount = new Label();
comboBoxComponent = new ComboBox();
textBoxCount = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelComponent
//
labelComponent.AutoSize = true;
labelComponent.Location = new Point(23, 35);
labelComponent.Name = "labelComponent";
labelComponent.Size = new Size(91, 20);
labelComponent.TabIndex = 0;
labelComponent.Text = "Компонент:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(21, 85);
labelCount.Name = "labelCount";
labelCount.Size = new Size(93, 20);
labelCount.TabIndex = 1;
labelCount.Text = "Количество:";
//
// comboBoxComponent
//
comboBoxComponent.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxComponent.FormattingEnabled = true;
comboBoxComponent.Location = new Point(128, 35);
comboBoxComponent.Name = "comboBoxComponent";
comboBoxComponent.Size = new Size(265, 28);
comboBoxComponent.TabIndex = 2;
//
// textBoxCount
//
textBoxCount.Location = new Point(128, 82);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(265, 27);
textBoxCount.TabIndex = 3;
//
// buttonSave
//
buttonSave.Location = new Point(128, 130);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(114, 40);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(277, 130);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(116, 40);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormGiftComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(440, 207);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(comboBoxComponent);
Controls.Add(labelCount);
Controls.Add(labelComponent);
Name = "FormGiftComponent";
Text = "Компонент изделия";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private Label labelComponent;
private Label labelCount;
private ComboBox comboBoxComponent;
private TextBox textBoxCount;
}
}

View File

@ -0,0 +1,77 @@
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Models;
namespace GiftShopView
{
public partial class FormGiftComponent : Form
{
private readonly List<ComponentViewModel>? _list;
public int Id
{
get { return Convert.ToInt32(comboBoxComponent.SelectedValue); }
set { comboBoxComponent.SelectedValue = value; }
}
public IComponentModel? ComponentModel
{
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 FormGiftComponent(IComponentLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxComponent.DisplayMember = "ComponentName";
comboBoxComponent.ValueMember = "Id";
comboBoxComponent.DataSource = _list;
comboBoxComponent.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComponent.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 GiftShopView
{
partial class FormGifts
{
/// <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();
buttonAdd = new Button();
buttonUpd = new Button();
buttonDel = new Button();
buttonRef = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(444, 380);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(517, 38);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(131, 42);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(517, 111);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(131, 42);
buttonUpd.TabIndex = 2;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonDel
//
buttonDel.Location = new Point(517, 187);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(131, 42);
buttonDel.TabIndex = 3;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonRef
//
buttonRef.Location = new Point(517, 265);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(131, 42);
buttonRef.TabIndex = 4;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// FormGifts
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(709, 407);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormGifts";
Text = "Изделия";
Load += FormGifts_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpd;
private Button buttonDel;
private Button buttonRef;
}
}

View File

@ -0,0 +1,108 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
public partial class FormGifts : Form
{
private readonly ILogger _logger;
private readonly IGiftLogic _logic;
public FormGifts(ILogger<FormGifts> logger, IGiftLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormGifts_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["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["GiftComponents"].Visible = false;
}
_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(FormGift));
if (service is FormGift 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(FormGift));
if (service is FormGift 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 GiftBindingModel
{
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>

222
GiftShop/GiftShopView/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,222 @@
namespace GiftShopView
{
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()
{
menuStrip = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
компонентыToolStripMenuItem = new ToolStripMenuItem();
изделияToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
поставкиToolStripMenuItem = new ToolStripMenuItem();
продажиToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
shopReplenishment = new Button();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Padding = new Padding(8, 2, 0, 2);
menuStrip.Size = new Size(1709, 33);
menuStrip.TabIndex = 0;
menuStrip.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, магазиныToolStripMenuItem, поставкиToolStripMenuItem, продажиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(139, 29);
справочникиToolStripMenuItem.Text = "Справочники";
//
// компонентыToolStripMenuItem
//
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(270, 34);
компонентыToolStripMenuItem.Text = "Компоненты";
компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// изделияToolStripMenuItem
//
изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
изделияToolStripMenuItem.Size = new Size(270, 34);
изделияToolStripMenuItem.Text = "Изделия";
изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(270, 34);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += МагазиныToolStripMenuItem_Click;
//
// поставкиToolStripMenuItem
//
поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem";
поставкиToolStripMenuItem.Size = new Size(270, 34);
поставкиToolStripMenuItem.Text = "Поставки";
поставкиToolStripMenuItem.Click += поставкиToolStripMenuItem_Click;
//
// продажиToolStripMenuItem
//
продажиToolStripMenuItem.Name = "продажиToolStripMenuItem";
продажиToolStripMenuItem.Size = new Size(270, 34);
продажиToolStripMenuItem.Text = "Продажи";
продажиToolStripMenuItem.Click += продажиToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(15, 51);
dataGridView.Margin = new Padding(4);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(1404, 529);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1444, 84);
buttonCreateOrder.Margin = new Padding(4);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(236, 51);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(1444, 170);
buttonTakeOrderInWork.Margin = new Padding(4);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(236, 51);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(1444, 264);
buttonOrderReady.Margin = new Padding(4);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(236, 51);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1444, 362);
buttonIssuedOrder.Margin = new Padding(4);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(236, 51);
buttonIssuedOrder.TabIndex = 5;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(1444, 445);
buttonRef.Margin = new Padding(4);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(236, 51);
buttonRef.TabIndex = 6;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// shopReplenishment
//
shopReplenishment.Location = new Point(1444, 525);
shopReplenishment.Margin = new Padding(4);
shopReplenishment.Name = "shopReplenishment";
shopReplenishment.Size = new Size(236, 51);
shopReplenishment.TabIndex = 7;
shopReplenishment.Text = "Пополнение магазина";
shopReplenishment.UseVisualStyleBackColor = true;
shopReplenishment.Click += ShopReplenishment_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1709, 589);
Controls.Add(shopReplenishment);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Margin = new Padding(4);
Name = "FormMain";
Text = "Магазин подарков";
Load += FormMain_Load;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem компонентыToolStripMenuItem;
private ToolStripMenuItem изделияToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private Button shopReplenishment;
private ToolStripMenuItem поставкиToolStripMenuItem;
private ToolStripMenuItem продажиToolStripMenuItem;
}
}

View File

@ -0,0 +1,217 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
}
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["GiftId"].Visible = false;
dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormGifts));
if (service is FormGifts form)
{
form.ShowDialog();
}
}
private void МагазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void продажиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSell));
if (service is FormSell form)
{
form.ShowDialog();
}
}
private void поставкиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSupply));
if (service is FormSupply form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id,
GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value),
GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id,
GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value),
GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id,
GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value),
GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
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 ShopReplenishment_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopReplenishment));
if (service is FormShopReplenishment form)
{
form.ShowDialog();
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

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

124
GiftShop/GiftShopView/FormSell.Designer.cs generated Normal file
View File

@ -0,0 +1,124 @@
namespace GiftShopView
{
partial class FormSell
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
GiftComboBox = new ComboBox();
GiftLabel = new Label();
CountLabel = new Label();
CountTextBox = new TextBox();
SaveButton = new Button();
CancelButton = new Button();
SuspendLayout();
//
// GiftComboBox
//
GiftComboBox.FormattingEnabled = true;
GiftComboBox.Location = new Point(149, 30);
GiftComboBox.Margin = new Padding(4, 5, 4, 5);
GiftComboBox.Name = "GiftComboBox";
GiftComboBox.Size = new Size(241, 33);
GiftComboBox.TabIndex = 0;
//
// GiftLabel
//
GiftLabel.AutoSize = true;
GiftLabel.Location = new Point(51, 33);
GiftLabel.Margin = new Padding(4, 0, 4, 0);
GiftLabel.Name = "GiftLabel";
GiftLabel.Size = new Size(90, 25);
GiftLabel.TabIndex = 1;
GiftLabel.Text = "Подарок:";
//
// CountLabel
//
CountLabel.AutoSize = true;
CountLabel.Location = new Point(30, 82);
CountLabel.Margin = new Padding(4, 0, 4, 0);
CountLabel.Name = "CountLabel";
CountLabel.Size = new Size(111, 25);
CountLabel.TabIndex = 2;
CountLabel.Text = "Количество:";
//
// CountTextBox
//
CountTextBox.Location = new Point(149, 79);
CountTextBox.Margin = new Padding(4, 5, 4, 5);
CountTextBox.Name = "CountTextBox";
CountTextBox.Size = new Size(241, 31);
CountTextBox.TabIndex = 3;
//
// SaveButton
//
SaveButton.Location = new Point(51, 157);
SaveButton.Margin = new Padding(4, 5, 4, 5);
SaveButton.Name = "SaveButton";
SaveButton.Size = new Size(152, 50);
SaveButton.TabIndex = 4;
SaveButton.Text = "Сохранить";
SaveButton.UseVisualStyleBackColor = true;
SaveButton.Click += SaveButton_Click;
//
// CancelButton
//
CancelButton.Location = new Point(250, 157);
CancelButton.Margin = new Padding(4, 5, 4, 5);
CancelButton.Name = "CancelButton";
CancelButton.Size = new Size(152, 50);
CancelButton.TabIndex = 5;
CancelButton.Text = "Отмена";
CancelButton.UseVisualStyleBackColor = true;
//
// SellForm
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(415, 221);
Controls.Add(CancelButton);
Controls.Add(SaveButton);
Controls.Add(CountTextBox);
Controls.Add(CountLabel);
Controls.Add(GiftLabel);
Controls.Add(GiftComboBox);
Margin = new Padding(4, 5, 4, 5);
Name = "SellForm";
Text = "Форма продажи";
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox GiftComboBox;
private Label GiftLabel;
private Label CountLabel;
private TextBox CountTextBox;
private Button SaveButton;
private Button CancelButton;
}
}

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