Compare commits

...

6 Commits

37 changed files with 1138 additions and 160 deletions

View File

@ -85,7 +85,7 @@ namespace ComputerShopBusinessLogic.BusinessLogics
_saveToPdf.CreateDoc(new PdfInfoImplementer
{
FileName = model.FileName,
Title = "Список участников",
Title = "Отчёт по заказам за период",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
Orders = GetReportOrdersByDates(model)

View File

@ -0,0 +1,64 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
//private readonly IOrganiserLogic _organiserLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger/*, IOrganiserLogic organiserLogic*/)
{
_logger = logger;
//_organiserLogic = organiserLogic;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{
return;
}
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,51 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using ComputerShopContracts.BusinessLogicContracts;
using System.Net.Mime;
using ComputerShopContracts.BindingModels;
namespace ComputerShopBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger/*, IOrganiserLogic organiserLogic*/) : base(logger/*, organiserLogic*/) { }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
Attachment attachment = new Attachment("C:\\!Курсовая\\Отчёт за период.pdf", new ContentType(MediaTypeNames.Application.Pdf));
objMailMessage.Attachments.Add(attachment);
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
}
}

View File

@ -16,17 +16,29 @@ namespace GarmentFactoryBusinessLogic.OfficePackage
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateParagraph(new PdfParagraph { Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
//!!!МБ ТУТ НЕЛЬЗЯ ДРОБНЫЕ ЧИСЛА ИЛИ МОЖНО С ТОЧКОЙ
CreateTable(new List<string> { "1,5cm", "3cm", "3cm", "2,5cm", "1,5cm", "4cm", "3cm", "3cm", "3cm", "3cm" });
CreateTable(new List<string> { "2cm", "2.5cm", "2cm", "2cm", "2cm", "4cm", "2.5cm", "3.5cm", "3.5cm", "2.5cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "ID заказа", "Дата заказа", "Стоимость заказа", "Статус заказа", "ID заявки", "ФИО клиента", "Дата заявки", "Название сборки", "Каетегория сборки", "Цена сборки" },
Texts = new List<string> { "ID заказа", "Дата заказа", "Сумма заказа", "Статус заказа", "ID заявки", "ФИО клиента", "Дата заявки", "Название сборки", "Категория сборки", "Цена сборки" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.Orders)
{
//!!!СЮДА
if (order.RequestsAssemblies.Count < 1)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> {
order.OrderId.ToString(), order.DateCreateOrder.ToShortDateString(), order.OrderSum.ToString(), order.OrderStatus.ToString(),
"Заказ без заявок", "Неизвестно", "Неизвестно",
"Неизвестно", "Неизвестно", "0"
}
});
}
foreach (var request in order.RequestsAssemblies)
{
CreateRow(new PdfRowParameters
@ -34,11 +46,12 @@ namespace GarmentFactoryBusinessLogic.OfficePackage
Texts = new List<string> { order.OrderId.ToString(), order.DateCreateOrder.ToShortDateString(), order.OrderSum.ToString(), order.OrderStatus.ToString(),
request.RequestId.ToString(), request.ClientFIO, request.DateRequest.ToShortDateString(),
string.IsNullOrEmpty(request.AssemblyName) ? "Сборка не привязана" : request.AssemblyName,
string.IsNullOrEmpty(request.AssemblyCategory) ? "Неизвестная категория" : request.AssemblyCategory,
string.IsNullOrEmpty(request.AssemblyCategory) ? "Неизвестно" : request.AssemblyCategory,
request.AssemblyPrice.ToString()
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
}
//},
//Style = "Normal",
//ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}

View File

@ -41,8 +41,9 @@ namespace GarmentFactoryBusinessLogic.OfficePackage.Implements
protected override void CreatePdf(PdfInfoImplementer info)
{
_document = new Document();
DefineStyles(_document);
DefineStyles(_document);
_document.DefaultPageSetup.Orientation = Orientation.Landscape;
_section = _document.AddSection();
}
@ -100,12 +101,14 @@ namespace GarmentFactoryBusinessLogic.OfficePackage.Implements
}
}
//!!!ТУТ ИСКЛЮЧЕНИЕ
protected override void SavePdf(PdfInfoImplementer info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}

View File

@ -14,7 +14,7 @@ namespace ComputerShopContracts.BindingModels
public string Category { get; set; } = string.Empty;
public Dictionary<int, (IComponentModel, int)> AssemblyComponents { get; set; } = new();
public Dictionary<int, IComponentModel> AssemblyComponents { get; set; } = new();
public Dictionary<int, int> Test { get; set; } = new();
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopContracts.BindingModels
{
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { 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 ComputerShopContracts.BindingModels
{
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
}

View File

@ -16,6 +16,6 @@ namespace ComputerShopContracts.BindingModels
public int Warranty { get; set; }
public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new();
public Dictionary<int, IComponentModel> ProductComponents { get; set; } = new();
}
}

View File

@ -18,6 +18,6 @@ namespace ComputerShopContracts.ViewModels
[DisplayName("Категория")]
public string Category { get; set; } = string.Empty;
public Dictionary<int, (IComponentModel, int)> AssemblyComponents { get; set; } = new();
public Dictionary<int, IComponentModel> AssemblyComponents { get; set; } = new();
}
}

