Borschevskaya A.A. Lab Work 5 Hard #13

Closed
pgirl1 wants to merge 53 commits from lab5_hard into lab5_base
147 changed files with 79325 additions and 43 deletions

View File

@ -14,10 +14,12 @@ namespace FurnitureAssemFileImplement
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string FurnitureFileName = "Furniture.xml";
private readonly string ShopFileName = "Shop.xml";
private readonly string ClientFileName = "Client.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Furniture> Furnitures { get; private set; }
public List<Shop> Shops { get; private set; }
public List<Client> Clients { get; private set; }
public static DataFileSingleton GetInstance()
{
@ -31,12 +33,14 @@ namespace FurnitureAssemFileImplement
public void SaveFurnitures() => SaveData(Furnitures, FurnitureFileName, "Furnitures", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Furnitures = LoadData(FurnitureFileName, "Furniture", x => Furniture.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

View File

@ -0,0 +1,145 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemFileImplement.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.Equals(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 =>
(model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName))?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Shops.Remove(element);
source.SaveShops();
return element.GetViewModel;
}
return null;
}
private int GetCountFurnitureAllShops(FurnitureBindingModel furniture)
{
int count = 0;
foreach (var shop in source.Shops)
{
if (shop.Furnitures.ContainsKey(furniture.Id))
{
count += shop.Furnitures[furniture.Id].Item2;
}
}
return count;
}
public bool Sell(FurnitureBindingModel furniture, int count)
{
if (GetCountFurnitureAllShops(furniture) < count)
{
return false;
}
foreach (var shop in source.Shops)
{
if (shop.Furnitures.ContainsKey(furniture.Id))
{
if (shop.Furnitures[furniture.Id].Item2 > count)
{
shop.Furnitures[furniture.Id] = (shop.Furnitures[furniture.Id].Item1, shop.Furnitures[furniture.Id].Item2 - count);
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
MaxCount = shop.MaxCount,
Furnitures = shop.Furnitures,
Address = shop.Address,
DateOpening = shop.DateOpening,
});
break;
}
count -= shop.Furnitures[furniture.Id].Item2;
shop.Furnitures[furniture.Id] = (shop.Furnitures[furniture.Id].Item1, 0);
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
MaxCount = shop.MaxCount,
Furnitures = shop.Furnitures,
Address = shop.Address,
DateOpening = shop.DateOpening,
});
}
}
source.SaveShops();
return true;
}
}
}

View File

@ -0,0 +1,115 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyDataModels.Models;
using FurnitureAssemblyContracts.ViewModels;
using System.Xml.Linq;
using System.Diagnostics;
namespace FurnitureAssemFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
private Dictionary<int, (IFurnitureModel, int)>? _furnitures = null;
public Dictionary<int, (IFurnitureModel, int)> Furnitures
{
get
{
if (_furnitures == null)
{
var source = DataFileSingleton.GetInstance();
_furnitures = CurrentCount.ToDictionary(
x => x.Key,
y => (source.Furnitures.FirstOrDefault(z => z.Id == y.Key)! as IFurnitureModel, y.Value));
}
return _furnitures;
}
private set { }
}
public int MaxCount { get; private set; }
public Dictionary<int, int> CurrentCount { get; private set; } = new();
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
MaxCount = model.MaxCount,
CurrentCount = model.Furnitures.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
MaxCount = Convert.ToInt32(element.Element("MaxCount")!.Value),
CurrentCount = element.Element("CurrentCount")!.Elements("CurrentCountFurniture")
.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;
Address = model.Address;
MaxCount = model.MaxCount;
DateOpening = model.DateOpening;
if (model.Furnitures.Count > 0)
{
CurrentCount = model.Furnitures.ToDictionary(x => x.Key, x => x.Value.Item2);
_furnitures = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
MaxCount = MaxCount,
Furnitures = Furnitures
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening),
new XElement("MaxCount", MaxCount),
new XElement("CurrentCount",
CurrentCount.Select(
x => new XElement("CurrentCountFurniture", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()));
}
}

View File

@ -19,7 +19,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FurnitureAssemblyDatabaseIm
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FurnitureAssemblyRestApi", "FurnitureAssemblyRestApi\FurnitureAssemblyRestApi.csproj", "{2BA2B5A8-DE7B-4E6F-A84A-04FD7566CE97}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyClientApp", "FurnitureAssemblyClientApp\FurnitureAssemblyClientApp.csproj", "{01C17D7C-CA7C-48F7-98CC-8A658F3A7DD8}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FurnitureAssemblyClientApp", "FurnitureAssemblyClientApp\FurnitureAssemblyClientApp.csproj", "{01C17D7C-CA7C-48F7-98CC-8A658F3A7DD8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FurnitureAssemblyShopWorkApp", "FurnitureAssemblyShopWorkApp\FurnitureAssemblyShopWorkApp.csproj", "{7BD27F0D-4FDC-4CC3-A748-5476B831AA80}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -63,6 +65,10 @@ Global
{01C17D7C-CA7C-48F7-98CC-8A658F3A7DD8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{01C17D7C-CA7C-48F7-98CC-8A658F3A7DD8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{01C17D7C-CA7C-48F7-98CC-8A658F3A7DD8}.Release|Any CPU.Build.0 = Release|Any CPU
{7BD27F0D-4FDC-4CC3-A748-5476B831AA80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7BD27F0D-4FDC-4CC3-A748-5476B831AA80}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7BD27F0D-4FDC-4CC3-A748-5476B831AA80}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7BD27F0D-4FDC-4CC3-A748-5476B831AA80}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -38,11 +38,17 @@
this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.компонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.изделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.магазиныToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.пополнениеМагазинаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ClientsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.отчетыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FurnituresToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.FurnituresComponentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ShopsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ShopsFurnituresToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.OrderDateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonSell = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
@ -110,6 +116,7 @@
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникиToolStripMenuItem,
this.пополнениеМагазинаToolStripMenuItem,
this.отчетыToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
@ -122,6 +129,8 @@
this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.компонентыToolStripMenuItem,
this.изделияToolStripMenuItem,
this.магазиныToolStripMenuItem,
this.изделияToolStripMenuItem,
this.ClientsMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(94, 20);
@ -141,6 +150,20 @@
this.изделияToolStripMenuItem.Text = "Изделия";
this.изделияToolStripMenuItem.Click += new System.EventHandler(this.ИзделияToolStripMenuItem_Click);
//
// магазиныToolStripMenuItem
//
this.магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
this.магазиныToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
this.магазиныToolStripMenuItem.Text = "Магазины";
this.магазиныToolStripMenuItem.Click += new System.EventHandler(this.ShopsToolStripMenuItem_Click);
//
// пополнениеМагазинаToolStripMenuItem
//
this.пополнениеМагазинаToolStripMenuItem.Name = "пополнениеМагазинаToolStripMenuItem";
this.пополнениеМагазинаToolStripMenuItem.Size = new System.Drawing.Size(143, 20);
this.пополнениеМагазинаToolStripMenuItem.Text = "Пополнение магазина";
this.пополнениеМагазинаToolStripMenuItem.Click += new System.EventHandler(this.ReplenishmentToolStripMenuItem_Click);
//
// ClientsMenuItem
//
this.ClientsMenuItem.Name = "ClientsMenuItem";
@ -153,7 +176,10 @@
this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.FurnituresToolStripMenuItem,
this.FurnituresComponentsToolStripMenuItem,
this.списокЗаказовToolStripMenuItem});
this.списокЗаказовToolStripMenuItem,
this.ShopsToolStripMenuItem,
this.ShopsFurnituresToolStripMenuItem,
this.OrderDateToolStripMenuItem});
this.отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(60, 20);
this.отчетыToolStripMenuItem.Text = "Отчеты";
@ -179,11 +205,43 @@
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click);
//
// ShopsToolStripMenuItem
//
this.ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem";
this.ShopsToolStripMenuItem.Size = new System.Drawing.Size(216, 22);
this.ShopsToolStripMenuItem.Text = "Список магазинов";
this.ShopsToolStripMenuItem.Click += new System.EventHandler(this.ShopsToolStripMenuItem_Click_1);
//
// ShopsFurnituresToolStripMenuItem
//
this.ShopsFurnituresToolStripMenuItem.Name = "ShopsFurnituresToolStripMenuItem";
this.ShopsFurnituresToolStripMenuItem.Size = new System.Drawing.Size(216, 22);
this.ShopsFurnituresToolStripMenuItem.Text = "Изделия в магазинах";
this.ShopsFurnituresToolStripMenuItem.Click += new System.EventHandler(this.ShopsFurnituresToolStripMenuItem_Click);
//
// OrderDateToolStripMenuItem
//
this.OrderDateToolStripMenuItem.Name = "OrderDateToolStripMenuItem";
this.OrderDateToolStripMenuItem.Size = new System.Drawing.Size(216, 22);
this.OrderDateToolStripMenuItem.Text = "Список заказов по датам";
this.OrderDateToolStripMenuItem.Click += new System.EventHandler(this.OrderDateToolStripMenuItem_Click);
//
// buttonSell
//
this.buttonSell.Location = new System.Drawing.Point(902, 324);
this.buttonSell.Name = "buttonSell";
this.buttonSell.Size = new System.Drawing.Size(150, 25);
this.buttonSell.TabIndex = 7;
this.buttonSell.Text = "Продажа мебели";
this.buttonSell.UseVisualStyleBackColor = true;
this.buttonSell.Click += new System.EventHandler(this.buttonSell_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1065, 450);
this.Controls.Add(this.buttonSell);
this.Controls.Add(this.ButtonRef);
this.Controls.Add(this.ButtonIssuedOrder);
this.Controls.Add(this.ButtonOrderReady);
@ -219,6 +277,12 @@
private ToolStripMenuItem FurnituresToolStripMenuItem;
private ToolStripMenuItem FurnituresComponentsToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem пополнениеМагазинаToolStripMenuItem;
private Button buttonSell;
private ToolStripMenuItem ShopsToolStripMenuItem;
private ToolStripMenuItem ShopsFurnituresToolStripMenuItem;
private ToolStripMenuItem OrderDateToolStripMenuItem;
private ToolStripMenuItem ClientsMenuItem;
}
}

