чето-там-то сделал, устал но продолжаю

This commit is contained in:
Алексей Тихоненков 2024-05-26 20:36:01 +04:00
parent 96c38b0049
commit 12cb7a1290
55 changed files with 1367 additions and 438 deletions

View File

@ -13,10 +13,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiningRoomDatabaseImplement
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiningRoomBusinessLogic", "DiningRoomBusinessLogic\DiningRoomBusinessLogic.csproj", "{89A8AB71-ADD4-405D-AE0B-03ACB1A1BF24}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiningRoomClientApp", "DiningRoomClientApp\DiningRoomClientApp.csproj", "{543BA573-04E2-4CF1-8848-19B8EFE56EE1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiningRoomRestApi", "DiningRoomRestApi\DiningRoomRestApi.csproj", "{75B8E90E-E98D-4B04-9EF1-BBDAC55F1936}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -43,14 +39,6 @@ Global
{89A8AB71-ADD4-405D-AE0B-03ACB1A1BF24}.Debug|Any CPU.Build.0 = Debug|Any CPU
{89A8AB71-ADD4-405D-AE0B-03ACB1A1BF24}.Release|Any CPU.ActiveCfg = Release|Any CPU
{89A8AB71-ADD4-405D-AE0B-03ACB1A1BF24}.Release|Any CPU.Build.0 = Release|Any CPU
{543BA573-04E2-4CF1-8848-19B8EFE56EE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{543BA573-04E2-4CF1-8848-19B8EFE56EE1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{543BA573-04E2-4CF1-8848-19B8EFE56EE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{543BA573-04E2-4CF1-8848-19B8EFE56EE1}.Release|Any CPU.Build.0 = Release|Any CPU
{75B8E90E-E98D-4B04-9EF1-BBDAC55F1936}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{75B8E90E-E98D-4B04-9EF1-BBDAC55F1936}.Debug|Any CPU.Build.0 = Debug|Any CPU
{75B8E90E-E98D-4B04-9EF1-BBDAC55F1936}.Release|Any CPU.ActiveCfg = Release|Any CPU
{75B8E90E-E98D-4B04-9EF1-BBDAC55F1936}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -7,7 +7,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.19.0" />
<PackageReference Include="MailKit" Version="4.6.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="PDFsharp-MigraDoc" Version="1.50.5147" />
</ItemGroup>
<ItemGroup>

View File

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

View File

@ -0,0 +1,54 @@
@using CarpentryWorkshopContracts.ViewModels
@model List<MessageInfoViewModel>
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Заказы</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DateDelivery)
</td>
<td>
@Html.DisplayFor(modelItem => item.Subject)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -11,6 +11,7 @@ namespace DiningRoomContracts.BindingModels
public class CardBindingModel : ICardModel
{
public int Id { get; set; }
public int UserId { get; set; }
public string CardName { get; set; } = string.Empty;
public DateTime DateCardCreate { get; set; } = DateTime.Now;
}

View File

@ -7,7 +7,8 @@ namespace DiningRoomContracts.BindingModels
{
public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty;
public int UserId { get; set; }
public string ComponentName { get; set; } = string.Empty;
public ComponentUnit Unit { get; set; } = ComponentUnit.Неизвестна;
public double Cost { get; set; }
}

View File

@ -5,7 +5,8 @@ namespace DiningRoomContracts.BindingModels
public class DrinkBindingModel : IDrinkModel
{
public int Id { get; set; }
public int CardId { get; set; }
public int UserId { get; set; }
public int? CardId { get; set; }
public string CardName { get; set; } = string.Empty;
public string DrinkName { get; set; } = string.Empty;

View File

@ -11,6 +11,8 @@ namespace DiningRoomContracts.BindingModels
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int UserId { get; set; }
public int ProductId { get; set; }
public string ProductName { get; set; } = string.Empty;
public DateTime DateCreate { get; set; } = DateTime.Now;

View File

@ -6,6 +6,7 @@ namespace DiningRoomContracts.BindingModels
{
public int Id { get; set; }
public int UserId { get; set; }
public string ProductName { get; set; } = string.Empty;
public double Cost { get; set; }

View File

@ -3,8 +3,9 @@
public class CardSearchModel
{
public int? Id { get; set; }
public int? UserId { get; set; }
public DateTime? DateCardCreate { get; set; }
public DateTime? DateCardCreate { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? DrinkId { get; set; }

View File

@ -3,6 +3,7 @@
public class ComponentSearchModel
{
public int? Id { get; set; }
public string ComponentName { get; set; }
public int? UserId { get; set; }
public string ComponentName { get; set; }
}
}

View File

@ -3,8 +3,9 @@
public class DrinkSearchModel
{
public int? Id { get; set; }
public int? UserId { get; set; }
public int? CardId { get; set; }
public int? CardId { get; set; }
public string? DrinkName { get; set; }
}

View File

@ -12,7 +12,9 @@ namespace DiningRoomContracts.SearchModels
{
public int? Id { get; set; }
public DateTime? DateFrom { get; set; }
public string Name { get; set; } = string.Empty;
public int? UserId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public string? ProductName { get; set; }

View File

@ -3,7 +3,7 @@
public class ProductSearchModel
{
public int? Id { get; set; }
public int? UserId { get; set; }
public string? ProductName { get; set; }
}
}

View File

@ -6,9 +6,10 @@ namespace DiningRoomContracts.ViewModels
public class CardViewModel : ICardModel
{
public int Id { get; set; }
public int UserId { get; set; }
public string Login { get; set; } = string.Empty;
[DisplayName("Название карты")]
[DisplayName("Название карты")]
public string CardName { get; set; } = string.Empty;
public Dictionary<int, (IDrinkModel, int)> DrinkCard { get; set; } = new();
[DisplayName("Дата создания")]

View File

@ -7,9 +7,10 @@ namespace DiningRoomContracts.ViewModels
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
public int UserId { get; set; }
public string Login { get; set; } = string.Empty;
[DisplayName("Название продукта")]
[DisplayName("Название продукта")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Единица измерения")]
public ComponentUnit Unit { get; set; } = ComponentUnit.Неизвестна;

View File

@ -6,7 +6,9 @@ namespace DiningRoomContracts.ViewModels
public class DrinkViewModel : IDrinkModel
{
public int Id { get; set; }
public int CardId { get; set; }
public int UserId { get; set; }
public string Login { get; set; } = string.Empty;
public int? CardId { get; set; }
[DisplayName("Алкогольная карта")]
public string CardName { get; set; } = string.Empty;

View File

@ -13,7 +13,11 @@ namespace DiningRoomContracts.ViewModels
{
[DisplayName("Номер")]
public int Id { get; set; }
public int ProductId { get; set; }
[DisplayName("Название заказа")]
public string Name { get; set; } = string.Empty;
public int UserId { get; set; }
public string? Login { get; set; } = string.Empty;
public int ProductId { get; set; }
[DisplayName("Дата Создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Блюдо")]

View File

@ -6,8 +6,10 @@ namespace DiningRoomContracts.ViewModels
public class ProductViewModel : IProductModel
{
public int Id { get; set; }
public int UserId { get; set; }
public string Login { get; set; } = string.Empty;
[DisplayName("Название товара")]
[DisplayName("Название товара")]
public string ProductName { get; set; } = string.Empty;
[DisplayName("Стоимость")]

View File

@ -5,11 +5,14 @@
/// </summary>
public interface ICardModel : IId
{
/// <summary>
/// Название карты
/// </summary>
string CardName { get; }
/// <summary>
/// Пользователь, который добавил
/// </summary>
int UserId { get; }
/// <summary>
/// Название карты
/// </summary>
string CardName { get; }
DateTime DateCardCreate { get; }
}
}

View File

@ -7,10 +7,14 @@ namespace DiningRoomDataModels.Models
/// </summary>
public interface IComponentModel : IId
{
/// <summary>
/// Название продукта
/// </summary>
string ComponentName { get; }
/// <summary>
/// Пользователь, который добавил
/// </summary>
int UserId { get; }
/// <summary>
/// Название продукта
/// </summary>
string ComponentName { get; }
/// <summary>
/// Единица измерения
/// </summary>

View File

@ -5,17 +5,21 @@
/// </summary>
public interface IDrinkModel : IId
{
/// <summary>
/// Пользователь, который добавил
/// </summary>
int UserId { get; }
/// <summary>
/// Название напитка
/// </summary>
string DrinkName { get; }
/// <summary>
/// Название напитка
/// </summary>
string DrinkName { get; }
/// <summary>
/// Стоимость товара
/// </summary>
double Cost { get; }
public int CardId { get; set; }
public int? CardId { get; set; }
/// <summary>
/// Список продуктов

View File

@ -9,10 +9,15 @@ namespace DiningRoomDataModels.Models
{
public interface IOrderModel : IId
{
/// <summary>
/// Дата создания заказа
/// </summary>
DateTime DateCreate { get; }
string Name { get; }
/// <summary>
/// Пользователь, который добавил
/// </summary>
int UserId { get; }
/// <summary>
/// Дата создания заказа
/// </summary>
DateTime DateCreate { get; }
int ProductId { get; }
/// <summary>
/// Статус заказа

View File

@ -5,11 +5,14 @@
/// </summary>
public interface IProductModel : IId
{
/// <summary>
/// Название блюда
/// </summary>
string ProductName { get; }
/// <summary>
/// Пользователь, который добавил
/// </summary>
int UserId { get; }
/// <summary>
/// Название блюда
/// </summary>
string ProductName { get; }
/// <summary>
/// Стоимость блюда

View File

@ -25,24 +25,16 @@ namespace DiningRoomDatabaseImplement.Implements
}
public List<CardViewModel> GetFilteredList(CardSearchModel model) {
using var context = new DiningRoomDatabase();
using var context = new DiningRoomDatabase();
var query = context.Cards.AsQueryable();
//сортировка по дате создания заявки
if (model.DateFrom.HasValue && model.DateTo.HasValue)
{
return context.Cards
.Where(x => (x.DateCardCreate >= model.DateFrom && x.DateCardCreate <= model.DateTo))
.Include(x => x.Drinks)
.Select(x => x.GetViewModel)
.ToList();
}
//возвращение просто всех заявок пользователя (замена GetFullList)
return context.Cards
.Where(x => x.Id == model.Id)
.Include(x => x.Drinks)
.Select(x => x.GetViewModel)
.ToList();
}
if (model.UserId.HasValue)
{
query = query.Where(x => x.UserId == model.UserId.Value);
}
return query.Select(x => x.GetViewModel).ToList();
}
//Поиск только по id, потому что другие поля не уникальные - нет смысла искать 1 элемент
public CardViewModel? GetElement(CardSearchModel model)

View File

@ -20,13 +20,15 @@ namespace DiningRoomDatabaseImplement.Implements
//
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new DiningRoomDatabase();
return context.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
var query = context.Components.AsQueryable();
if (model.UserId.HasValue)
{
query = query.Where(x => x.UserId == model.UserId.Value);
}
return query
.Select(x => x.GetViewModel)
.ToList();
}

View File

@ -23,20 +23,16 @@ namespace DiningRoomDatabaseImplement.Implements
public List<DrinkViewModel> GetFilteredList(DrinkSearchModel model)
{
if (string.IsNullOrEmpty(model.DrinkName))
{
return new();
}
using var context = new DiningRoomDatabase();
return context.Drinks
.Include(x => x.Card)
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.DrinkName.Contains(model.DrinkName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
using var context = new DiningRoomDatabase();
var query = context.Drinks.AsQueryable();
if (model.UserId.HasValue)
{
query = query.Where(x => x.UserId == model.UserId.Value);
}
return query.Select(x => x.GetViewModel).ToList();
}
public DrinkViewModel? GetElement(DrinkSearchModel model)
{

View File

@ -21,6 +21,7 @@ namespace DiningRoomDatabaseImplement.Implements
var element = context.Orders
.Include(x => x.Product)
.Include(x => x.User)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
@ -45,39 +46,21 @@ namespace DiningRoomDatabaseImplement.Implements
return context.Orders
.Include(x=> x.Product)
.Include(x => x.User)
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new DiningRoomDatabase();
if (model.DateFrom.HasValue && model.DateTo.HasValue)
var query = context.Orders.AsQueryable();
if (model.UserId.HasValue)
{
return context.Orders
.Where(x =>(x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo))
.Include(x => x.Product)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
query = query.Where(x => x.UserId == model.UserId.Value);
}
else if (model.Status.HasValue)
{
return context.Orders
.Where(x => (x.Status == model.Status))
.Include(x => x.Product)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders
.Where(x => x.Id == model.Id)
.Include(x => x.Product)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
return query.Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()

View File

@ -24,14 +24,14 @@ namespace DiningRoomDatabaseImplement.Implements
public List<ProductViewModel> GetFilteredList(ProductSearchModel model)
{
using var context = new DiningRoomDatabase();
var query = context.Products.AsQueryable();
return context.Products
.Include(x => x.Order)
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
if (model.UserId.HasValue)
{
query = query.Where(x => x.UserId == model.UserId.Value);
}
return query.Select(x => x.GetViewModel).ToList();
}
public ProductViewModel? GetElement(ProductSearchModel Model)

View File

@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace DiningRoomDatabaseImplement.Migrations
{
[DbContext(typeof(DiningRoomDatabase))]
[Migration("20240526010428_InitialCreate")]
[Migration("20240526163252_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
@ -40,7 +40,7 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<DateTime>("DateCardCreate")
.HasColumnType("timestamp without time zone");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -68,7 +68,7 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<int>("Unit")
.HasColumnType("integer");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -78,36 +78,6 @@ namespace DiningRoomDatabaseImplement.Migrations
b.ToTable("Components");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Drink", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CardId")
.HasColumnType("integer");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.Property<string>("DrinkName")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CardId");
b.HasIndex("UserId");
b.ToTable("Drinks");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.DrinkComponent", b =>
{
b.Property<int>("Id")
@ -148,6 +118,10 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductId")
.HasColumnType("integer");
@ -157,7 +131,7 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -184,7 +158,7 @@ namespace DiningRoomDatabaseImplement.Migrations
.IsRequired()
.HasColumnType("text");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -245,33 +219,56 @@ namespace DiningRoomDatabaseImplement.Migrations
b.ToTable("Users");
});
modelBuilder.Entity("Drink", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("CardId")
.HasColumnType("integer");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.Property<string>("DrinkName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CardId");
b.HasIndex("UserId");
b.ToTable("Drinks");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Card", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Cards")
.HasForeignKey("UserId");
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Component", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Components")
.HasForeignKey("UserId");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Drink", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.Card", "Card")
.WithMany("Drinks")
.HasForeignKey("CardId")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
.WithMany("Drinks")
.HasForeignKey("UserId");
b.Navigation("Card");
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.DrinkComponent", b =>
@ -282,7 +279,7 @@ namespace DiningRoomDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DiningRoomDatabaseImplement.Models.Drink", "Drink")
b.HasOne("Drink", "Drink")
.WithMany("Components")
.HasForeignKey("DrinkId")
.OnDelete(DeleteBehavior.Cascade)
@ -301,18 +298,26 @@ namespace DiningRoomDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserId");
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Product", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Products")
.HasForeignKey("UserId");
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.ProductComponent", b =>
@ -334,6 +339,23 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Navigation("Product");
});
modelBuilder.Entity("Drink", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.Card", "Card")
.WithMany("Drinks")
.HasForeignKey("CardId");
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Drinks")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Card");
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Card", b =>
{
b.Navigation("Drinks");
@ -346,11 +368,6 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Navigation("ProductComponents");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Drink", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Product", b =>
{
b.Navigation("Components");
@ -370,6 +387,11 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Navigation("Products");
});
modelBuilder.Entity("Drink", b =>
{
b.Navigation("Components");
});
#pragma warning restore 612, 618
}
}

View File

@ -33,9 +33,9 @@ namespace DiningRoomDatabaseImplement.Migrations
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<int>(type: "integer", nullable: false),
CardName = table.Column<string>(type: "text", nullable: false),
DateCardCreate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: true)
DateCardCreate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
@ -44,7 +44,8 @@ namespace DiningRoomDatabaseImplement.Migrations
name: "FK_Cards_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
@ -53,10 +54,10 @@ namespace DiningRoomDatabaseImplement.Migrations
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<int>(type: "integer", nullable: false),
ComponentName = table.Column<string>(type: "text", nullable: false),
Unit = table.Column<int>(type: "integer", nullable: false),
Cost = table.Column<double>(type: "double precision", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: true)
Cost = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
@ -65,7 +66,8 @@ namespace DiningRoomDatabaseImplement.Migrations
name: "FK_Components_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
@ -74,9 +76,9 @@ namespace DiningRoomDatabaseImplement.Migrations
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<int>(type: "integer", nullable: false),
ProductName = table.Column<string>(type: "text", nullable: false),
Cost = table.Column<double>(type: "double precision", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: true)
Cost = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
@ -85,7 +87,8 @@ namespace DiningRoomDatabaseImplement.Migrations
name: "FK_Products_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
@ -94,10 +97,10 @@ namespace DiningRoomDatabaseImplement.Migrations
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<int>(type: "integer", nullable: false),
DrinkName = table.Column<string>(type: "text", nullable: false),
CardId = table.Column<int>(type: "integer", nullable: false),
Cost = table.Column<double>(type: "double precision", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: true)
CardId = table.Column<int>(type: "integer", nullable: true),
Cost = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
@ -106,13 +109,13 @@ namespace DiningRoomDatabaseImplement.Migrations
name: "FK_Drinks_Cards_CardId",
column: x => x.CardId,
principalTable: "Cards",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
principalColumn: "Id");
table.ForeignKey(
name: "FK_Drinks_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
@ -121,12 +124,13 @@ namespace DiningRoomDatabaseImplement.Migrations
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
ProductId = table.Column<int>(type: "integer", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
Status = table.Column<int>(type: "integer", nullable: false),
DateCreate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: true)
UserId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
@ -141,7 +145,8 @@ namespace DiningRoomDatabaseImplement.Migrations
name: "FK_Orders_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id");
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(

View File

@ -37,7 +37,7 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<DateTime>("DateCardCreate")
.HasColumnType("timestamp without time zone");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -65,7 +65,7 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<int>("Unit")
.HasColumnType("integer");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -75,36 +75,6 @@ namespace DiningRoomDatabaseImplement.Migrations
b.ToTable("Components");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Drink", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("CardId")
.HasColumnType("integer");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.Property<string>("DrinkName")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CardId");
b.HasIndex("UserId");
b.ToTable("Drinks");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.DrinkComponent", b =>
{
b.Property<int>("Id")
@ -145,6 +115,10 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductId")
.HasColumnType("integer");
@ -154,7 +128,7 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -181,7 +155,7 @@ namespace DiningRoomDatabaseImplement.Migrations
.IsRequired()
.HasColumnType("text");
b.Property<int?>("UserId")
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
@ -242,33 +216,56 @@ namespace DiningRoomDatabaseImplement.Migrations
b.ToTable("Users");
});
modelBuilder.Entity("Drink", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("CardId")
.HasColumnType("integer");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.Property<string>("DrinkName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("CardId");
b.HasIndex("UserId");
b.ToTable("Drinks");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Card", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Cards")
.HasForeignKey("UserId");
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Component", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Components")
.HasForeignKey("UserId");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Drink", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.Card", "Card")
.WithMany("Drinks")
.HasForeignKey("CardId")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
.WithMany("Drinks")
.HasForeignKey("UserId");
b.Navigation("Card");
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.DrinkComponent", b =>
@ -279,7 +276,7 @@ namespace DiningRoomDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DiningRoomDatabaseImplement.Models.Drink", "Drink")
b.HasOne("Drink", "Drink")
.WithMany("Components")
.HasForeignKey("DrinkId")
.OnDelete(DeleteBehavior.Cascade)
@ -298,18 +295,26 @@ namespace DiningRoomDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserId");
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Product", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.User", null)
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Products")
.HasForeignKey("UserId");
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.ProductComponent", b =>
@ -331,6 +336,23 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Navigation("Product");
});
modelBuilder.Entity("Drink", b =>
{
b.HasOne("DiningRoomDatabaseImplement.Models.Card", "Card")
.WithMany("Drinks")
.HasForeignKey("CardId");
b.HasOne("DiningRoomDatabaseImplement.Models.User", "User")
.WithMany("Drinks")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Card");
b.Navigation("User");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Card", b =>
{
b.Navigation("Drinks");
@ -343,11 +365,6 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Navigation("ProductComponents");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Drink", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("DiningRoomDatabaseImplement.Models.Product", b =>
{
b.Navigation("Components");
@ -367,6 +384,11 @@ namespace DiningRoomDatabaseImplement.Migrations
b.Navigation("Products");
});
modelBuilder.Entity("Drink", b =>
{
b.Navigation("Components");
});
#pragma warning restore 612, 618
}
}

View File

@ -16,6 +16,8 @@ namespace DiningRoomDatabaseImplement.Models
public class Card : ICardModel
{
public int Id { get; set; }
public int UserId { get; set; }
public User User { get; set; }
[Required]
public string CardName { get; set; } = string.Empty;
[Required]
@ -29,6 +31,7 @@ namespace DiningRoomDatabaseImplement.Models
Id = model.Id,
CardName = model.CardName,
DateCardCreate = model.DateCardCreate,
UserId = model.UserId,
};
}
public void Update(CardBindingModel model)

View File

@ -10,8 +10,10 @@ namespace DiningRoomDatabaseImplement.Models
public class Component : IComponentModel
{
public int Id { get; private set; }
public int UserId { get; set; }
public User User { get; set; }
[Required]
[Required]
public string ComponentName { get; private set; } = string.Empty;
[Required]
public ComponentUnit Unit { get; private set; } = ComponentUnit.Неизвестна;
@ -36,6 +38,7 @@ namespace DiningRoomDatabaseImplement.Models
ComponentName = Model.ComponentName,
Cost = Model.Cost,
Unit = Model.Unit,
UserId = Model.UserId,
};
}
public static Component Create(ComponentViewModel Model)
@ -46,6 +49,7 @@ namespace DiningRoomDatabaseImplement.Models
ComponentName = Model.ComponentName,
Cost = Model.Cost,
Unit = Model.Unit,
UserId = Model.UserId,
};
}
public void Update(ComponentBindingModel Model)
@ -65,6 +69,7 @@ namespace DiningRoomDatabaseImplement.Models
ComponentName = ComponentName,
Cost = Cost,
Unit = Unit,
UserId = UserId,
};
}