View File

@ -23,6 +23,6 @@ namespace ComputerShopContracts.ViewModels
[DisplayName("Гарантия (мес.)")]
public int Warranty { get; set; }
public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new();
public Dictionary<int, IComponentModel> ProductComponents { get; set; } = new();
}
}

View File

@ -28,6 +28,6 @@
/// <summary>
/// Список комплектующих
/// </summary>
Dictionary<int, (IComponentModel, int)> AssemblyComponents { get; }
Dictionary<int, IComponentModel> AssemblyComponents { get; }
}
}

View File

@ -28,7 +28,7 @@
/// <summary>
/// Список комплектующих
/// </summary>
Dictionary<int, (IComponentModel, int)> ProductComponents { get; }
Dictionary<int, IComponentModel> ProductComponents { get; }
/// <summary>
/// Привязка товара к партии товаров

View File

@ -24,7 +24,7 @@ namespace ComputerShopDatabaseImplement.Implements
{
using var Context = new ComputerShopDatabase();
// Optional search by Category name
// Optional search by Category
if (!string.IsNullOrEmpty(Model.Category))
{
return Context.Assemblies
@ -35,6 +35,7 @@ namespace ComputerShopDatabaseImplement.Implements
.ToList();
}
// Search by UserId by default
return Context.Assemblies
.Include(x => x.Components)
.ThenInclude(x => x.Component)

View File

@ -106,7 +106,7 @@ namespace ComputerShopDatabaseImplement.Implements
ComponentName = x.ComponentName,
ComponentCost = x.Cost,
Shipments = x.ProductComponents
.Select(y => (y.Count, y.Product.ProductName, y.Product.Price, y.Product.Shipment!.ProviderName, y.Product.Shipment.DateShipment))
.Select(y => (0, y.Product.ProductName, y.Product.Price, y.Product.Shipment!.ProviderName, y.Product.Shipment.DateShipment))
.ToList(),
})
.ToList();

View File

@ -83,10 +83,11 @@ namespace ComputerShopDatabaseImplement.Implements
public List<ReportOrdersViewModel> GetOrdersInfoByDates(ReportBindingModel report)
{
using var context = new ComputerShopDatabase();
return context.Orders.Include(x => x.Requests)
return context.Orders
.Where(x => x.UserId == report.UserId && DateTime.Compare(x.DateCreate, report.DateFrom.Value) >= 0 && DateTime.Compare(x.DateCreate, report.DateTo.Value) <= 0)
.Include(x => x.Requests)
.ThenInclude(x => x.Request)
.ThenInclude(x => x.Assembly)
.Where(x => x.UserId == report.UserId && x.DateCreate >= report.DateFrom && x.DateCreate <= report.DateTo)
.ToList()
.Select(x => new ReportOrdersViewModel
{
@ -95,9 +96,9 @@ namespace ComputerShopDatabaseImplement.Implements
OrderSum = x.Sum,
OrderStatus = x.Status,
RequestsAssemblies = x.Requests.Select(r => (r.Request.Id, r.Request.ClientFIO, r.Request.DateRequest,
(r.Request.Assembly != null) ? r.Request.Assembly.AssemblyName : "Без сборки",
(r.Request.Assembly != null) ? r.Request.Assembly.Category : "Без сборки",
(r.Request.Assembly != null) ? r.Request.Assembly.Price : 0)).ToList()
(r.Request.Assembly != null) ? r.Request.Assembly.AssemblyName : "",
(r.Request.Assembly != null) ? r.Request.Assembly.Category : "",
(r.Request.Assembly != null) ? r.Request.Assembly.Price : 0)).ToList(),
})
.ToList();
}