View File

@ -18,11 +18,14 @@ namespace FurnitureAssembly
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
private readonly IReportLogic _reportLogic;
private readonly IShopLogic _shopLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IShopLogic shopLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_shopLogic = shopLogic;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
@ -108,8 +111,8 @@ namespace FurnitureAssembly
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'",
id);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
@ -117,6 +120,7 @@ namespace FurnitureAssembly
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
@ -133,8 +137,7 @@ namespace FurnitureAssembly
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'",
id);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
@ -158,6 +161,33 @@ namespace FurnitureAssembly
LoadData();
}
private void ShopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void ReplenishmentToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReplenishmentShop));
if (service is FormReplenishmentShop form)
{
form.ShowDialog();
}
}
private void buttonSell_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSell));
if (service is FormSell form)
{
form.ShowDialog();
}
}
private void FurnituresToolStripMenuItem_Click(object sender, EventArgs
e)
{
@ -192,6 +222,38 @@ namespace FurnitureAssembly
}
}
private void ShopsToolStripMenuItem_Click_1(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveShopsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
private void ShopsFurnituresToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopFurnitures));
if (service is FormReportShopFurnitures form)
{
form.ShowDialog();
}
}
private void OrderDateToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportCountOrdersByPeriod));
if (service is FormReportCountOrdersByPeriod form)
{
form.ShowDialog();
}
}
private void ClientsMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));

View File

@ -0,0 +1,142 @@
namespace FurnitureAssembly
{
partial class FormReplenishmentShop
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.labelShop = new System.Windows.Forms.Label();
this.comboBoxFurniture = new System.Windows.Forms.ComboBox();
this.labelFurniture = new System.Windows.Forms.Label();
this.labelNum = new System.Windows.Forms.Label();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// comboBoxShop
//
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(133, 18);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(296, 23);
this.comboBoxShop.TabIndex = 0;
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(46, 21);
this.labelShop.Name = "labelShop";
this.labelShop.Size = new System.Drawing.Size(54, 15);
this.labelShop.TabIndex = 1;
this.labelShop.Text = "Магазин";
//
// comboBoxFurniture
//
this.comboBoxFurniture.FormattingEnabled = true;
this.comboBoxFurniture.Location = new System.Drawing.Point(133, 62);
this.comboBoxFurniture.Name = "comboBoxFurniture";
this.comboBoxFurniture.Size = new System.Drawing.Size(296, 23);
this.comboBoxFurniture.TabIndex = 2;
//
// labelFurniture
//
this.labelFurniture.AutoSize = true;
this.labelFurniture.Location = new System.Drawing.Point(46, 65);
this.labelFurniture.Name = "labelFurniture";
this.labelFurniture.Size = new System.Drawing.Size(53, 15);
this.labelFurniture.TabIndex = 4;
this.labelFurniture.Text = "Изделие";
//
// labelNum
//
this.labelNum.AutoSize = true;
this.labelNum.Location = new System.Drawing.Point(46, 106);
this.labelNum.Name = "labelNum";
this.labelNum.Size = new System.Drawing.Size(72, 15);
this.labelNum.TabIndex = 5;
this.labelNum.Text = "Количество";
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(194, 161);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(99, 29);
this.buttonAdd.TabIndex = 6;
this.buttonAdd.Text = "Пополнить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(330, 161);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(99, 29);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(133, 103);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(160, 23);
this.textBoxCount.TabIndex = 8;
//
// FormReplenishmentShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(479, 214);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.labelNum);
this.Controls.Add(this.labelFurniture);
this.Controls.Add(this.comboBoxFurniture);
this.Controls.Add(this.labelShop);
this.Controls.Add(this.comboBoxShop);
this.Name = "FormReplenishmentShop";
this.Text = "Пополнение магазина";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComboBox comboBoxShop;
private Label labelShop;
private ComboBox comboBoxFurniture;
private Label labelFurniture;
private Label labelNum;
private Button buttonAdd;
private Button buttonCancel;
private TextBox textBoxCount;
}
}

View File