View File

@ -1,112 +1,113 @@
using DiningRoomContracts.BindingModels;
using DiningRoomContracts.ViewModels;
using DiningRoomDatabaseImplement.Models;
using DiningRoomDatabaseImplement;
using DiningRoomDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
namespace DiningRoomDatabaseImplement.Models
public class Drink : IDrinkModel
{
public class Drink : IDrinkModel
{
public int Id { get; private set; }
public int Id { get; private set; }
public int UserId { get; set; }
public User User { get; set; }
[Required]
public string DrinkName { get; private set; } = string.Empty;
public int CardId { get; set; }
[Required]
public string DrinkName { get; private set; } = string.Empty;
[Required]
public double Cost { get; private set; }
public virtual Card Card { get; set; }
public int? CardId { get; set; }
[ForeignKey("DrinkId")]
public virtual List<DrinkComponent> Components { get; set; } = new();
[Required]
public double Cost { get; private set; }
private Dictionary<int, (IComponentModel, int)>? _drinkComponents;
public virtual Card? Card { get; set; }
[NotMapped]
public Dictionary<int, (IComponentModel, int)> DrinkComponents
{
get
{
if (_drinkComponents == null)
{
_drinkComponents = Components.ToDictionary(
DrkComp => DrkComp.ComponentId,
DrkComp => (DrkComp.Component as IComponentModel, DrkComp.Count)
);
}
[ForeignKey("DrinkId")]
public virtual List<DrinkComponent> Components { get; set; } = new();
return _drinkComponents;
}
}
private Dictionary<int, (IComponentModel, int)>? _drinkComponents;
public static Drink Create(DiningRoomDatabase Context, DrinkBindingModel Model)
{
return new()
{
Id = Model.Id,
DrinkName = Model.DrinkName,
CardId = Model.CardId,
Cost = Model.Cost,
Components = Model.DrinkComponents.Select(x => new DrinkComponent
{
Component = Context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
};
}
public void Update(DrinkBindingModel model)
{
DrinkName = model.DrinkName;
Cost = model.Cost;
CardId = model.CardId;
}
public DrinkViewModel GetViewModel
{
get
{
using var context = new DiningRoomDatabase();
return new DrinkViewModel
{
Id = Id,
DrinkName = DrinkName,
Cost = Cost,
CardId = CardId,
CardName = context.Cards.FirstOrDefault(x => x.Id == CardId)?.CardName ?? string.Empty,
DrinkComponents = DrinkComponents
};
}
}
public void UpdateComponents(DiningRoomDatabase context, DrinkBindingModel model)
[NotMapped]
public Dictionary<int, (IComponentModel, int)> DrinkComponents
{
get
{
var drinkComponents = context.DrinkComponents.Where(rec => rec.DrinkId == model.Id).ToList();
if (drinkComponents != null && drinkComponents.Count > 0)
{ // удалили те, которых нет в модели
context.DrinkComponents.RemoveRange(drinkComponents.Where(rec => !model.DrinkComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in drinkComponents)
{
updateComponent.Count = model.DrinkComponents[updateComponent.ComponentId].Item2;
model.DrinkComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var drink = context.Drinks.First(x => x.Id == Id);
foreach (var pc in model.DrinkComponents)
if (_drinkComponents == null)
{
context.DrinkComponents.Add(new DrinkComponent
{
Drink = drink,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
_drinkComponents = Components.ToDictionary(
DrkComp => DrkComp.ComponentId,
DrkComp => (DrkComp.Component as IComponentModel, DrkComp.Count)
);
}
_drinkComponents = null;
return _drinkComponents;
}
}
public static Drink Create(DiningRoomDatabase Context, DrinkBindingModel Model)
{
return new()
{
Id = Model.Id,
DrinkName = Model.DrinkName,
CardId = Model.CardId,
Cost = Model.Cost,
Components = Model.DrinkComponents.Select(x => new DrinkComponent
{
Component = Context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
UserId = Model.UserId,
};
}
public void Update(DrinkBindingModel model)
{
DrinkName = model.DrinkName;
Cost = model.Cost;
CardId = model.CardId;
}
public DrinkViewModel GetViewModel
{
get
{
using var context = new DiningRoomDatabase();
return new DrinkViewModel
{
Id = Id,
DrinkName = DrinkName,
Cost = Cost,
CardId = CardId,
CardName = CardId.HasValue ? context.Cards.FirstOrDefault(x => x.Id == CardId)?.CardName ?? string.Empty : null,
DrinkComponents = DrinkComponents
};
}
}
public void UpdateComponents(DiningRoomDatabase context, DrinkBindingModel model)
{
var drinkComponents = context.DrinkComponents.Where(rec => rec.DrinkId == model.Id).ToList();
if (drinkComponents != null && drinkComponents.Count > 0)
{ // удалили те, которых нет в модели
context.DrinkComponents.RemoveRange(drinkComponents.Where(rec => !model.DrinkComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in drinkComponents)
{
updateComponent.Count = model.DrinkComponents[updateComponent.ComponentId].Item2;
model.DrinkComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var drink = context.Drinks.First(x => x.Id == Id);
foreach (var pc in model.DrinkComponents)
{
context.DrinkComponents.Add(new DrinkComponent
{
Drink = drink,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_drinkComponents = null;
}
}

View File

@ -14,18 +14,22 @@ namespace DiningRoomDatabaseImplement.Models
{
public class Order : IOrderModel
{
[Required]
public string Name { get; set; }
public int Id { get; set; }
[Required]
public int ProductId { get; set; }
[Required]
public int Count { get; set; }
[Required]
public double Sum { get; set; }
[Required]
public OrderStatus Status { get; set; }
[Required]
public DateTime DateCreate { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public virtual Product Product { get; set; }
@ -38,7 +42,9 @@ namespace DiningRoomDatabaseImplement.Models
return new Order()
{
Id = model.Id,
ProductId = model.ProductId,
Name = model.Name,
UserId = model.UserId,
ProductId = model.ProductId,
DateCreate = model.DateCreate,
Status = model.Status,
Count = model.Count,
@ -53,6 +59,7 @@ namespace DiningRoomDatabaseImplement.Models
return;
}
using var context = new DiningRoomDatabase();
Name = model.Name;
Status = model.Status;
context.SaveChanges();
}
@ -65,6 +72,9 @@ namespace DiningRoomDatabaseImplement.Models
return new OrderViewModel
{
Id = Id,
Name = Name,
UserId = UserId,
Login = context.Users.FirstOrDefault(x=> x.Id == UserId)?.Login ?? string.Empty,
ProductId = ProductId,
ProductName = context.Products.FirstOrDefault(x => x.Id == ProductId)?.ProductName ?? string.Empty,
DateCreate = DateCreate,

View File

@ -10,8 +10,10 @@ namespace DiningRoomDatabaseImplement.Models
public class Product : IProductModel
{
public int Id { get; set; }
public int UserId { get; set; }
public User User { get; set; }
[Required]
[Required]
public string ProductName { get; set; } = string.Empty;
[Required]
@ -50,6 +52,7 @@ namespace DiningRoomDatabaseImplement.Models
Component = Context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
UserId = Model.UserId,
};
}
public void Update(ProductBindingModel model)

View File

@ -107,7 +107,7 @@
Controls.Add(dataGridView);
Name = "FormCards";
Text = "Изделия";
Load += FormWoods_Load;
Load += FormProducts_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();

View File

@ -1,6 +1,7 @@
using DiningRoomContracts.BindingModels;
using DiningRoomContracts.BusinessLogicContracts;
using DiningRoomContracts.SearchModels;
using DiningRoomContracts.ViewModels;
using DiningRoomDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
@ -20,25 +21,35 @@ namespace DiningRoomView
{
private readonly ILogger _logger;
private readonly ICardLogic _logic;
public UserViewModel? _currentUser { get; set; }
public FormCards(ILogger<FormCards> logger, ICardLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormWoods_Load(object sender, EventArgs e)
private void FormProducts_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
Close();
return;
}
try
{
var list = _logic.ReadList(null);
var list = _logic.ReadList(new CardSearchModel { UserId = _currentUser.Id });
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["UserId"].Visible = false;
dataGridView.Columns["DrinkCard"].Visible = false;
dataGridView.Columns["Login"].Visible = false;
dataGridView.Columns["CardName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
@ -52,6 +63,11 @@ namespace DiningRoomView
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -64,6 +80,7 @@ namespace DiningRoomView
{
Id = 0,
CardName = textBoxName.Text,
UserId = _currentUser.Id,
};
var operationResult =_logic.Create(model);
if (!operationResult)

View File

@ -12,6 +12,7 @@ namespace DiningRoomView
private readonly IComponentLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public int UserId { get; set; }
public FormComponent(ILogger<FormComponent> logger, IComponentLogic logic)
{
InitializeComponent(); _logger = logger;
@ -24,7 +25,7 @@ namespace DiningRoomView
try
{
_logger.LogInformation("Ïîëó÷åíèå êîìïîíåíòà");
var view = _logic.ReadElement(new ComponentSearchModel { Id = _id.Value });
var view = _logic.ReadElement(new ComponentSearchModel { Id = _id.Value, UserId = UserId });
if (view != null)
{
textBoxName.Text = view.ComponentName;
@ -32,7 +33,7 @@ namespace DiningRoomView
comboBoxUnit.DisplayMember = "Unit";
comboBoxUnit.ValueMember = "Id";
comboBoxUnit.DataSource = Enum.GetValues(typeof(ComponentUnit)); ;
comboBoxUnit.SelectedItem = null;
comboBoxUnit.SelectedItem = view.Unit;
}
}
catch (Exception ex)
@ -62,7 +63,8 @@ namespace DiningRoomView
Id = _id ?? 0,
ComponentName = textBoxName.Text,
Unit = (ComponentUnit)comboBoxUnit.SelectedItem,
Cost = Convert.ToDouble(textBoxCost.Text)
Cost = Convert.ToDouble(textBoxCost.Text),
UserId = UserId
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)

View File

@ -1,6 +1,7 @@
using DiningRoomContracts.BindingModels;
using DiningRoomContracts.BusinessLogicContracts;
using DiningRoomContracts.SearchModels;
using DiningRoomContracts.ViewModels;
using DiningRoomDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
@ -19,6 +20,7 @@ namespace DiningRoomView
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
public UserViewModel? _currentUser { get; set; }
public FormComponents(ILogger<FormComponents> logger, IComponentLogic logic)
{
InitializeComponent();
@ -31,13 +33,21 @@ namespace DiningRoomView
}
private void LoadData()
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
Close();
return;
}
try
{
var list = _logic.ReadList(null);
var list = _logic.ReadList((new ComponentSearchModel { UserId = _currentUser.Id }));
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["UserId"].Visible = false;
dataGridView.Columns["Login"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
@ -51,9 +61,15 @@ namespace DiningRoomView
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
form.UserId = _currentUser.Id;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
@ -62,11 +78,17 @@ namespace DiningRoomView
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
form.UserId = _currentUser.Id;
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{

View File

@ -22,6 +22,7 @@ namespace DiningRoomView
private readonly ILogger _logger;
private readonly IProductLogic _logicP;
private readonly IOrderLogic _logicO;
public int UserId { get; set; }
public FormCreateOrder(ILogger<FormCreateOrder> logger, IProductLogic logicP, IOrderLogic logicO)
{
@ -35,7 +36,7 @@ namespace DiningRoomView
{
_logger.LogInformation("Загрузка изделий для заказа");
// прописать логику
List<ProductViewModel> list = _logicP.ReadList(null);
List<ProductViewModel> list = _logicP.ReadList(new ProductSearchModel { UserId = UserId });
if (list != null)
{
comboBoxProduct.DisplayMember = "ProductName";
@ -73,14 +74,9 @@ namespace DiningRoomView
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
if (UserId == 0)
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxProduct.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
@ -92,7 +88,8 @@ namespace DiningRoomView
ProductName = comboBoxProduct.Text,
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text),
Status = OrderStatus.Принят
Status = OrderStatus.Принят,
UserId = UserId
});
if (!operationResult)
{

View File

@ -23,29 +23,12 @@ namespace DiningRoomView
private readonly IDrinkLogic _logic;
private readonly ICardLogic _cardLogic;
private int? _id;
public int UserId { get; set; }
private Dictionary<int, (IComponentModel, int)> _drinkComponents;
public int Id { get { return Convert.ToInt32(comboBoxCards.SelectedValue); } set { comboBoxCards.SelectedValue = value; _id = value; } }
private readonly List<CardViewModel>? _list;
public ICardModel? CardModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public FormDrink(ILogger<FormDrink> logger, IDrinkLogic logic, ICardLogic cardLogic)
{
InitializeComponent();
@ -74,6 +57,7 @@ namespace DiningRoomView
{
textBoxName.Text = view.DrinkName;
textBoxPrice.Text = view.Cost.ToString();
comboBoxCards.SelectedItem = view.CardId;
_drinkComponents = view.DrinkComponents ?? new Dictionary<int, (IComponentModel, int)>();
LoadData();
}
@ -177,6 +161,11 @@ namespace DiningRoomView
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (UserId == 0)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -200,8 +189,9 @@ namespace DiningRoomView
Id = _id ?? 0,
DrinkName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxPrice.Text),
CardId = Convert.ToInt32(comboBoxCards.SelectedValue),
DrinkComponents = _drinkComponents
CardId = comboBoxCards.SelectedValue as int?,
DrinkComponents = _drinkComponents,
UserId = this.UserId // Передаем UserId
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)

View File

@ -0,0 +1,119 @@
namespace DiningRoomView
{
partial class FormLogin
{
/// <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()
{
labelPassword = new Label();
labelLogin = new Label();
textBoxPassword = new TextBox();
textBoxLogin = new TextBox();
buttonReg = new Button();
buttonLogin = new Button();
SuspendLayout();
//
// labelPassword
//
labelPassword.AutoSize = true;
labelPassword.Location = new Point(23, 51);
labelPassword.Name = "labelPassword";
labelPassword.Size = new Size(52, 15);
labelPassword.TabIndex = 22;
labelPassword.Text = "Пароль:";
//
// labelLogin
//
labelLogin.AutoSize = true;
labelLogin.Location = new Point(23, 15);
labelLogin.Name = "labelLogin";
labelLogin.Size = new Size(44, 15);
labelLogin.TabIndex = 20;
labelLogin.Text = "Логин:";
//
// textBoxPassword
//
textBoxPassword.Location = new Point(98, 48);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.PasswordChar = '*';
textBoxPassword.Size = new Size(301, 23);
textBoxPassword.TabIndex = 19;
//
// textBoxLogin
//
textBoxLogin.Location = new Point(98, 12);
textBoxLogin.Name = "textBoxLogin";
textBoxLogin.Size = new Size(301, 23);
textBoxLogin.TabIndex = 17;
//
// buttonReg
//
buttonReg.Location = new Point(12, 131);
buttonReg.Name = "buttonReg";
buttonReg.Size = new Size(129, 23);
buttonReg.TabIndex = 15;
buttonReg.Text = "Регистрация";
buttonReg.UseVisualStyleBackColor = true;
buttonReg.Click += RegButt_Click;
//
// buttonLogin
//
buttonLogin.Location = new Point(324, 131);
buttonLogin.Name = "buttonLogin";
buttonLogin.Size = new Size(75, 23);
buttonLogin.TabIndex = 1;
buttonLogin.Text = "Логин";
buttonLogin.UseVisualStyleBackColor = true;
buttonLogin.Click += ButtonLogin_Click;
//
// FormLogin
//
AcceptButton = buttonLogin;
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(413, 168);
Controls.Add(buttonLogin);
Controls.Add(labelPassword);
Controls.Add(labelLogin);
Controls.Add(textBoxPassword);
Controls.Add(textBoxLogin);
Controls.Add(buttonReg);
Name = "FormLogin";
Text = "Логин";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelPassword;
private Label labelLogin;
private TextBox textBoxPassword;
private TextBox textBoxLogin;
private Button buttonReg;
private Button buttonLogin;
}
}

View File

@ -0,0 +1,57 @@
using DiningRoomContracts.BusinessLogicContracts;
using DiningRoomContracts.SearchModels;
using DiningRoomContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DiningRoomView
{
public partial class FormLogin : Form
{
private readonly IUserLogic _userLogic;
public UserViewModel? LoggedInUser { get; private set; }
public FormLogin(IUserLogic userLogic)
{
InitializeComponent();
_userLogic = userLogic;
}
private void ButtonLogin_Click(object sender, EventArgs e)
{
var user = _userLogic.ReadElement(new UserSearchModel
{
Login = textBoxLogin.Text,
Password = textBoxPassword.Text
});
if (user != null)
{
LoggedInUser = user;
DialogResult = DialogResult.OK;
Close();
}
else
{
MessageBox.Show("Неверный логин или пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RegButt_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormRegister));
if (service is FormRegister form)
{
form.ShowDialog();
}
}
}
}

View File

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

View File

@ -164,6 +164,7 @@
button5.TabIndex = 10;
button5.Text = "Обновить списки";
button5.UseVisualStyleBackColor = true;
button5.Click += ButtonRef_Click;
//
// button6
//

View File

@ -10,6 +10,9 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DiningRoomContracts.BindingModels;
using DiningRoomBusinessLogic.BusinessLogic;
using DiningRoomContracts.ViewModels;
using DiningRoomContracts.SearchModels;
namespace DiningRoomView
{
@ -18,88 +21,134 @@ namespace DiningRoomView
private readonly ILogger _logger;
private readonly IProductLogic _productLogic;
private readonly IDrinkLogic _drinkLogic;
public FormMain(ILogger<FormMain> logger, IProductLogic productLogic, IDrinkLogic drinkLogic)
{
InitializeComponent();
_logger = logger;
private readonly IUserLogic _userLogic;
private UserViewModel? _currentUser;
public FormMain(ILogger<FormMain> logger, IProductLogic productLogic, IDrinkLogic drinkLogic, IUserLogic userLogic)
{
InitializeComponent();
_logger = logger;
_productLogic = productLogic;
_drinkLogic = drinkLogic;
}
private void FormMain_Load(object sender, EventArgs e)
_userLogic = userLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
var loginForm = new FormLogin(_userLogic);
if (loginForm.ShowDialog() != DialogResult.OK)
{
Close();
return;
}
_currentUser = loginForm.LoggedInUser;
LoadData();
}
private void LoadData()
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка блюд");
try
{
var list = _productLogic.ReadList(null);
if (list != null)
{
dataGridView1.DataSource = list;
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
Close();
return;
}
_logger.LogInformation("Загрузка блюд");
try
{
var list = _productLogic.ReadList(new ProductSearchModel { UserId = _currentUser.Id });
if (list != null)
{
dataGridView1.DataSource = list;
dataGridView1.Columns["Id"].Visible = false;
dataGridView1.Columns["UserId"].Visible = false;
dataGridView1.Columns["Login"].Visible = false;
dataGridView1.Columns["ProductComponents"].Visible = false;
dataGridView1.Columns["ProductName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка блюд успешна");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки блюд");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка блюд успешна");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки блюд");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка напитков");
try
{
var list = _drinkLogic.ReadList(null);
if (list != null)
{
_logger.LogInformation("Загрузка напитков");
try
{
var list = _drinkLogic.ReadList(new DrinkSearchModel { UserId = _currentUser.Id });
if (list != null)
{
dataGridView2.DataSource = list;
dataGridView2.Columns["Id"].Visible = false;
dataGridView2.Columns["UserId"].Visible = false;
dataGridView2.Columns["Login"].Visible = false;
dataGridView2.Columns["CardId"].Visible = false;
dataGridView2.Columns["DrinkComponents"].Visible = false;
dataGridView2.Columns["DrinkName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка напитков успешна");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки напитков");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
_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 (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
form._currentUser = _currentUser;
form.ShowDialog();
}
}
private void ЗаказыToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormOrders));
if (service is FormOrders form)
{
form._currentUser = _currentUser;
form.ShowDialog();
}
}
private void КартыToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormCards));
if (service is FormCards form)
{
form._currentUser = _currentUser;
form.ShowDialog();
}
}
private void ButtonAddProduct_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormProduct));
if (service is FormProduct form)
{
form.UserId = _currentUser.Id;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
@ -108,11 +157,17 @@ namespace DiningRoomView
}
private void ButtonUpdProduct_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (dataGridView1.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormProduct));
if (service is FormProduct form)
{
form.UserId = _currentUser.Id;
form.Id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
@ -147,9 +202,15 @@ namespace DiningRoomView
}
private void ButtonAddDrink_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormDrink));
if (service is FormDrink form)
{
form.UserId = _currentUser.Id;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
@ -160,9 +221,15 @@ namespace DiningRoomView
{
if (dataGridView2.SelectedRows.Count == 1)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormDrink));
if (service is FormDrink form)
{
form.UserId = _currentUser.Id;
form.Id = Convert.ToInt32(dataGridView2.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
@ -195,6 +262,10 @@ namespace DiningRoomView
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
//private void ButtonCreateSale_Click(object sender, EventArgs e)
//{

View File

@ -1,6 +1,8 @@
using DiningRoomBusinessLogic.BusinessLogic;
using DiningRoomContracts.BindingModels;
using DiningRoomContracts.BusinessLogicContracts;
using DiningRoomContracts.SearchModels;
using DiningRoomContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -18,6 +20,7 @@ namespace DiningRoomView
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public UserViewModel? _currentUser { get; set; }
public FormOrders(ILogger<FormMain> logger, IOrderLogic orderLogic)
{
InitializeComponent();
@ -30,11 +33,16 @@ namespace DiningRoomView
}
private void LoadData()
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Загрузка заказов");
// прописать логику
try
{
var list = _orderLogic.ReadList(null);
var list = _orderLogic.ReadList(new OrderSearchModel { UserId = _currentUser.Id });
if (list != null)
{
dataGridView.DataSource = list;
@ -50,9 +58,15 @@ namespace DiningRoomView
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
if (_currentUser == null)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.UserId = _currentUser.Id;
form.ShowDialog();
LoadData();
}

View File

@ -1,6 +1,7 @@
using DiningRoomContracts.BindingModels;
using DiningRoomContracts.BusinessLogicContracts;
using DiningRoomContracts.SearchModels;
using DiningRoomContracts.ViewModels;
using DiningRoomDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
@ -22,6 +23,7 @@ namespace DiningRoomView
private int? _id;
private Dictionary<int, (IComponentModel, int)> _productComponents;
public int Id { set { _id = value; } }
public int UserId { get; set; }
public FormProduct(ILogger<FormProduct> logger, IProductLogic logic)
{
InitializeComponent();
@ -144,6 +146,11 @@ namespace DiningRoomView
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (UserId == 0)
{
MessageBox.Show("Ошибка авторизации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
@ -167,7 +174,8 @@ namespace DiningRoomView
Id = _id ?? 0,
ProductName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxPrice.Text),
ProductComponents = _productComponents
ProductComponents = _productComponents,
UserId = UserId // Передаем UserId
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
@ -180,7 +188,8 @@ namespace DiningRoomView
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения изделия"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError(ex, "Ошибка сохранения изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)

View File

@ -1,4 +1,5 @@
using DiningRoomContracts.BusinessLogicContracts;
using DiningRoomContracts.SearchModels;
using DiningRoomContracts.ViewModels;
using DiningRoomDataModels.Models;
using System;

View File

@ -0,0 +1,140 @@
namespace DiningRoomView
{
partial class FormRegister
{
/// <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()
{
buttonReg = new Button();
buttonBack = new Button();
textBoxLogin = new TextBox();
textBoxEmail = new TextBox();
textBoxPassword = new TextBox();
labelLogin = new Label();
labelEmail = new Label();
labelPassword = new Label();
SuspendLayout();
//
// buttonReg
//
buttonReg.Location = new Point(119, 139);
buttonReg.Name = "buttonReg";
buttonReg.Size = new Size(129, 23);
buttonReg.TabIndex = 7;
buttonReg.Text = "Зарегистрироваться";
buttonReg.UseVisualStyleBackColor = true;
buttonReg.Click += ButtonRegister_Click;
//
// buttonBack
//
buttonBack.Location = new Point(254, 139);
buttonBack.Name = "buttonBack";
buttonBack.Size = new Size(75, 23);
buttonBack.TabIndex = 8;
buttonBack.Text = "Назад";
buttonBack.UseVisualStyleBackColor = true;
buttonBack.Click += LoginButt_Click;
//
// textBoxLogin
//
textBoxLogin.Location = new Point(94, 17);
textBoxLogin.Name = "textBoxLogin";
textBoxLogin.Size = new Size(235, 23);
textBoxLogin.TabIndex = 9;
//
// textBoxEmail
//
textBoxEmail.Location = new Point(94, 46);
textBoxEmail.Name = "textBoxEmail";
textBoxEmail.Size = new Size(235, 23);
textBoxEmail.TabIndex = 10;
//
// textBoxPassword
//
textBoxPassword.Location = new Point(94, 75);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.Size = new Size(235, 23);
textBoxPassword.TabIndex = 11;
//
// labelLogin
//
labelLogin.AutoSize = true;
labelLogin.Location = new Point(19, 20);
labelLogin.Name = "labelLogin";
labelLogin.Size = new Size(44, 15);
labelLogin.TabIndex = 12;
labelLogin.Text = "Логин:";
//
// labelEmail
//
labelEmail.AutoSize = true;
labelEmail.Location = new Point(19, 49);
labelEmail.Name = "labelEmail";
labelEmail.Size = new Size(44, 15);
labelEmail.TabIndex = 13;
labelEmail.Text = "Почта:";
//
// labelPassword
//
labelPassword.AutoSize = true;
labelPassword.Location = new Point(19, 78);
labelPassword.Name = "labelPassword";
labelPassword.Size = new Size(52, 15);
labelPassword.TabIndex = 14;
labelPassword.Text = "Пароль:";
//
// FormRegister
//
AcceptButton = buttonReg;
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(352, 176);
Controls.Add(labelPassword);
Controls.Add(labelEmail);
Controls.Add(labelLogin);
Controls.Add(textBoxPassword);
Controls.Add(textBoxEmail);
Controls.Add(textBoxLogin);
Controls.Add(buttonBack);
Controls.Add(buttonReg);
Name = "FormRegister";
Text = "Регистрация";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonReg;
private Button buttonBack;
private TextBox textBoxLogin;
private TextBox textBoxEmail;
private TextBox textBoxPassword;
private Label labelLogin;
private Label labelEmail;
private Label labelPassword;
}
}

View File

@ -0,0 +1,66 @@
using DiningRoomContracts.BindingModels;
using DiningRoomContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DiningRoomView
{
public partial class FormRegister : Form
{
private readonly IUserLogic _userLogic;
private readonly ILogger _logger;
public FormRegister(IUserLogic userLogic, ILogger<FormRegister> logger)
{
InitializeComponent();
_userLogic = userLogic;
_logger = logger;
}
private void ButtonRegister_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxLogin.Text) || string.IsNullOrEmpty(textBoxPassword.Text) || string.IsNullOrEmpty(textBoxEmail.Text))
{
MessageBox.Show("Заполните все поля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var model = new UserBindingModel
{
Login = textBoxLogin.Text,
Password = textBoxPassword.Text,
Email = textBoxEmail.Text
};
try
{
if (_userLogic.Create(model))
{
MessageBox.Show("Регистрация прошла успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
Close();
}
else
{
MessageBox.Show("Ошибка при регистрации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoginButt_Click(object sender, EventArgs e)
{
Close();
}
}
}

View File

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

View File

@ -40,12 +40,14 @@ namespace DiningRoomView
services.AddTransient<IDrinkStorage, DrinkStorage>();
services.AddTransient<ICardStorage, CardStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IUserStorage, UserStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IProductLogic, ProductLogic>();
services.AddTransient<IDrinkLogic, DrinkLogic>();
services.AddTransient<ICardLogic, CardLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IUserLogic, UserLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
@ -57,6 +59,8 @@ namespace DiningRoomView
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormOrders>();
services.AddTransient<FormCards>();
services.AddTransient<FormRegister>();
services.AddTransient<FormLogin>();