View File

@ -37,6 +37,7 @@ namespace ComputerShopDatabaseImplement.Implements
.ToList();
}
// Search by UserId by default
return Context.Products
.Include(x => x.Shipment)
.Include(x => x.Components)

View File

@ -0,0 +1,516 @@
// <auto-generated />
using System;
using ComputerShopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ComputerShopDatabaseImplement.Migrations
{
[DbContext(typeof(ComputerShopDatabase))]
[Migration("20240528105815_Edit AssemblyComponent and ProductComponent")]
partial class EditAssemblyComponentandProductComponent
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.18")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Assembly", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("AssemblyName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Assemblies");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.AssemblyComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("AssemblyId")
.HasColumnType("integer");
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("ComponentId");
b.ToTable("AssemblyComponents");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Components");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp without time zone");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Orders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ShipmentId")
.HasColumnType("integer");
b.Property<int>("UserId")
.HasColumnType("integer");
b.Property<int>("Warranty")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ShipmentId");
b.HasIndex("UserId");
b.ToTable("Products");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ProductComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("ProductId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Request", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("AssemblyId")
.HasColumnType("integer");
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateRequest")
.HasColumnType("timestamp without time zone");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("UserId");
b.ToTable("Requests");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.RequestOrder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderId")
.HasColumnType("integer");
b.Property<int>("RequestId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("RequestId");
b.ToTable("RequestOrders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Shipment", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("DateShipment")
.HasColumnType("timestamp without time zone");
b.Property<string>("ProviderName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Shipments");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ShipmentOrder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderId")
.HasColumnType("integer");
b.Property<int>("ShipmentId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("ShipmentId");
b.ToTable("ShipmentOrders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Role")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Assembly", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Assemblies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.AssemblyComponent", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Assembly", "Assembly")
.WithMany("Components")
.HasForeignKey("AssemblyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Component", "Component")
.WithMany("AssemblyComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("Component");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Component", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Components")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Orders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Product", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Shipment", "Shipment")
.WithMany("Products")
.HasForeignKey("ShipmentId");
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Products")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Shipment");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ProductComponent", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Component", "Component")
.WithMany("ProductComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Product", "Product")
.WithMany("Components")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Request", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Assembly", "Assembly")
.WithMany("Requests")
.HasForeignKey("AssemblyId");
b.HasOne("ComputerShopDatabaseImplement.Models.User", "User")
.WithMany("Requests")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("User");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.RequestOrder", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Order", "Order")
.WithMany("Requests")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Request", "Request")
.WithMany("Orders")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Request");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Shipment", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Shipments")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ShipmentOrder", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Order", "Order")
.WithMany("Shipments")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Shipment", "Shipment")
.WithMany("Orders")
.HasForeignKey("ShipmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Shipment");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Assembly", b =>
{
b.Navigation("Components");
b.Navigation("Requests");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Component", b =>
{
b.Navigation("AssemblyComponents");
b.Navigation("ProductComponents");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Order", b =>
{
b.Navigation("Requests");
b.Navigation("Shipments");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Product", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Request", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Shipment", b =>
{
b.Navigation("Orders");
b.Navigation("Products");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.User", b =>
{
b.Navigation("Assemblies");
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("Products");
b.Navigation("Requests");
b.Navigation("Shipments");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ComputerShopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class EditAssemblyComponentandProductComponent : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Count",
table: "ProductComponents");
migrationBuilder.DropColumn(
name: "Count",
table: "AssemblyComponents");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Count",
table: "ProductComponents",
type: "integer",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "Count",
table: "AssemblyComponents",
type: "integer",
nullable: false,
defaultValue: 0);
}
}
}

View File

@ -65,9 +65,6 @@ namespace ComputerShopDatabaseImplement.Migrations
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
@ -173,9 +170,6 @@ namespace ComputerShopDatabaseImplement.Migrations
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("ProductId")
.HasColumnType("integer");
@ -370,7 +364,7 @@ namespace ComputerShopDatabaseImplement.Migrations
.HasForeignKey("ShipmentId");
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Proucts")
.WithMany("Products")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
@ -507,7 +501,7 @@ namespace ComputerShopDatabaseImplement.Migrations
b.Navigation("Orders");
b.Navigation("Proucts");
b.Navigation("Products");
b.Navigation("Requests");

View File

@ -28,10 +28,10 @@ namespace ComputerShopDatabaseImplement.Models
[ForeignKey("AssemblyId")]
public virtual List<AssemblyComponent> Components { get; set; } = new();
private Dictionary<int, (IComponentModel, int)>? _assemblyComponents;
private Dictionary<int, IComponentModel>? _assemblyComponents;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> AssemblyComponents
public Dictionary<int, IComponentModel> AssemblyComponents
{
get
{
@ -39,7 +39,7 @@ namespace ComputerShopDatabaseImplement.Models
{
_assemblyComponents = Components.ToDictionary(
AsmComp => AsmComp.ComponentId,
AsmComp => (AsmComp.Component as IComponentModel, AsmComp.Count)
AsmComp => AsmComp.Component as IComponentModel
);
}
@ -49,18 +49,22 @@ namespace ComputerShopDatabaseImplement.Models
public static Assembly Create(ComputerShopDatabase Context, AssemblyBindingModel Model)
{
return new()
var Components = Model.AssemblyComponents
.Select(x => new AssemblyComponent
{
Component = Context.Components.First(y => y.Id == x.Key)
})
.ToList();
double Price = Components.Sum(x => x.Component.Cost);
return new Assembly()
{
Id = Model.Id,
UserId = Model.UserId,
AssemblyName = Model.AssemblyName,
Price = Model.Price,
Price = Price,
Category = Model.Category,
Components = Model.AssemblyComponents.Select(x => new AssemblyComponent
{
Component = Context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
Components = Components,
};
}
@ -75,8 +79,6 @@ namespace ComputerShopDatabaseImplement.Models
{
Category = Model.Category;
}
Price = Model.Price;
}
public AssemblyViewModel ViewModel => new()
@ -91,17 +93,22 @@ namespace ComputerShopDatabaseImplement.Models
public void UpdateComponents(ComputerShopDatabase Context, AssemblyBindingModel Model)
{
// Сначала подсчитывается новая цена, т.к. Model.AssemblyComponents далее может измениться
double NewPrice = Context.Components
.Where(x => Model.AssemblyComponents.ContainsKey(x.Id))
.Sum(x => x.Cost);
var AssemblyComponents = Context.AssemblyComponents.Where(x => x.AssemblyId == Model.Id).ToList();
if (AssemblyComponents != null && AssemblyComponents.Count > 0)
{
// Удаление записей из таблицы AssemblyComponents тех компонентов, которых нет в модели
Context.AssemblyComponents
.RemoveRange(AssemblyComponents
.Where(x => !Model.AssemblyComponents.ContainsKey(x.ComponentId)));
.RemoveRange(AssemblyComponents.Where(x => !Model.AssemblyComponents.ContainsKey(x.ComponentId)));
Context.SaveChanges();
// После этого в Model.AssemblyComponents останутся только те компоненты, записей о которых еще нет в БД
foreach (var ComponentToUpdate in AssemblyComponents)
{
ComponentToUpdate.Count = Model.AssemblyComponents[ComponentToUpdate.ComponentId].Item2;
Model.AssemblyComponents.Remove(ComponentToUpdate.ComponentId);
}
@ -115,13 +122,31 @@ namespace ComputerShopDatabaseImplement.Models
{
Assembly = CurrentAssembly,
Component = Context.Components.First(x => x.Id == AssemblyComponent.Key),
Count = AssemblyComponent.Value.Item2
});
Context.SaveChanges();
}
Price = NewPrice;
Context.SaveChanges();
_assemblyComponents = null;
}
private void CalculatePrice(
ComputerShopDatabase Context,
Dictionary<int, IComponentModel> ModelComponents,
out List<AssemblyComponent> OutComponents,
out double OutPrice)
{
OutComponents = ModelComponents
.Select(x => new AssemblyComponent
{
Component = Context.Components.First(y => y.Id == x.Key)
})
.ToList();
OutPrice = Components.Sum(x => x.Component.Cost);
}
}
}

View File

@ -12,9 +12,6 @@ namespace ComputerShopDatabaseImplement.Models
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Assembly Assembly { get; set; } = new();
public virtual Component Component { get; set; } = new();

View File

@ -29,10 +29,10 @@ namespace ComputerShopDatabaseImplement.Models
[ForeignKey("ProductId")]
public virtual List<ProductComponent> Components { get; set; } = new();
private Dictionary<int, (IComponentModel, int)>? _productComponents;
private Dictionary<int, IComponentModel>? _productComponents;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> ProductComponents
public Dictionary<int, IComponentModel> ProductComponents
{
get
{
@ -40,7 +40,7 @@ namespace ComputerShopDatabaseImplement.Models
{
_productComponents = Components.ToDictionary(
ProdComp => ProdComp.ComponentId,
ProdComp => (ProdComp.Component as IComponentModel, ProdComp.Count)
ProdComp => ProdComp.Component as IComponentModel
);
}
@ -50,7 +50,15 @@ namespace ComputerShopDatabaseImplement.Models
public static Product Create(ComputerShopDatabase Context, ProductBindingModel Model)
{
return new()
var Components = Model.ProductComponents
.Select(x => new ProductComponent
{
Component = Context.Components.First(y => y.Id == x.Key)
})
.ToList();
double Price = Components.Sum(x => x.Component.Cost);
return new Product()
{
Id = Model.Id,
UserId = Model.UserId,
@ -58,11 +66,7 @@ namespace ComputerShopDatabaseImplement.Models
ProductName = Model.ProductName,
Price = Model.Price,
Warranty = Model.Warranty,
Components = Model.ProductComponents.Select(x => new ProductComponent
{
Component = Context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList(),
Components = Components,
};
}
@ -74,7 +78,6 @@ namespace ComputerShopDatabaseImplement.Models
}
ShipmentId = Model.ShipmentId;
Price = Model.Price;
Warranty = Model.Warranty;
}
@ -91,17 +94,22 @@ namespace ComputerShopDatabaseImplement.Models
public void UpdateComponents(ComputerShopDatabase Context, ProductBindingModel Model)
{
// Сначала подсчитывается новая цена, т.к. Model.ProductComponents далее может измениться
double NewPrice = Context.Components
.Where(x => Model.ProductComponents.ContainsKey(x.Id))
.Sum(x => x.Cost);
var ProductComponents = Context.ProductComponents.Where(x => x.ProductId == Model.Id).ToList();
if (ProductComponents != null && ProductComponents.Count > 0)
{
// Удаление записей из таблицы ProductComponents тех компонентов, которых нет в модели
Context.ProductComponents
.RemoveRange(ProductComponents
.Where(x => !Model.ProductComponents.ContainsKey(x.ComponentId)));
.RemoveRange(ProductComponents.Where(x => !Model.ProductComponents.ContainsKey(x.ComponentId)));
Context.SaveChanges();
// После этого в Model.ProductComponents останутся только те компоненты, записей о которых еще нет в БД
foreach (var ComponentToUpdate in ProductComponents)
{
ComponentToUpdate.Count = Model.ProductComponents[ComponentToUpdate.ComponentId].Item2;
Model.ProductComponents.Remove(ComponentToUpdate.ComponentId);
}
@ -115,12 +123,14 @@ namespace ComputerShopDatabaseImplement.Models
{
Product = CurrentProduct,
Component = Context.Components.First(x => x.Id == ProductComponent.Key),
Count = ProductComponent.Value.Item2
});
Context.SaveChanges();
}
Price = NewPrice;
Context.SaveChanges();
_productComponents = null;
}
}

View File

@ -12,9 +12,6 @@ namespace ComputerShopDatabaseImplement.Models
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Product Product { get; set; } = new();
public virtual Component Component { get; set; } = new();

View File

@ -2,13 +2,8 @@
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.Enums;
using ComputerShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopDatabaseImplement.Models
{
@ -30,19 +25,21 @@ namespace ComputerShopDatabaseImplement.Models
[ForeignKey("UserId")]
public virtual List<Shipment> Shipments { get; set; } = new();
[ForeignKey("UserId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("UserId")]
public virtual List<Request> Requests { get; set; } = new();
[ForeignKey("UserId")]
public virtual List<Assembly> Assemblies { get; set; } = new();
[ForeignKey("UserId")]
public virtual List<Component> Components { get; set; } = new();
[ForeignKey("UserId")]
public virtual List<Product> Proucts { get; set; } = new();
public virtual List<Product> Products { get; set; } = new();
public static User Create(UserBindingModel model)
{

View File

@ -0,0 +1,49 @@
using ComputerShopContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace ComputerShopGuarantorApp
{
public static class ApiUser
{
private static readonly HttpClient _client = new();
public static UserViewModel? User { get; set; } = null;
public static void Connect(IConfiguration Configuration)
{
_client.BaseAddress = new Uri(Configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
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

@ -6,4 +6,12 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputerShopContracts\ComputerShopContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -1,27 +1,30 @@
var builder = WebApplication.CreateBuilder(args);
using ComputerShopGuarantorApp;
var Builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
Builder.Services.AddControllersWithViews();
var app = builder.Build();
var App = Builder.Build();
ApiUser.Connect(Builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
if (!App.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
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.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
App.UseHttpsRedirection();
App.UseStaticFiles();
app.UseRouting();
App.UseRouting();
app.UseAuthorization();
App.UseAuthorization();
app.MapControllerRoute(
App.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
App.Run();

View File

@ -3,34 +3,40 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - ComputerShopGuarantorApp</title>
<title>@ViewData["Title"] - Поручитель</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="~/ComputerShopGuarantorApp.styles.css" asp-append-version="true" />
</head>
<body>
<body class="d-flex flex-column min-vh-100" padding="56px">
<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">ComputerShopGuarantorApp</a>
<nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark">
<div class="container-md">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index"><span class="fw-bold text-uppercase ms-2">Приложение поручителя</span></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">Home</a>
<div class="collapse navbar-collapse justify-content-end align-center" id="main-nav">
<ul class="navbar-nav">
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Index">Главная</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
<li class="nav-item me-3">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item d-lg-none">
<a class="nav-link text-light" asp-area="" asp-controller="Home" asp-action="Privacy">Вход в аккаунт</a>
</li>
<li class="nav-item d-none d-lg-inline">
<a class="btn btn-light" asp-area="" asp-controller="Home" asp-action="Privacy">Вход в аккаунт</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<div class="container-md py-4 mb-4">
<main role="main" class="pb-3">
@RenderBody()
</main>

View File

@ -1,6 +1,10 @@
/* 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. */
body {
background-color: #ff0000;
}
a.navbar-brand {
white-space: normal;
text-align: center;
@ -46,3 +50,4 @@ button.accept-policy {
white-space: nowrap;
line-height: 60px;
}

View File

@ -5,5 +5,6 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"IPAddress": "http://localhost:5024"
}

View File

@ -7,6 +7,7 @@ using ComputerShopDataModels.Enums;
using ComputerShopDataModels.Models;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.BusinessLogicContracts;
using DocumentFormat.OpenXml.Bibliography;
namespace ComputerShopImplementerApp.Controllers
{
@ -594,10 +595,116 @@ namespace ComputerShopImplementerApp.Controllers
throw;
}
string table = "";
//МБ НЕ НДО ПРИСВАИВАТЬ КЛАСС u-table-entity
table += $"<table class=\"u-table-entity\">";
table += "<colgroup>";
//ID заказа
table += "<col width=\"5%\" />";
//Дата заказа
table += "<col width=\"10%\" />";
//Стоимость заказа
table += "<col width=\"10%\" />";
//Статус заказа
table += "<col width=\"10%\" />";
//ID заявки
table += "<col width=\"5%\" />";
//ФИО клиента
table += "<col width=\"15%\" />";
//Дата заявки
table += "<col width=\"10%\" />";
//Название сборки
table += "<col width=\"15%\" />";
//Категория сборки
table += "<col width=\"10%\" />";
//Цена сборки
table += "<col width=\"10%\" />";
table += "</colgroup>";
//МБ НЕ НДО ПРИСВАИВАТЬ КЛАСС
table += "<thead class=\"u-custom-color-1 u-table-header u-table-header-1\">";
//МБ ИЗМЕНИТЬ ВЫСОТУ
table += "<tr style=\"height: 31px\">";
//МБ ИЗМЕНИТЬ КЛАСС
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ID заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Дата заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Стоимость заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Статус заказа</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ID заявки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">ФИО клиента</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Дата заявки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Название сборки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Категория сборки</th>";
table += $"<th class=\"u-border-1 u-border-grey-50 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">Цена сборки</th>";
table += "</tr>";
table += "</thead>";
//МБ НЕ ПРИСВАИВАТЬ КЛАСС ИЛИ СДЕЛАТЬ ПЕРЕД ВНУТРЕННИМ ЦИКЛОМ
table += "<tbody class=\"u-table-body\">";
foreach (var order in result)
{
if (order.RequestsAssemblies.Count < 1)
{
//МБ ПОМЕНЯТЬ ВЫСОТУ
table += "<tr style=\"height: 75px\">";
table += $"<td class=\"u-border-1 u-border-grey-40 u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderId.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.DateCreateOrder.ToShortDateString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderSum.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderStatus.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Заказ без заявок"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{"Неизвестно"}</td>";
table += "</tr>";
}
foreach (var request in order.RequestsAssemblies)
{
//МБ ПОМЕНЯТЬ ВЫСОТУ
table += "<tr style=\"height: 75px\">";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderId.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.DateCreateOrder.ToShortDateString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderSum.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{order.OrderStatus.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.RequestId.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.ClientFIO.ToString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.DateRequest.ToShortDateString()}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{(string.IsNullOrEmpty(request.AssemblyName) ? "Сборка не привязана" : request.AssemblyName)}</td>";
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{(string.IsNullOrEmpty(request.AssemblyCategory) ? "Неизвестная категория" : request.AssemblyCategory)}</td>";
//МБ тут не будет 0 у непривязанных сборок
table += $"<td class=\"u-border-1 u-border-grey-40 u-border-no-left u-border-no-right u-table-cell\" style=\"text-align:center; border: 1px solid black; border-collapse:collapse\">{request.AssemblyPrice.ToString()}</td>";
table += "</tr>";
}
}
table += "</table>";
return table;
}
[HttpPost]
public void ReportOrdersByDates(DateTime dateFrom, DateTime dateTo)
{
if (APIUser.User == null)
{
throw new Exception("Вход только авторизованным");
}
//if (string.IsNullOrEmpty(organiserEmail))
//{
// throw new Exception("Email пуст");
//}
APIUser.PostRequest("api/order/CreateReportToPDFFile", new ReportBindingModel
{
FileName = "C:\\!КУРСОВАЯ\\Отчёт за период.pdf",
DateFrom = dateFrom,
DateTo = dateTo,
UserId = APIUser.User.Id
});
APIUser.PostRequest("api/order/SendPDFToMail", new MailSendInfoBindingModel
{
//!!!МБ СЮДА ПЕРЕДАВАТЬ ПОЧТУ, КОТОРУЮ ВВОДЯТ НА СТРАНИЦЕ
MailAddress = APIUser.User.Email,
Subject = "Отчет за период",
Text = "Отчет по заказам с " + dateFrom.ToShortDateString() + " по " + dateTo.ToShortDateString()
});
Response.Redirect("Index");
}
// ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ ОСТАЛЬНОЕ
@ -651,6 +758,8 @@ namespace ComputerShopImplementerApp.Controllers
[HttpPost]
public void Enter(string login, string password)
{
try
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
@ -663,6 +772,11 @@ namespace ComputerShopImplementerApp.Controllers
}
Response.Redirect("Index");
}
catch (Exception)
{
Response.Redirect("Enter");
}
}
[HttpGet]
public IActionResult Register()

View File

@ -5,6 +5,8 @@ using ComputerShopDatabaseImplement.Implements;
using ComputerShopDatabaseImplement.Models;
using ComputerShopDataModels.Models;
using ComputerShopImplementerApp;
using GarmentFactoryBusinessLogic.OfficePackage;
using GarmentFactoryBusinessLogic.OfficePackage.Implements;
var builder = WebApplication.CreateBuilder(args);
@ -13,19 +15,25 @@ var builder = WebApplication.CreateBuilder(args);
//builder.Services.AddTransient<IShipmentModel, Shipment>();
//builder.Services.AddTransient<IRequestModel, Request>();
builder.Services.AddTransient<IUserStorage, UserStorage>();
builder.Services.AddTransient<IShipmentStorage, ShipmentStorage>();
builder.Services.AddTransient<IRequestStorage, RequestStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddTransient<IShipmentLogic, ShipmentLogic>();
builder.Services.AddTransient<IRequestLogic, RequestLogic>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IAssemblyStorage, AssemblyStorage>();
builder.Services.AddTransient<IReportImplementerLogic, ReportImplementerLogic>();
builder.Services.AddTransient<AbstractSaveToWordImplementer, SaveToWordImplementer>();
builder.Services.AddTransient<AbstractSaveToExcelImplementer, SaveToExcelImplementer>();
builder.Services.AddTransient<AbstractSaveToPdfImplementer, SaveToPdfImplementer>();
//builder.Services.AddTransient<IReportImplementerLogic, ReportImplementerLogic>();
// Add services to the container.
builder.Services.AddControllersWithViews();

View File

@ -8,25 +8,22 @@
<h2 class="display-4">Отчёт за период по заказам</h2>
</div>
<div class="form-group">
<label class="mb-3" for="dateFrom">Начало периода</label>
<label class="mb-3" for="dateFrom">Начало периода:</label>
<input type="datetime-local" placeholder="Выберите дату начала периода" id="dateFrom" name="dateFrom" />
</div>
<div class="form-group">
<label class="mb-3" for="dateTo">Окончание периода</label>
<label class="mb-3" for="dateTo">Окончание периода:</label>
<input type="datetime-local" placeholder="Выберите дату окончания периода" id="dateTo" name="dateTo"/>
</div>
<div class="form-group">
<label class="mb-3">Текущий статус заказа:</label>
@* <input class="mb-3" type="text" id="currentStatus" name="currentStatus" readonly /> *@
<span id="currentStatus" style="font-weight: bold;"></span>
</div>
<div class="row">
<button type="button" id="show">Вывести здесь</button>
<div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div>
</div>
</form>
<div class="row">
<button class="mt-5" type="button" id="show">Вывести здесь</button>
</div>
<div class="mt-3" id="report">
</div>
</form>
<script>

View File

@ -2,6 +2,7 @@
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.ViewModels;
using ComputerShopBusinessLogic.MailWorker;
using ComputerShopDatabaseImplement.Models;
using ComputerShopDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
@ -18,11 +19,14 @@ namespace ComputerShopRestApi.Controllers
private readonly IReportImplementerLogic _reportLogic;
public OrderController(IOrderLogic logic, ILogger<OrderController> logger, IReportImplementerLogic reportLogic)
private readonly AbstractMailWorker _mailWorker;
public OrderController(IOrderLogic logic, ILogger<OrderController> logger, IReportImplementerLogic reportLogic, AbstractMailWorker mailWorker)
{
_logger = logger;
_logic = logic;
_reportLogic = reportLogic;
_mailWorker = mailWorker;
}
[HttpGet]
@ -104,6 +108,22 @@ namespace ComputerShopRestApi.Controllers
}
}
[HttpPost]
public void SendPDFToMail(MailSendInfoBindingModel model)
{
try
{
_mailWorker.MailSendAsync(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отправки письма");
throw;
}
}
//МБ ИЗМЕНИТЬ IEnumerable на List
//!!!ПОТОМ УДАЛИТЬ
//[HttpGet]

View File

@ -2,11 +2,13 @@ using ComputerShopBusinessLogic.BusinessLogics;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.StorageContracts;
using ComputerShopDatabaseImplement.Implements;
using ComputerShopBusinessLogic.MailWorker;
using ComputerShopDatabaseImplement.Models;
using ComputerShopDataModels.Models;
using GarmentFactoryBusinessLogic.OfficePackage;
using GarmentFactoryBusinessLogic.OfficePackage.Implements;
using Microsoft.OpenApi.Models;
using ComputerShopContracts.BindingModels;
var Builder = WebApplication.CreateBuilder(args);
Builder.Logging.SetMinimumLevel(LogLevel.Trace);
@ -40,6 +42,8 @@ Builder.Services.AddTransient<AbstractSaveToExcelImplementer, SaveToExcelImpleme
Builder.Services.AddTransient<AbstractSaveToWordImplementer, SaveToWordImplementer>();
Builder.Services.AddTransient<AbstractSaveToPdfImplementer, SaveToPdfImplementer>();
Builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
Builder.Services.AddControllers();
Builder.Services.AddEndpointsApiExplorer();
Builder.Services.AddSwaggerGen(c =>
@ -53,6 +57,19 @@ Builder.Services.AddSwaggerGen(c =>
var App = Builder.Build();
var mailSender = App.Services.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = Builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
MailPassword = Builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
SmtpClientHost = Builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
SmtpClientPort = Convert.ToInt32(Builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
PopHost = Builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty,
PopPort = Convert.ToInt32(Builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
});
if (App.Environment.IsDevelopment())
{
App.UseSwagger();

View File

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "rpplab7chernyshev@gmail.com",
"MailPassword": "cojg axan axbk qtqb"
}