@ -0,0 +1,128 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections;
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 FurnitureAssembly
{
public partial class FormReplenishmentShop : Form
{
private readonly List<ShopViewModel>? _listShops;
private readonly List<FurnitureViewModel>? _listFurnitures;
private IShopLogic _shopLogic;
private ILogger _logger;
public int Id
{
get
{
return Convert.ToInt32(comboBoxShop.SelectedValue);
}
set
{
comboBoxShop.SelectedValue = value;
}
}
public int FurnitureId
{
get
{
return Convert.ToInt32(comboBoxFurniture.SelectedValue);
}
set
{
comboBoxFurniture.SelectedValue = value;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxCount.Text); }
set
{ textBoxCount.Text = value.ToString(); }
}
public FormReplenishmentShop(ILogger<FormReplenishmentShop> logger, IShopLogic shopLogic, IFurnitureLogic furnitureLogic)
{
InitializeComponent();
_logger = logger;
_shopLogic = shopLogic;
_listShops = shopLogic.ReadList(null);
_listFurnitures = furnitureLogic.ReadList(null);
if (_listShops != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = _listShops;
comboBoxShop.SelectedItem = null;
}
if (_listFurnitures != null)
{
comboBoxFurniture.DisplayMember = "FurnitureName";
comboBoxFurniture.ValueMember = "Id";
comboBoxFurniture.DataSource = _listFurnitures;
comboBoxFurniture.SelectedItem = null;
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxFurniture.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Укажите количество поступившего изделия", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
_logger.LogInformation("Добавление в магазин с id = {ShopName} изделия: id = { FurnitureName} - { Count}", Id, FurnitureId, Count);
var operationResult = _shopLogic.AddFurniture(new ShopBindingModel { Id = Id }, new FurnitureBindingModel { Id = FurnitureId }, Count);
if (!operationResult)
{
throw new Exception("Ошибка при пополнении магазина. Дополнительная информация в логах.");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при пополнении магазина c id = " + Id);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
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,118 @@
namespace FurnitureAssembly
{
partial class FormReportCountOrdersByPeriod
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel = new System.Windows.Forms.Panel();
this.buttonMake_Pdf = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.buttonToPdf = new System.Windows.Forms.Button();
this.buttonMake = new System.Windows.Forms.Button();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonMake_Pdf);
this.panel.Controls.Add(this.button1);
this.panel.Controls.Add(this.buttonToPdf);
this.panel.Controls.Add(this.buttonMake);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(987, 40);
this.panel.TabIndex = 2;
//
// buttonMake_Pdf
//
this.buttonMake_Pdf.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonMake_Pdf.Location = new System.Drawing.Point(826, 8);
this.buttonMake_Pdf.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.buttonMake_Pdf.Name = "buttonMake_Pdf";
this.buttonMake_Pdf.Size = new System.Drawing.Size(139, 27);
this.buttonMake_Pdf.TabIndex = 7;
this.buttonMake_Pdf.Text = "В Pdf";
this.buttonMake_Pdf.UseVisualStyleBackColor = true;
this.buttonMake_Pdf.Click += new System.EventHandler(this.ButtonToPdf_Click);
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(1564, 8);
this.button1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(139, 27);
this.button1.TabIndex = 6;
this.button1.Text = "В Pdf";
this.button1.UseVisualStyleBackColor = true;
//
// buttonToPdf
//
this.buttonToPdf.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonToPdf.Location = new System.Drawing.Point(2452, 8);
this.buttonToPdf.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.buttonToPdf.Name = "buttonToPdf";
this.buttonToPdf.Size = new System.Drawing.Size(139, 27);
this.buttonToPdf.TabIndex = 5;
this.buttonToPdf.Text = "В Pdf";
this.buttonToPdf.UseVisualStyleBackColor = true;
//
// buttonMake
//
this.buttonMake.Location = new System.Drawing.Point(476, 8);
this.buttonMake.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.buttonMake.Name = "buttonMake";
this.buttonMake.Size = new System.Drawing.Size(139, 27);
this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true;
this.buttonMake.Click += new System.EventHandler(this.buttonMake_Click);
//
// FormReportCountOrdersByPeriod
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(987, 596);
this.Controls.Add(this.panel);
this.Name = "FormReportCountOrdersByPeriod";
this.Text = "Заказы по датам";
this.panel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Panel panel;
private Button button1;
private Button buttonToPdf;
private Button buttonMake;
private Button buttonMake_Pdf;
}
}

View File

@ -0,0 +1,83 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FurnitureAssembly
{
public partial class FormReportCountOrdersByPeriod : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportCountOrdersByPeriod(ILogger<FormReportCountOrdersByPeriod> logger, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_logic = reportLogic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrdersCount.rdlc", FileMode.Open)); // другой файл
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void buttonMake_Click(object sender, EventArgs e)
{
try
{
var dataSource = _logic.GetCountOrders();
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов, объединенных по дате");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonToPdf_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveCountOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка заказов");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,104 @@
namespace FurnitureAssembly
{
partial class FormReportShopFurnitures
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ButtonSaveToExcel = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.Shop = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Furniture = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// ButtonSaveToExcel
//
this.ButtonSaveToExcel.Location = new System.Drawing.Point(12, 22);
this.ButtonSaveToExcel.Name = "ButtonSaveToExcel";
this.ButtonSaveToExcel.Size = new System.Drawing.Size(166, 27);
this.ButtonSaveToExcel.TabIndex = 1;
this.ButtonSaveToExcel.Text = "Сохранить в Excel";
this.ButtonSaveToExcel.UseVisualStyleBackColor = true;
this.ButtonSaveToExcel.Click += new System.EventHandler(this.ButtonSaveToExcel_Click);
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Shop,
this.Furniture,
this.Count});
this.dataGridView.Location = new System.Drawing.Point(12, 80);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(600, 358);
this.dataGridView.TabIndex = 2;
//
// Shop
//
this.Shop.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Shop.HeaderText = "Магазин";
this.Shop.Name = "Shop";
//
// Furniture
//
this.Furniture.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Furniture.HeaderText = "Изделие";
this.Furniture.Name = "Furniture";
//
// Count
//
this.Count.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.ColumnHeader;
this.Count.HeaderText = "Количество";
this.Count.Name = "Count";
this.Count.Width = 97;
//
// FormReportShopFurnitures
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(627, 450);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.ButtonSaveToExcel);
this.Name = "FormReportShopFurnitures";
this.Text = "Магазины с изделиями";
this.Load += new System.EventHandler(this.FormReportShopFurnitures_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button ButtonSaveToExcel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn Shop;
private DataGridViewTextBoxColumn Furniture;
private DataGridViewTextBoxColumn Count;
}
}

View File

@ -0,0 +1,87 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
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 FurnitureAssembly
{
public partial class FormReportShopFurnitures : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShopFurnitures(ILogger<FormReportShopFurnitures> logger, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_logic = reportLogic;
}
private void ButtonSaveToExcel_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog
{
Filter = "xlsx|*.xlsx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveShopFurnituresToExcelFile(new
ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка магазинов с изделиями в них");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка магазинов с изделиями в них");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void FormReportShopFurnitures_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShopFurnitures();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" });
foreach (var listElem in elem.Furnitures)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка магазинов с изделиями в них");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка магазинов с изделиями в них");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,78 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="Shop.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Furniture.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Shop.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Furniture.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.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 FurnitureAssembly
{
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()
{
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSell = new System.Windows.Forms.Button();
this.labelNum = new System.Windows.Forms.Label();
this.labelFurniture = new System.Windows.Forms.Label();
this.comboBoxFurniture = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(135, 84);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(160, 23);
this.textBoxCount.TabIndex = 14;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(332, 142);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(99, 29);
this.buttonCancel.TabIndex = 13;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSell
//
this.buttonSell.Location = new System.Drawing.Point(196, 142);
this.buttonSell.Name = "buttonSell";
this.buttonSell.Size = new System.Drawing.Size(99, 29);
this.buttonSell.TabIndex = 12;
this.buttonSell.Text = "Продать";
this.buttonSell.UseVisualStyleBackColor = true;
this.buttonSell.Click += new System.EventHandler(this.buttonSell_Click);
//
// labelNum
//
this.labelNum.AutoSize = true;
this.labelNum.Location = new System.Drawing.Point(48, 87);
this.labelNum.Name = "labelNum";
this.labelNum.Size = new System.Drawing.Size(72, 15);
this.labelNum.TabIndex = 11;
this.labelNum.Text = "Количество";
//
// labelFurniture
//
this.labelFurniture.AutoSize = true;
this.labelFurniture.Location = new System.Drawing.Point(48, 46);
this.labelFurniture.Name = "labelFurniture";
this.labelFurniture.Size = new System.Drawing.Size(53, 15);
this.labelFurniture.TabIndex = 10;
this.labelFurniture.Text = "Изделие";
//
// comboBoxFurniture
//
this.comboBoxFurniture.FormattingEnabled = true;
this.comboBoxFurniture.Location = new System.Drawing.Point(135, 43);
this.comboBoxFurniture.Name = "comboBoxFurniture";
this.comboBoxFurniture.Size = new System.Drawing.Size(296, 23);
this.comboBoxFurniture.TabIndex = 9;
//
// FormSell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(479, 214);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSell);
this.Controls.Add(this.labelNum);
this.Controls.Add(this.labelFurniture);
this.Controls.Add(this.comboBoxFurniture);
this.Name = "FormSell";
this.Text = "Продажа мебели";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxCount;
private Button buttonCancel;
private Button buttonSell;
private Label labelNum;
private Label labelFurniture;
private ComboBox comboBoxFurniture;
}
}

View File

@ -0,0 +1,117 @@
using FurnitureAssemblyBusinessLogic;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FurnitureAssembly
{
public partial class FormSell : Form
{
private readonly IShopLogic _shopLogic;
private readonly List<FurnitureViewModel>? _listFurnitures;
public int Id
{
get
{
return Convert.ToInt32(comboBoxFurniture.SelectedValue);
}
set
{
comboBoxFurniture.SelectedValue = value;
}
}
public IFurnitureModel? FurnitureModel
{
get
{
if (_listFurnitures == null)
{
return null;
}
foreach (var elem in _listFurnitures)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get
{
return Convert.ToInt32(textBoxCount.Text);
}
set
{
textBoxCount.Text = value.ToString();
}
}
public FormSell(IShopLogic shopLogic, IFurnitureLogic furnitureLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_listFurnitures = furnitureLogic.ReadList(null);
if (_listFurnitures != null)
{
comboBoxFurniture.DisplayMember = "FurnitureName";
comboBoxFurniture.ValueMember = "Id";
comboBoxFurniture.DataSource = _listFurnitures;
comboBoxFurniture.SelectedItem = null;
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void buttonSell_Click(object sender, EventArgs e)
{
if (FurnitureModel == null)
{
MessageBox.Show("Выберите изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (Count <= 0)
{
MessageBox.Show("Укажите количество изделия", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_shopLogic.Sell(new() { Id = FurnitureModel.Id }, Count))
{
MessageBox.Show("Не удалось продать изделие " + FurnitureModel.FurnitureName, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("Продажа прошла успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
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,203 @@
namespace FurnitureAssembly
{
partial class FormShop
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelShopName = new System.Windows.Forms.Label();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.labelAddress = new System.Windows.Forms.Label();
this.labelDate = new System.Windows.Forms.Label();
this.dateTimePicker = new System.Windows.Forms.DateTimePicker();
this.ButtonSave = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.FurnitureId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.FurnitureName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.textBoxMaxCount = new System.Windows.Forms.TextBox();
this.labelMaxCount = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// labelShopName
//
this.labelShopName.AutoSize = true;
this.labelShopName.Location = new System.Drawing.Point(35, 22);
this.labelShopName.Name = "labelShopName";
this.labelShopName.Size = new System.Drawing.Size(113, 15);
this.labelShopName.TabIndex = 0;
this.labelShopName.Text = "Название магазина";
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(166, 19);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(282, 23);
this.textBoxName.TabIndex = 1;
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(166, 60);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(282, 23);
this.textBoxAddress.TabIndex = 3;
//
// labelAddress
//
this.labelAddress.AutoSize = true;
this.labelAddress.Location = new System.Drawing.Point(35, 63);
this.labelAddress.Name = "labelAddress";
this.labelAddress.Size = new System.Drawing.Size(40, 15);
this.labelAddress.TabIndex = 2;
this.labelAddress.Text = "Адрес";
//
// labelDate
//
this.labelDate.AutoSize = true;
this.labelDate.Location = new System.Drawing.Point(35, 105);
this.labelDate.Name = "labelDate";
this.labelDate.Size = new System.Drawing.Size(87, 15);
this.labelDate.TabIndex = 4;
this.labelDate.Text = "Дата открытия";
//
// dateTimePicker
//
this.dateTimePicker.Location = new System.Drawing.Point(166, 99);
this.dateTimePicker.Name = "dateTimePicker";
this.dateTimePicker.Size = new System.Drawing.Size(282, 23);
this.dateTimePicker.TabIndex = 6;
//
// ButtonSave
//
this.ButtonSave.Location = new System.Drawing.Point(382, 490);
this.ButtonSave.Name = "ButtonSave";
this.ButtonSave.Size = new System.Drawing.Size(99, 28);
this.ButtonSave.TabIndex = 7;
this.ButtonSave.Text = "Сохранить";
this.ButtonSave.UseVisualStyleBackColor = true;
this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(509, 490);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(99, 28);
this.ButtonCancel.TabIndex = 8;
this.ButtonCancel.Text = "Отмена";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.FurnitureId,
this.FurnitureName,
this.Count});
this.dataGridView1.Location = new System.Drawing.Point(37, 177);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowTemplate.Height = 25;
this.dataGridView1.Size = new System.Drawing.Size(571, 289);
this.dataGridView1.TabIndex = 9;
//
// FurnitureId
//
this.FurnitureId.HeaderText = "Id";
this.FurnitureId.Name = "FurnitureId";
this.FurnitureId.Visible = false;
//
// FurnitureName
//
this.FurnitureName.HeaderText = "Название";
this.FurnitureName.Name = "FurnitureName";
//
// Count
//
this.Count.HeaderText = "Количество";
this.Count.Name = "Count";
//
// textBoxMaxCount
//
this.textBoxMaxCount.Location = new System.Drawing.Point(166, 138);
this.textBoxMaxCount.Name = "textBoxMaxCount";
this.textBoxMaxCount.Size = new System.Drawing.Size(282, 23);
this.textBoxMaxCount.TabIndex = 11;
//
// labelMaxCount
//
this.labelMaxCount.AutoSize = true;
this.labelMaxCount.Location = new System.Drawing.Point(35, 141);
this.labelMaxCount.Name = "labelMaxCount";
this.labelMaxCount.Size = new System.Drawing.Size(80, 15);
this.labelMaxCount.TabIndex = 10;
this.labelMaxCount.Text = "Вместимость";
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(631, 530);
this.Controls.Add(this.textBoxMaxCount);
this.Controls.Add(this.labelMaxCount);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.ButtonSave);
this.Controls.Add(this.dateTimePicker);
this.Controls.Add(this.labelDate);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.labelAddress);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.labelShopName);
this.Name = "FormShop";
this.Text = "Магазин";
this.Load += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelShopName;
private TextBox textBoxName;
private TextBox textBoxAddress;
private Label labelAddress;
private Label labelDate;
private DateTimePicker dateTimePicker;
private Button ButtonSave;
private Button ButtonCancel;
private DataGridView dataGridView1;
private DataGridViewTextBoxColumn FurnitureId;
private DataGridViewTextBoxColumn FurnitureName;
private DataGridViewTextBoxColumn Count;
private TextBox textBoxMaxCount;
private Label labelMaxCount;
}
}

View File

@ -0,0 +1,143 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyDataModels.Models;
using Microsoft.Extensions.Logging;
namespace FurnitureAssembly
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
private Dictionary<int, (IFurnitureModel, int)> _shopFurnitures;
private int? _id;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopFurnitures = new Dictionary<int, (IFurnitureModel, int)>();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(dateTimePicker.Text))
{
MessageBox.Show("Заполните дату открытия", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (Convert.ToInt32(textBoxMaxCount.Text) <= 0)
{
MessageBox.Show("Некорректная вместимость", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
MaxCount = Convert.ToInt32(textBoxMaxCount.Text),
DateOpening = dateTimePicker.Value
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение магазина");
var view = _logic.ReadElement(new ShopSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address.ToString();
dateTimePicker.Value = view.DateOpening;
textBoxMaxCount.Text = view.MaxCount.ToString();
_shopFurnitures = view.Furnitures ?? new
Dictionary<int, (IFurnitureModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонент изделия");
try
{
if (_shopFurnitures != null)
{
dataGridView1.Rows.Clear();
foreach (var pc in _shopFurnitures)
{
dataGridView1.Rows.Add(new object[] { pc.Key, pc.Value.Item1.FurnitureName, pc.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонент изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}

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="FurnitureId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="FurnitureName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,114 @@
namespace FurnitureAssembly
{
partial class FormShops
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ButtonRef = new System.Windows.Forms.Button();
this.ButtonUpd = new System.Windows.Forms.Button();
this.ButtonDel = new System.Windows.Forms.Button();
this.ButtonAdd = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(-1, -1);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(559, 453);
this.dataGridView.TabIndex = 6;
//
// ButtonRef
//
this.ButtonRef.Location = new System.Drawing.Point(601, 223);
this.ButtonRef.Name = "ButtonRef";
this.ButtonRef.Size = new System.Drawing.Size(105, 29);
this.ButtonRef.TabIndex = 13;
this.ButtonRef.Text = "Обновить";
this.ButtonRef.UseVisualStyleBackColor = true;
this.ButtonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// ButtonUpd
//
this.ButtonUpd.Location = new System.Drawing.Point(601, 168);
this.ButtonUpd.Name = "ButtonUpd";
this.ButtonUpd.Size = new System.Drawing.Size(105, 29);
this.ButtonUpd.TabIndex = 12;
this.ButtonUpd.Text = "Изменить";
this.ButtonUpd.UseVisualStyleBackColor = true;
this.ButtonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// ButtonDel
//
this.ButtonDel.Location = new System.Drawing.Point(601, 113);
this.ButtonDel.Name = "ButtonDel";
this.ButtonDel.Size = new System.Drawing.Size(105, 29);
this.ButtonDel.TabIndex = 11;
this.ButtonDel.Text = "Удалить";
this.ButtonDel.UseVisualStyleBackColor = true;
this.ButtonDel.Click += new System.EventHandler(this.ButtonDel_Click);
//
// ButtonAdd
//
this.ButtonAdd.Location = new System.Drawing.Point(601, 59);
this.ButtonAdd.Name = "ButtonAdd";
this.ButtonAdd.Size = new System.Drawing.Size(105, 29);
this.ButtonAdd.TabIndex = 10;
this.ButtonAdd.Text = "Добавить";
this.ButtonAdd.UseVisualStyleBackColor = true;
this.ButtonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// FormShops
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(743, 451);
this.Controls.Add(this.ButtonRef);
this.Controls.Add(this.ButtonUpd);
this.Controls.Add(this.ButtonDel);
this.Controls.Add(this.ButtonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormShops";
this.Text = "Магазины";
this.Load += new System.EventHandler(this.FormShops_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button ButtonRef;
private Button ButtonUpd;
private Button ButtonDel;
private Button ButtonAdd;
}
}

View File

@ -0,0 +1,109 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using Microsoft.Extensions.Logging;
namespace FurnitureAssembly
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["Furnitures"].Visible = false;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление магазина");
try
{
if (!_logic.Delete(new ShopBindingModel{ Id = id}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -11,6 +11,7 @@
<ItemGroup>
<None Remove="nlog.config" />
<None Remove="ReportOrders.rdlc" />
<None Remove="ReportOrdersCount.rdlc" />
</ItemGroup>
<ItemGroup>
@ -20,6 +21,9 @@
<EmbeddedResource Include="ReportOrders.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
<EmbeddedResource Include="ReportOrdersCount.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>

View File

@ -40,6 +40,7 @@ namespace FurnitureAssembly
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IFurnitureStorage, FurnitureStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
@ -53,6 +54,7 @@ namespace FurnitureAssembly
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
@ -62,6 +64,12 @@ namespace FurnitureAssembly
services.AddTransient<FormFurnitures>();
services.AddTransient<FormReportFurnitureComponents>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormReplenishmentShop>();
services.AddTransient<FormSell>();
services.AddTransient<FormReportShopFurnitures>();
services.AddTransient<FormReportCountOrdersByPeriod>();
services.AddTransient<FormClients>();
}
}

View File

@ -0,0 +1,459 @@
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<AutoRefresh>0</AutoRefresh>
<DataSources>
<DataSource Name="FurnitureAssemblyContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>10791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetOrders">
<Query>
<DataSourceName>FurnitureAssemblyContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="DateCreate">
<DataField>DateCreate</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="CountOrders">
<DataField>CountOrders</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
<Field Name="TotalSumOrders">
<DataField>TotalSumOrders</DataField>
<rd:TypeName>System.Double</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>FurnitureAssemblyContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportCountOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>FurnitureAssemblyContracts.ViewModels.ReportCountOrdersViewModel, FurnitureAssemblyContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="ReportParameterPeriod">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Parameters!ReportParameterPeriod.Value</Value>
<Style>
<FontSize>14pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<rd:DefaultName>ReportParameterPeriod</rd:DefaultName>
<Top>1cm</Top>
<Height>1cm</Height>
<Width>21cm</Width>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Заказы</Value>
<Style>
<FontSize>16pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>1cm</Height>
<Width>21cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>3cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3cm</Width>
</TablixColumn>
<TablixColumn>
<Width>7cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Textbox1">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата создания</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox1</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox3">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Количество заказов</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox3</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox2">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Сумма</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox2</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="DateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!DateCreate.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>DateCreate</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="CountOrders">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!CountOrders.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>CountOrders</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="TotalSumOrders">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!TotalSumOrders.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>TotalSumOrders</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
<TablixColumnHierarchy>
<TablixMembers>
<TablixMember />
<TablixMember />
<TablixMember />
</TablixMembers>
</TablixColumnHierarchy>
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
</TablixMember>
<TablixMember>
<Group Name="Подробности" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
<DataSetName>DataSetOrders</DataSetName>
<Top>2.48391cm</Top>
<Left>0.55245cm</Left>
<Height>1.2cm</Height>
<Width>19.84713cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>Double</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxTotalSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Итого:</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>15.39958cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>3</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="SumTotal">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!TotalSumOrders.Value, "DataSetOrders")</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>17.89958cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>4</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</ReportItems>
<Height>5.72875cm</Height>
<Style />
</Body>
<Width>21cm</Width>
<Page>
<PageHeight>29.7cm</PageHeight>
<PageWidth>21cm</PageWidth>
<LeftMargin>2cm</LeftMargin>
<RightMargin>2cm</RightMargin>
<TopMargin>2cm</TopMargin>
<BottomMargin>2cm</BottomMargin>
<ColumnSpacing>0.13cm</ColumnSpacing>
<Style />
</Page>
</ReportSection>
</ReportSections>
<ReportParameters>
<ReportParameter Name="ReportParameterPeriod">
<DataType>String</DataType>
<Nullable>true</Nullable>
<Prompt>ReportParameter1</Prompt>
</ReportParameter>
</ReportParameters>
<ReportParametersLayout>
<GridLayoutDefinition>
<NumberOfColumns>4</NumberOfColumns>
<NumberOfRows>2</NumberOfRows>
<CellDefinitions>
<CellDefinition>
<ColumnIndex>0</ColumnIndex>
<RowIndex>0</RowIndex>
<ParameterName>ReportParameterPeriod</ParameterName>
</CellDefinition>
</CellDefinitions>
</GridLayoutDefinition>
</ReportParametersLayout>
<rd:ReportUnitType>Cm</rd:ReportUnitType>
<rd:ReportID>2de0031a-4d17-449d-922d-d9fc54572312</rd:ReportID>
</Report>

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperEnums;
using DocumentFormat.OpenXml.EMMA;
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperEnums;
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
@ -30,6 +31,19 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage
CellToName = "C1"
});
uint rowIndex = 2;
if (info is ExcelInfoFurnitures infoFurnitures)
{
CreateExcelCellsFurnitures(infoFurnitures, rowIndex);
}
else if (info is ExcelInfoShops infoShops)
{
CreateExcelCellsShops(infoShops, rowIndex);
}
SaveExcel(info);
}
private void CreateExcelCellsFurnitures(ExcelInfoFurnitures info, uint rowIndex)
{
foreach (var pc in info.FurnitureComponents)
{
InsertCellInWorksheet(new ExcelCellParameters
@ -76,8 +90,58 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage
});
rowIndex++;
}
SaveExcel(info);
}
private void CreateExcelCellsShops(ExcelInfoShops info, uint rowIndex)
{
foreach (var sF in info.ShopFurnitures)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = sF.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var furniture in sF.Furnitures)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = furniture.Item1,
StyleInfo =
ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = furniture.Item2.ToString(),
StyleInfo =
ExcelStyleInfoType.TextWithBroder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = sF.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
}
/// <summary>
/// Создание excel-файла
/// </summary>

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperEnums;
using DocumentFormat.OpenXml.EMMA;
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperEnums;
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
@ -19,11 +20,25 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
if (info is PdfInfoOrders infoOrders)
{
Text = $"с { info.DateFrom.ToShortDateString() } по { info.DateTo.ToShortDateString() }", Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с { info.DateFrom.ToShortDateString() } по { info.DateTo.ToShortDateString() }",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateDocOrders(infoOrders);
} else if (info is PdfInfoCountOrders countOrders)
{
CreateDocCountOrders(countOrders);
}
SavePdf(info);
}
private void CreateDocOrders(PdfInfoOrders info)
{
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
@ -47,7 +62,33 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage
ParagraphAlignment =
PdfParagraphAlignmentType.Right
});
SavePdf(info);
}
private void CreateDocCountOrders(PdfInfoCountOrders info)
{
CreateTable(new List<string> { "3cm", "3cm", "7cm"});
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата заказа", "Количество заказов", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.CountOrders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.DateCreate.ToShortDateString(), order.CountOrders.ToString(), order.TotalSumOrders.ToString()},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph
{
Text = $"Итого: {info.CountOrders.Sum(x => x.TotalSumOrders)}\t",
Style = "Normal",
ParagraphAlignment =
PdfParagraphAlignmentType.Right
});
}
/// <summary>
/// Создание doc-файла

View File

@ -1,4 +1,5 @@
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperEnums;
using DocumentFormat.OpenXml.EMMA;
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperEnums;
using FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels;
@ -6,6 +7,48 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateTableDoc(WordInfo wordInfo) {
CreateWord(wordInfo);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (wordInfo.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
WordTable wordTable = new();
if (wordInfo is WordInfoShops infoShops)
{
wordTable = CreateTableDocShops(infoShops);
}
CreateTable(wordTable);
SaveWord(wordInfo);
}
private WordTable CreateTableDocShops(WordInfoShops wordInfo)
{
var list = new List<string>();
foreach (var shop in wordInfo.Shops)
{
list.Add(shop.ShopName);
list.Add(shop.Address);
list.Add(shop.DateOpening.ToString());
}
var wordTable = new WordTable
{
Headers = new List<string> {
"Название",
"Адрес",
"Дата открытия"},
Texts = list
};
return wordTable;
}
public void CreateDoc(WordInfo info)
{
CreateWord(info);
@ -18,18 +61,22 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage
JustificationType = WordJustificationType.Center
}
});
foreach (var furniture in info.Furnitures)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (furniture.FurnitureName, new WordTextProperties { Size = "24", Bold=true}), (" - " + furniture.Price.ToString(), new WordTextProperties { Size = "24", }) },
TextProperties = new WordTextProperties
if (info is WordInfoFurnitures infoFurnitures) {
foreach (var furniture in infoFurnitures.Furnitures)
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (furniture.FurnitureName,
new WordTextProperties { Size = "24", Bold=true}), (" - " + furniture.Price.ToString(),
new WordTextProperties { Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
}
SaveWord(info);
}
@ -38,6 +85,7 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage
/// </summary>
/// <param name="info"></param>
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateTable(WordTable info);
/// <summary>
/// Создание абзаца с текстом
/// </summary>

View File

@ -5,11 +5,6 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportFurnitureComponentViewModel> FurnitureComponents
{
get;
set;
} = new();
public string Title { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,18 @@
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfoFurnitures : ExcelInfo
{
public List<ReportFurnitureComponentViewModel> FurnitureComponents
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,18 @@
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfoShops : ExcelInfo
{
public List<ReportShopFurnituresViewModel> ShopFurnitures
{
get;
set;
} = new();
}
}

View File

@ -9,6 +9,5 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
}
}

View File

@ -0,0 +1,14 @@
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfoCountOrders : PdfInfo
{
public List<ReportCountOrdersViewModel> CountOrders { get; set; } = new();
}
}

View File

@ -0,0 +1,14 @@
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfoOrders : PdfInfo
{
public List<ReportOrdersViewModel> Orders { get; set; } = new();
}
}

View File

@ -5,7 +5,6 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<FurnitureViewModel> Furnitures { get; set; } = new();
public string Title { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,14 @@
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
{
public class WordInfoFurnitures : WordInfo
{
public List<FurnitureViewModel> Furnitures { get; set; } = new();
}
}

View File

@ -0,0 +1,14 @@
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
{
public class WordInfoShops : WordInfo
{
public List<ShopViewModel> Shops { get; set; } = new();
}
}

View File

@ -0,0 +1,12 @@

using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels
{
public class WordTable
{
public List<string> Headers { get; set; } = new();
public List<string> Texts { get; set; } = new ();
}
}

View File

@ -3,6 +3,7 @@ using FurnitureAssemblyBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Xml.Linq;
namespace FurnitureAssemblyBusinessLogic.OfficePackage.Implements
{
@ -122,5 +123,86 @@ namespace FurnitureAssemblyBusinessLogic.OfficePackage.Implements
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close();
}
protected override void CreateTable(WordTable table)
{
if (_docBody == null || table == null)
{
return;
}
Table tab = new Table();
TableProperties props = new TableProperties(
new TableBorders(
new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}
)
);
tab.AppendChild<TableProperties>(props);
// разметка сетки таблицы
TableGrid tableGrid = new TableGrid();
for (int i = 0; i < table.Headers.Count; i++) {
tableGrid.AppendChild(new GridColumn ());
}
tab.AppendChild(tableGrid);
TableRow tableRow = new TableRow();
// заполнение заголовков
foreach (var text in table.Headers)
{
tableRow.AppendChild(CreateTableCell(text));
}
tab.AppendChild(tableRow);
// заполнение содержимым
int height = table.Texts.Count / table.Headers.Count;
int width = table.Headers.Count;
for (int i = 0; i < height; i++) {
tableRow = new TableRow();
for (int j = 0; j < width; j++) {
var element = table.Texts[i * table.Headers.Count + j];
tableRow.AppendChild(CreateTableCell(element));
}
tab.AppendChild(tableRow);
}
_docBody.AppendChild(tab);
}
private TableCell CreateTableCell(string element) {
var tableParagraph = new Paragraph();
var run = new Run();
run.AppendChild(new Text { Text = element });
tableParagraph.AppendChild(run);
var tableCell = new TableCell();
tableCell.AppendChild(tableParagraph);
return tableCell;
}
}
}

View File

@ -17,11 +17,13 @@ namespace FurnitureAssemblyBusinessLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopLogic _shopLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
}
private bool ChangeStatus(OrderBindingModel model, OrderStatus orderStatus)
@ -75,6 +77,11 @@ namespace FurnitureAssemblyBusinessLogic
if (model == null) {
return false;
}
if (!_shopLogic.AddFurnituresAtShops(new FurnitureBindingModel() { Id = model.FurnitureId }, model.Count))
{
_logger.LogWarning("There are not empty places at shops. Replenishment is impossible");
return false;
}
if (!ChangeStatus(model, OrderStatus.Готов))
{
_logger.LogWarning("Order's status is wrong");
@ -91,6 +98,7 @@ namespace FurnitureAssemblyBusinessLogic
{
return false;
}
if (!ChangeStatus(model, OrderStatus.Выдан))
{
_logger.LogWarning("Order's status is wrong");
@ -101,7 +109,7 @@ namespace FurnitureAssemblyBusinessLogic
return true;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);

View File

@ -17,17 +17,19 @@ namespace FurnitureAssemblyBusinessLogic
{
private readonly IFurnitureStorage _furnitureStorage;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IFurnitureStorage furnitureStorage, IOrderStorage orderStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf, IShopStorage shopStorage)
{
_furnitureStorage = furnitureStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
_shopStorage = shopStorage;
}
/// <summary>
/// Получение списка компонент с указанием, в каких изделиях используются
@ -82,20 +84,20 @@ namespace FurnitureAssemblyBusinessLogic
/// <param name="model"></param>
public void SaveFurnituresToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
_saveToWord.CreateDoc(new WordInfoFurnitures
{
FileName = model.FileName,
Title = "Список изделий",
Furnitures = _furnitureStorage.GetFullList()
});
}
}
/// <summary>
/// Сохранение компонент с указаеним продуктов в файл-Excel
/// </summary>
/// <param name="model"></param>
public void SaveFurnitureComponentToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
_saveToExcel.CreateReport(new ExcelInfoFurnitures
{
FileName = model.FileName,
Title = "Список изделий",
@ -108,7 +110,7 @@ namespace FurnitureAssemblyBusinessLogic
/// <param name="model"></param>
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
_saveToPdf.CreateDoc(new PdfInfoOrders
{
FileName = model.FileName,
Title = "Список заказов",
@ -117,5 +119,69 @@ namespace FurnitureAssemblyBusinessLogic
Orders = GetOrders(model)
});
}
/// <summary>
/// Сохранение магазинов в файл-Word
/// </summary>
/// <param name="model"></param>
public void SaveShopsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateTableDoc(new WordInfoShops
{
FileName = model.FileName,
Title = "Список магазинов",
Shops = _shopStorage.GetFullList()
});
}
public void SaveShopFurnituresToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfoShops
{
FileName = model.FileName,
Title = "Список магазинов с изделиями",
ShopFurnitures = GetShopFurnitures()
});
}
public List<ReportShopFurnituresViewModel> GetShopFurnitures()
{
var shops = _shopStorage.GetFullList();
var list = new List<ReportShopFurnituresViewModel>();
foreach (var shop in shops)
{
var record = new ReportShopFurnituresViewModel
{
ShopName = shop.ShopName,
Furnitures = new List<Tuple<string, int>>(),
TotalCount = 0
};
foreach (var furnitureCount in shop.Furnitures.Values)
{
record.Furnitures.Add(new Tuple<string, int>(furnitureCount.Item1.FurnitureName, furnitureCount.Item2));
record.TotalCount += furnitureCount.Item2;
}
list.Add(record);
}
return list;
}
public List<ReportCountOrdersViewModel> GetCountOrders()
{
return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportCountOrdersViewModel
{
DateCreate = x.Key,
CountOrders = x.Count(),
TotalSumOrders = x.Sum(y => y.Sum)
}).ToList();
}
public void SaveCountOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfoCountOrders
{
FileName = model.FileName,
Title = "Список объединенных по дате заказов",
CountOrders = GetCountOrders()
});
}
}
}

View File

@ -0,0 +1,212 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
private readonly IFurnitureStorage _furnitureStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage, IFurnitureStorage furnitureStorage)
{
_logger = logger;
_shopStorage = shopStorage;
_furnitureStorage = furnitureStorage;
}
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 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 Update(ShopBindingModel model)
{
CheckModel(model);
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.Address))
{
throw new ArgumentNullException("Нет адреса магазина", nameof(model.Address));
}
if (model.DateOpening.Equals(null))
{
throw new ArgumentNullException("Нет даты открытия магазина", nameof(model.DateOpening));
}
if (model.MaxCount <= 0)
{
throw new ArgumentNullException("Нет вместимости магазина", nameof(model.DateOpening));
}
_logger.LogInformation("Shop. ShopName:{ShopName}. Address:{ Address}. DateOpening:{ DateOpening}. Id: { Id}", model.ShopName, model.Address, model.DateOpening, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel { ShopName = model.ShopName });
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool AddFurniture(ShopBindingModel model, FurnitureBindingModel furnitureModel, int count)
{
var shop = _shopStorage.GetElement(new ShopSearchModel { Id = model.Id });
var furniture = _furnitureStorage.GetElement(new FurnitureSearchModel { Id = furnitureModel.Id });
if (shop == null || furniture == null)
{
return false;
}
if (GetCountFreePlaces(model.Id) < count)
{
return false;
}
if (shop.Furnitures.ContainsKey(furniture.Id))
{
int prev_count = shop.Furnitures[furniture.Id].Item2;
shop.Furnitures[furniture.Id] = (furniture, prev_count + count);
}
else
{
shop.Furnitures[furniture.Id] = (furniture, count);
}
model.Furnitures = shop.Furnitures;
model.DateOpening = shop.DateOpening;
model.MaxCount = shop.MaxCount;
model.Address = shop.Address;
model.ShopName = shop.ShopName;
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Replenishment operation failed");
return false;
}
return true;
}
private int GetCountFreePlaces(int ShopId)
{
var shop = ReadElement(new ShopSearchModel { Id = ShopId });
if (shop == null)
return 0;
int count = shop.MaxCount;
foreach (var f in shop.Furnitures)
{
count -= f.Value.Item2;
if (count <= 0)
{
return 0;
}
}
return count;
}
private int GetCountFreePlaces_All()
{
return _shopStorage.GetFullList().Select(x => GetCountFreePlaces(x.Id)).Sum();
}
public bool AddFurnituresAtShops(FurnitureBindingModel furnitureModel, int count)
{
if (GetCountFreePlaces_All() < count)
{
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
int countShop = GetCountFreePlaces(shop.Id);
if (countShop >= count)
{
AddFurniture(new() { Id = shop.Id }, furnitureModel, count);
break;
}
else
{
AddFurniture(new() { Id = shop.Id }, furnitureModel, countShop);
}
count -= countShop;
}
return true;
}
public bool Sell(FurnitureBindingModel furnitureBindingModel, int count)
{
return _shopStorage.Sell(furnitureBindingModel, count);
}
}
}

View File

@ -0,0 +1,25 @@
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime DateOpening { get; set; }
public Dictionary<int, (IFurnitureModel, int)> Furnitures { get; set; } = new();
public int MaxCount { get; set; }
}
}

View File

@ -31,5 +31,15 @@ namespace FurnitureAssemblyContracts.BusinessLogicsContarcts
/// </summary>
/// <param name="model"></param>
void SaveOrdersToPdfFile(ReportBindingModel model);
void SaveShopsToWordFile(ReportBindingModel model);
void SaveShopFurnituresToExcelFile(ReportBindingModel model);
List<ReportShopFurnituresViewModel> GetShopFurnitures();
/// <summary>
/// Получение объединенных по дате заказов за определенный период
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
List<ReportCountOrdersViewModel> GetCountOrders();
void SaveCountOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BusinessLogicsContarcts
{
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 AddFurniture(ShopBindingModel model, FurnitureBindingModel furnitureModel, int count);
bool AddFurnituresAtShops(FurnitureBindingModel furnitureModel, int count);
bool Sell(FurnitureBindingModel furnitureModel, int count);
}
}

View File

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

View File

@ -0,0 +1,19 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyContracts.StoragesContracts
{
public interface IShopStorage
{
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? GetElement(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool Sell(FurnitureBindingModel furnitureBindingModel, int count);
}
}

View File

@ -0,0 +1,15 @@
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.ViewModels
{
public class FurnitureCountViewModel
{
public string furniture { get; set; }
public int Count { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.ViewModels
{
public class ReportCountOrdersViewModel
{
public DateTime DateCreate { get; set; }
public int CountOrders { get; set; }
public double TotalSumOrders { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.ViewModels
{
public class ReportShopFurnituresViewModel
{
public string ShopName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<Tuple<string, int>> Furnitures { get; set; } = new();
}
}

View File

@ -0,0 +1,28 @@
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string Address { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime DateOpening { get; set; }
[JsonIgnore]
public Dictionary<int, (IFurnitureModel, int)> Furnitures { get; set; } = new();
[DisplayName("Вместимость")]
public int MaxCount { get; set; }
public List<FurnitureCountViewModel>? FurnituresCount { get; set; } = new();
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyDataModels.Models
{
public interface IShopModel : IId
{
string ShopName { get; }
string Address { get; }
DateTime DateOpening { get; }
Dictionary<int, (IFurnitureModel, int)> Furnitures { get; }
int MaxCount { get; }
}
}

View File

@ -22,6 +22,9 @@ namespace FurnitureAssemblyDatabaseImplement
public virtual DbSet<Furniture> Furnitures { set; get; }
public virtual DbSet<FurnitureComponent> FurnitureComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopFurniture> ShopFurniture { set; get; }
public virtual DbSet<Client> Clients { set; get; }
}
}

View File

@ -0,0 +1,178 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new FurnitureAssemblyDatabase();
return context.Shops
.Include(x => x.ShopFurnitures)
.ThenInclude(x => x.Furniture)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) &&
x.ShopName == model.ShopName) ||
(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 FurnitureAssemblyDatabase();
return context.Shops
.Include(x => x.ShopFurnitures)
.ThenInclude(x => x.Furniture)
.Where(x => x.ShopName.Contains(model.ShopName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFullList()
{
using var context = new FurnitureAssemblyDatabase();
return context.Shops
.Include(x => x.ShopFurnitures)
.ThenInclude(x => x.Furniture)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var element = context.Shops.Include(x => x.ShopFurnitures).FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
if (GetElement(new ShopSearchModel { ShopName = newShop.ShopName}) != null)
{
throw new Exception("Магазин с таким названием уже есть");
}
context.Shops.Add(newShop);
context.SaveChanges();
transaction.Commit();
return newShop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public bool Sell(FurnitureBindingModel furniture, int count)
{
using var context = new FurnitureAssemblyDatabase();
using var transaction = context.Database.BeginTransaction();
foreach (var shop in context.Shops.Include(x => x.ShopFurnitures).ThenInclude(x => x.Furniture).ToList())
{
if (shop.Furnitures.ContainsKey(furniture.Id))
{
if (shop.Furnitures[furniture.Id].Item2 >= count)
{
shop.Furnitures[furniture.Id] = (shop.Furnitures[furniture.Id].Item1, shop.Furnitures[furniture.Id].Item2 - count);
count = 0;
}
else
{
count -= shop.Furnitures[furniture.Id].Item2;
shop.Furnitures[furniture.Id] = (shop.Furnitures[furniture.Id].Item1, 0);
}
var model = new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
MaxCount = shop.MaxCount,
Furnitures = shop.Furnitures,
Address = shop.Address,
DateOpening = shop.DateOpening
};
shop.Update(model);
shop.UpdateFurnitures(context, model);
if (count == 0)
break;
}
}
if (count == 0)
{
context.SaveChanges();
transaction.Commit();
return true;
}
else
{
transaction.Rollback();
return false;
}
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var shop = context.Shops.FirstOrDefault(rec =>
rec.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
if (model.Furnitures.Count > 0)
{
shop.UpdateFurnitures(context, model);
}
context.SaveChanges();
transaction.Commit();
return shop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -0,0 +1,251 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace FurnitureAssemblyDatabaseImplement.Migrations
{
[DbContext(typeof(FurnitureAssemblyDatabase))]
[Migration("20230312131725_ThirdMigration")]
partial class ThirdMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.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("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FurnitureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureComponent", 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>("FurnitureId")
.HasColumnType("int");
b.Property<int>("ProductId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("FurnitureId");
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.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>("FurnitureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.ToTable("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateOpening")
.HasColumnType("datetime2");
b.Property<int>("MaxCount")
.HasColumnType("int");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.ShopFurniture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("ShopId");
b.ToTable("ShopFurniture");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Component", "Component")
.WithMany("FurnitureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("Components")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("Orders")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.ShopFurniture", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany()
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Shop", "Shop")
.WithMany("ShopFurnitures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("Shop");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Shop", b =>
{
b.Navigation("ShopFurnitures");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,78 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FurnitureAssemblyDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ThirdMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
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),
Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateOpening = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCount = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ShopFurniture",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShopId = table.Column<int>(type: "int", nullable: false),
FurnitureId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopFurniture", x => x.Id);
table.ForeignKey(
name: "FK_ShopFurniture_Furnitures_FurnitureId",
column: x => x.FurnitureId,
principalTable: "Furnitures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopFurniture_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ShopFurniture_FurnitureId",
table: "ShopFurniture",
column: "FurnitureId");
migrationBuilder.CreateIndex(
name: "IX_ShopFurniture_ShopId",
table: "ShopFurniture",
column: "ShopId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ShopFurniture");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -151,6 +151,59 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.ToTable("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateOpening")
.HasColumnType("datetime2");
b.Property<int>("MaxCount")
.HasColumnType("int");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.ShopFurniture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("ShopId");
b.ToTable("ShopFurniture");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Component", "Component")
@ -189,6 +242,25 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.ShopFurniture", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany()
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Shop", "Shop")
.WithMany("ShopFurnitures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("Shop");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
@ -200,6 +272,11 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Shop", b =>
{
b.Navigation("ShopFurnitures");
});
#pragma warning restore 612, 618
}
}

View File

@ -0,0 +1,117 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using Microsoft.EntityFrameworkCore;
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 FurnitureAssemblyDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
[Required]
public string ShopName { get; private set; } = string.Empty;
[Required]
public string Address { get; private set; } = string.Empty;
[Required]
public DateTime DateOpening { get; private set; }
private Dictionary<int, (IFurnitureModel, int)>? _furnitures = null;
[NotMapped]
public Dictionary<int, (IFurnitureModel, int)> Furnitures
{
get
{
if (_furnitures == null)
{
_furnitures = ShopFurnitures
.ToDictionary(recSF => recSF.FurnitureId, recSF =>
(recSF.Furniture as IFurnitureModel, recSF.Count));
}
return _furnitures;
}
private set { }
}
public int MaxCount { get; private set; }
[ForeignKey("ShopId")]
public virtual List<ShopFurniture> ShopFurnitures { get; set; } = new();
public static Shop? Create(FurnitureAssemblyDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
MaxCount = model.MaxCount,
ShopFurnitures = model.Furnitures.Select(x => new ShopFurniture
{
Furniture = context.Furnitures.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
MaxCount = model.MaxCount;
DateOpening = model.DateOpening;
Furnitures = model.Furnitures;
}
public void UpdateFurnitures(FurnitureAssemblyDatabase context, ShopBindingModel model)
{
var shopFurnitures = context.ShopFurniture.Where(rec => rec.ShopId == model.Id).ToList();
if (shopFurnitures != null && shopFurnitures.Count >= 0)
{ // удалили те, которых нет в модели
context.ShopFurniture.RemoveRange(shopFurnitures.Where(rec => !model.Furnitures.ContainsKey(rec.FurnitureId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateComponent in shopFurnitures)
{
updateComponent.Count = model.Furnitures[updateComponent.FurnitureId].Item2;
model.Furnitures.Remove(updateComponent.FurnitureId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var pc in model.Furnitures)
{
context.ShopFurniture.Add(new ShopFurniture
{
Shop = shop,
Furniture = context.Furnitures.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_furnitures = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
MaxCount = MaxCount,
Furnitures = Furnitures
};
}
}

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 FurnitureAssemblyDatabaseImplement.Models
{
public class ShopFurniture
{
public int Id { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int FurnitureId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Furniture Furniture { get; set; } = new();
}
}

View File

@ -13,12 +13,15 @@ namespace FurnitureAssemblyListImplement
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Furniture> Furnitures { get; set; }
public List<Shop> Shops { get; set; }
public List<Client> Clients { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Furnitures = new List<Furniture>();
Shops = new List<Shop>();
Clients = new List<Client>();
}
public static DataListSingleton GetInstance()

View File

@ -0,0 +1,118 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyListImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.ShopName))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.ShopName.Contains(model.ShopName))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) ||
(model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public bool Sell(FurnitureBindingModel furnitureBindingModel, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,66 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyListImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, (IFurnitureModel, int)> Furnitures { get; private set; } = new();
public int MaxCount { get; private set; }
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
MaxCount = model.MaxCount,
DateOpening = model.DateOpening,
Furnitures = model.Furnitures
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
MaxCount = model.MaxCount;
DateOpening = model.DateOpening;
Furnitures = model.Furnitures;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
MaxCount = MaxCount,
DateOpening = DateOpening,
Furnitures = Furnitures
};
}
}

View File

@ -0,0 +1,120 @@
using DocumentFormat.OpenXml.Bibliography;
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContarcts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace FurnitureAssemblyRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ShopController : Controller
{
private readonly ILogger _logger;
private readonly IShopLogic _shop;
public ShopController(ILogger<ShopController> logger, IShopLogic shopLogic)
{
_logger = logger;
_shop = shopLogic;
}
[HttpGet]
public List<ShopViewModel>? GetShopList()
{
try
{
return _shop.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка магазинов");
throw;
}
}
[HttpGet]
public ShopViewModel? GetShop(int shopId)
{
try
{
// получаем обычную ShopViewModel из бизнес-логики, а затем преобразуем в новую модель для передачи в "стороннее" приложение - на клиент
// главное отличие от предыдущей модели в способе передачи изделий - теперь они представлены в виде списка сериализуемых моделей FurnitureCountViewModel
// данное решение необходимо для корректной сериализации изделий и их количества в магазине
var shop = _shop.ReadElement(new ShopSearchModel
{
Id = shopId
});
if (shop == null)
return null;
shop.FurnituresCount = shop.Furnitures.Select(x => x.Value)
.Select(x => new FurnitureCountViewModel { furniture = x.Item1.FurnitureName, Count = x.Item2 }).ToList();
return shop;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения магазина по id={Id}",
shopId);
throw;
}
}
[HttpPost]
public void CreateShop(ShopBindingModel model)
{
try
{
_shop.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания магазина");
throw;
}
}
[HttpPost]
public void UpdateShop(ShopBindingModel model)
{
try
{
_shop.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления магазина");
throw;
}
}
[HttpPost]
public void DeleteShop(ShopBindingModel model)
{
try
{
_shop.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
throw;
}
}
[HttpPost]
public void AddFurnituresToShop(Tuple<ShopBindingModel, FurnitureBindingModel, int> addInfo)
{
try
{
_shop.AddFurniture(addInfo.Item1, addInfo.Item2, addInfo.Item3);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
throw;
}
}
}
}

View File

@ -14,8 +14,10 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IFurnitureStorage, FurnitureStorage>();
builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddTransient<IFurnitureLogic, FurnitureLogic>();
builder.Services.AddControllers();

View File

@ -0,0 +1,46 @@
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
namespace FurnitureAssemblyShopWorkApp
{
public static class APIClient
{
private static readonly HttpClient _client = new();
public static bool isAuth { get; set; } = false;
public static string ConfigPassword { get; private set; } = string.Empty;
public static void Connect(IConfiguration configuration)
{
ConfigPassword = configuration["PasswordForAccess"];
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -0,0 +1,153 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyShopWorkApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace FurnitureAssemblyShopWorkApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
if (!APIClient.isAuth)
{
return Redirect("~/Home/Enter");
}
return
View(APIClient.GetRequest<List<ShopViewModel>>($"api/shop/getshoplist"));
}
public IActionResult Privacy()
{
if (!APIClient.isAuth)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string password)
{
if (string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
if (!password.Equals(APIClient.ConfigPassword))
{
throw new Exception("Неверный пароль");
}
APIClient.isAuth = true;
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public void Create(string shopName, string address, DateTime dateOpening, int count)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (count <= 0)
{
throw new Exception("Количество и сумма должны быть больше 0");
}
APIClient.PostRequest("api/shop/createshop", new ShopBindingModel
{
ShopName = shopName,
MaxCount = count,
Address = address,
DateOpening = dateOpening
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Delete()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshoplist");
return View();
}
[HttpPost]
public void Delete(int shop)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest($"api/shop/deleteshop", new ShopBindingModel { Id = shop});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Update()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshoplist");
return View();
}
[HttpPost]
public void Update(int shop, string shopName, string address, DateTime dateOpening, int count)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest($"api/shop/updateshop", new ShopBindingModel {
Id = shop,
ShopName = shopName,
Address = address,
DateOpening = dateOpening,
MaxCount = count }
);
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Replenishment()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshoplist");
ViewBag.Furnitures = APIClient.GetRequest<List<FurnitureViewModel>>("api/main/getfurniturelist");
return View();
}
[HttpPost]
public void Replenishment(int shop, int furniture, int count)
{
if (!APIClient.isAuth)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest($"api/shop/addfurniturestoshop", ( new ShopBindingModel { Id = shop }, new FurnitureBindingModel {Id =furniture}, count));
Response.Redirect("Index");
}
[HttpGet]
public ShopViewModel? GetShop(int shopId)
{
return APIClient.GetRequest<ShopViewModel>($"api/shop/getshop?shopId={shopId}");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

View File

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FurnitureAssemblyContracts\FurnitureAssemblyContracts.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="Views\Home\Enter.cshtml">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>

View File

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

View File

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

View File

@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:24780",
"sslPort": 44336
}
},
"profiles": {
"FurnitureAssemblyShopWorkApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7110;http://localhost:5110",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,28 @@
@{
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"><input type="text" name="shopName" id="shopName"/></div>
</div>
<div class="row">
<div class="col-4">Дата открытия:</div>
<div class="col-8"><input type="date" id="dateOpening" name="dateOpening"/></div>
<div class="row">
<div class="col-4">Адрес:</div>
<div class="col-8"><input type="text" id="address" name="address"/></div>
</div>
<div class="row">
<div class="col-4">Вместимость:</div>
<div class="col-8"><input type="number" id="count" name="count"/></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать" class="btn
btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,17 @@
@{
ViewData["Title"] = "Delete";
}
<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="shop" name="shop" class="form-control" asp-items="@(new SelectList(@ViewBag.Shops,"Id", "ShopName"))"></select>
</div>
</div>
<div class="col-4"><input type="submit" value="Удалить" class="btn
btn-primary" /></div>
</div>
</form>

View File

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

View File

@ -0,0 +1,57 @@
@using FurnitureAssemblyContracts.ViewModels
@model List<ShopViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Магазины</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="Create">Создать магазин</a>
<a asp-action="Delete">Удалить магазин</a>
<a asp-action="Update">Редактировать магазин</a>
<a asp-action="Replenishment">Пополнить магазин</a>
</p>
<table class="table">
<thead>
<tr>
<th>Номер</th>
<th>Название</th>
<th>Дата открытия</th>
<th>Адрес</th>
<th>Вместимость</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.ShopName)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateOpening)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.MaxCount)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@ -0,0 +1,27 @@
@{
ViewData["Title"] = "Replenishment";
}
<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="shop" name="shop" class="form-control" asp-items="@(new SelectList(@ViewBag.Shops,"Id", "ShopName"))"></select>
</div>
<div class="row">
<div class="col-4">Изделие:</div>
<div class="col-8">
<select id="furniture" name="furniture" class="form-control" asp-items="@(new SelectList(@ViewBag.Furnitures,"Id", "FurnitureName"))"></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="col-4"><input type="submit" value="Пополнить" class="btn
btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,72 @@
@{
ViewData["Title"] = "Update";
}
<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="shop" name="shop" onchange="getData()" class="form-control" asp-items="@(new SelectList(@ViewBag.Shops,"Id", "ShopName"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Название:</div>
<div class="col-8"><input type="text" name="shopName" id="shopName"/></div>
</div>
<div class="row">
<div class="col-4">Дата открытия:</div>
<div class="col-8"><input type="datetime-local" id="dateOpening" name="dateOpening"/></div>
<div class="row">
<div class="col-4">Адрес:</div>
<div class="col-8"><input type="text" id="address" name="address"/></div>
</div>
<div class="row">
<div class="col-4">Вместимость:</div>
<div class="col-8"><input type="number" id="count" name="count"/></div>
</div>
<div class="row">
<div class="col-4">Изделия в магазине:</div>
<div class="col-8">
<table class="table">
<thead>
<tr>
<th>Изделие</th>
<th>Количество</th>
</tr>
</thead>
<tbody id="furnitures">
</tbody>
</table>
</div>
</div>
<div class="col-4"><input type="submit" value="Принять" class="btn
btn-primary" /></div>
</div>
</form>
<script>
function getData() {
$.ajax({
method: "GET",
url: "/Home/GetShop",
data: { shopId: $('#shop').val()},
success: function (result) {
$("#shopName").val(result.shopName);
$("#dateOpening").val(new Date(result.dateOpening).toISOString().substring(0, 16));
$("#address").val(result.address);
$("#count").val(result.maxCount);
fillTable(result.furnituresCount);
}
});
}
function fillTable(furnitures) {
$("#furnitures").empty();
for(var i = 0; i < furnitures.length; i++)
$("#furnitures").append('<tr><td>' + furnitures[i].furniture +
'</td><td>' + furnitures[i].count + '</td></tr>');
}
</script>

View File

@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - FurnitureAssemblyShopWorkApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/FurnitureAssemblyShopWorkApp.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">FurnitureAssemblyShopWorkApp</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Магазины</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2023 - FurnitureAssemblyShopWorkApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,48 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@ -0,0 +1,3 @@
@using FurnitureAssemblyShopWorkApp
@using FurnitureAssemblyShopWorkApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

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

View File

@ -0,0 +1,11 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"IPAddress": "http://localhost:5078/",
"PasswordForAccess": "12345"
}

View File

@ -0,0 +1,18 @@
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -0,0 +1,4 @@
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2011-2021 Twitter, Inc.
Copyright (c) 2011-2021 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,427 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-left: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr /* rtl:ignore */;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: left;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: left;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: left;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
/* rtl:raw:
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.css.map */

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