5 Commits

Author SHA1 Message Date
6aa55f1c11 продукты 2024-05-29 18:48:47 +04:00
b626bfda7d короче сторе кипер 2024-05-29 17:25:32 +04:00
8aefc24b6a слишком синее неб0.. 2024-05-29 15:47:18 +04:00
598049b063 уладили конфликты 2024-05-29 15:43:40 +04:00
46f93270fe работа-работа, перейди на 2024-05-28 15:27:44 +04:00
39 changed files with 933 additions and 370 deletions

View File

@@ -14,6 +14,9 @@ EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputerHardwareStoreDatabaseImplement", "ComputerHardwareStoreDatabaseImplement\ComputerHardwareStoreDatabaseImplement.csproj", "{93BD4E28-48D8-4D3A-87FB-FB96F00DA64B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputerHardwareStoreREST", "ComputerHardwareStoreREST\ComputerHardwareStoreREST.csproj", "{20E4D287-C0F4-4DAB-B338-349F8B6EA22B}"
ProjectSection(ProjectDependencies) = postProject
{D32DEB60-AF40-46AF-8914-DC6A19BD66CD} = {D32DEB60-AF40-46AF-8914-DC6A19BD66CD}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VendorClient", "VendorClient\VendorClient.csproj", "{BD0D9FB9-7F73-4011-AAC8-D5508EC5EB53}"
EndProject

View File

@@ -0,0 +1,20 @@
using ComputerHardwareContracts.BindingModels;
using ComputerHardwareStoreContracts.BusinessLogicsContracts;
using ComputerHardwareStoreContracts.SearchModels;
using ComputerHardwareStoreContracts.ViewModels;
namespace ComputerHardwareStoreBusinessLogic.BusinessLogic
{
public class MessageInfoLogic : IMessageInfoLogic
{
public bool Create(MessageInfoBindingModel model)
{
throw new NotImplementedException();
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,62 @@
using ComputerHardwareStoreContracts.BindingModels;
using Microsoft.Extensions.Logging;
namespace ComputerHardwareStoreBusinessLogic.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 ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger)
{
_logger = logger;
}
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,41 @@
using ComputerHardwareStoreContracts.BindingModels;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace ComputerHardwareStoreBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger) : base(logger) { }
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;
MemoryStream ms = new(info.File);
objMailMessage.Attachments.Add(new Attachment(ms, "report.pdf", "application/pdf"));
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

@@ -0,0 +1,17 @@
namespace ComputerHardwareStoreContracts.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,13 @@
namespace ComputerHardwareStoreContracts.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;
public byte[] File { get; set; } = Array.Empty<byte>();
}
}

View File

@@ -0,0 +1,14 @@
using ComputerHardwareStoreDataModels.Models;
namespace ComputerHardwareContracts.BindingModels
{
public class MessageInfoBindingModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
}
}

View File

@@ -8,6 +8,6 @@ namespace ComputerHardwareStoreContracts.BindingModels
public string Name { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new();
public IStoreKeeperModel StoreKeeper { get; set; }
public int StoreKeeperId { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
using ComputerHardwareContracts.BindingModels;
using ComputerHardwareStoreContracts.SearchModels;
using ComputerHardwareStoreContracts.ViewModels;
namespace ComputerHardwareStoreContracts.BusinessLogicsContracts
{
public interface IMessageInfoLogic
{
List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
bool Create(MessageInfoBindingModel model);
}
}

View File

@@ -6,6 +6,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MailKit" Version="4.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputerHardwareStoreDataModels\ComputerHardwareStoreDataModels.csproj" />
</ItemGroup>

View File

@@ -0,0 +1,8 @@
namespace ComputerHardwareStoreContracts.SearchModels
{
public class MessageInfoSearchModel
{
public int? ClientId { get; set; }
public string? MessageId { get; set; }
}
}

View File

@@ -4,5 +4,6 @@
{
public int? Id { get; set; }
public string? Login { get; set; }
}
public string? Password { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using ComputerHardwareContracts.BindingModels;
using ComputerHardwareStoreContracts.SearchModels;
using ComputerHardwareStoreContracts.ViewModels;
namespace ComputerHardwareStoreContracts.StorageContracts
{
public interface IMessageInfoStorage
{
List<MessageInfoViewModel> GetFullList();
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
}
}

View File

@@ -0,0 +1,24 @@
using ComputerHardwareStoreDataModels.Models;
using System.ComponentModel;
namespace ComputerHardwareStoreContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
[DisplayName("Отправитель")]
public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата письма")]
public DateTime DateDelivery { get; set; }
[DisplayName("Заголовок")]
public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")]
public string Body { get; set; } = string.Empty;
}
}

View File

@@ -11,6 +11,6 @@ namespace ComputerHardwareStoreContracts.ViewModels
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new();
public IStoreKeeperModel StoreKeeper { get; set; }
public int StoreKeeperId { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace ComputerHardwareStoreContracts.ViewModels
{
public class ReportPurchaseViewModel
{
public int Id { get; set; }
public List<(string Build, int count, List<(string Component, int count)>)> Builds { get; set; } = new();
public int TotalCount { get; set; }
public double TotalCost { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
namespace ComputerHardwareStoreDataModels.Models
{
public interface IMessageInfoModel
{
string MessageId { get; }
int? ClientId { get; }
string SenderName { get; }
DateTime DateDelivery { get; }
string Subject { get; }
string Body { get; }
}
}

View File

@@ -4,7 +4,7 @@
{
string Name { get; }
double Price { get; }
public IStoreKeeperModel StoreKeeper { get; }
public int StoreKeeperId { get; }
public Dictionary<int, (IComponentModel, int)> ProductComponents { get; }
}
}

View File

@@ -14,8 +14,7 @@ namespace ComputerHardwareStoreDatabaseImplement.Models
public string Name { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
[NotMapped]
IStoreKeeperModel IProductModel.StoreKeeper => StoreKeeper;
public int StoreKeeperId { get; set; }
public virtual StoreKeeper StoreKeeper {get; set;} = new();
private Dictionary<int, (IComponentModel, int)>? _productComponents = null;
[NotMapped]
@@ -65,7 +64,7 @@ namespace ComputerHardwareStoreDatabaseImplement.Models
Name = Name,
Price = Price,
ProductComponents = ProductComponents,
StoreKeeper = StoreKeeper,
StoreKeeperId = StoreKeeperId,
};
public static void UpdateComponents(ComputerHardwareStoreDBContext context, ProductBindingModel model)

View File

@@ -2,87 +2,82 @@
using ComputerHardwareStoreContracts.BindingModels;
using ComputerHardwareStoreContracts.SearchModels;
using ComputerHardwareStoreContracts.StorageContracts;
using ComputerHardwareStoreContracts.BusinessLogicsContracts;
using ComputerHardwareStoreContracts.ViewModels;
namespace ComputerHardwareStoreREST.Controllers
{
[ApiController]
[Route("[controller]")]
public class StoreKeepersController : Controller
[Route("api/[controller]/[action]")]
[ApiController]
public class StoreKeeperController : Controller
{
private readonly ILogger<StoreKeepersController> _logger;
private readonly IStoreKeeperStorage _storage;
public StoreKeepersController(ILogger<StoreKeepersController> logger, IStoreKeeperStorage storage)
{
_logger = logger;
_storage = storage;
}
[HttpPost("get/filter")]
public IActionResult GetByFilter([FromBody] StoreKeeperSearchModel model)
{
try
{
var result = _storage.GetFilteredList(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("get")]
public IActionResult GetById([FromBody] StoreKeeperSearchModel model)
{
try
{
var result = _storage.GetElement(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("create")]
public IActionResult Create([FromBody] StoreKeeperBindingModel model)
{
try
{
var result = _storage.Insert(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut("update")]
public IActionResult Update([FromBody] StoreKeeperBindingModel model)
{
try
{
var result = _storage.Update(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("delete")]
public IActionResult Delete([FromBody] StoreKeeperBindingModel model)
{
try
{
var result = _storage.Delete(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
private readonly ILogger _logger;
private readonly IStoreKeeperLogic _logic;
private readonly IMessageInfoLogic _mailLogic;
public StoreKeeperController(IStoreKeeperLogic logic, IMessageInfoLogic mailLogic, ILogger<StoreKeeperController> logger)
{
_logger = logger;
_logic = logic;
_mailLogic = mailLogic;
}
[HttpGet]
public StoreKeeperViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new StoreKeeperSearchModel
{
Login = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка входа в систему");
throw;
}
}
[HttpPost]
public void Register(StoreKeeperBindingModel model)
{
try
{
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
[HttpPost]
public void UpdateData(StoreKeeperBindingModel model)
{
try
{
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных");
throw;
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
{
try
{
return _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

View File

@@ -1,87 +1,82 @@
using ComputerHardwareStoreContracts.BindingModels;
using ComputerHardwareStoreContracts.BusinessLogicsContracts;
using ComputerHardwareStoreContracts.SearchModels;
using ComputerHardwareStoreContracts.StorageContracts;
using ComputerHardwareStoreContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace ComputerHardwareStoreREST.Controllers
{
[ApiController]
[Route("[controller]")]
[Route("api/[controller]/[action]")]
[ApiController]
public class VendorController : Controller
{
private readonly ILogger<VendorController> _logger;
private readonly IVendorStorage _storage;
public VendorController(ILogger<VendorController> logger, IVendorStorage storage)
{
_logger = logger;
_storage = storage;
}
[HttpPost("get/filter")]
public IActionResult GetByFilter([FromBody] VendorSearchModel model)
{
try
{
var result = _storage.GetFilteredList(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("get")]
public IActionResult GetById([FromBody] VendorSearchModel model)
{
try
{
var result = _storage.GetElement(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("create")]
public IActionResult Create([FromBody] VendorBindingModel model)
{
try
{
var result = _storage.Insert(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut("update")]
public IActionResult Update([FromBody] VendorBindingModel model)
{
try
{
var result = _storage.Update(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("delete")]
public IActionResult Delete([FromBody] VendorBindingModel model)
{
try
{
var result = _storage.Delete(model);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
private readonly ILogger _logger;
private readonly IVendorLogic _logic;
private readonly IMessageInfoLogic _mailLogic;
public VendorController(IVendorLogic logic, IMessageInfoLogic mailLogic, ILogger<VendorController> logger)
{
_logger = logger;
_logic = logic;
_mailLogic = mailLogic;
}
[HttpGet]
public VendorViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new VendorSearchModel
{
Login = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка входа в систему");
throw;
}
}
[HttpPost]
public void Register(VendorBindingModel model)
{
try
{
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
[HttpPost]
public void UpdateData(VendorBindingModel model)
{
try
{
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных");
throw;
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId)
{
try
{
return _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

View File

@@ -1,7 +1,7 @@
using ComputerHardwareStoreBusinessLogic.BusinessLogic;
using ComputerHardwareStoreContracts.BindingModels;
using ComputerHardwareStoreContracts.BusinessLogicsContracts;
using ComputerHardwareStoreContracts.StorageContracts;
using ComputerHardwareStoreDatabaseImplement;
using ComputerHardwareStoreDatabaseImplement.Implements;
using ComputerHardwareStoreREST;
using Microsoft.EntityFrameworkCore;
@@ -32,19 +32,28 @@ builder.Services.AddTransient<ICommentLogic, CommentLogic>();
//builder.Services.AddTransient<IProductLogic, ProductLogic>();
builder.Services.AddTransient<IComponentLogic, ComponentLogic>();
builder.Services.AddTransient<IStoreKeeperLogic, StoreKeeperLogic>();
builder.Services.AddTransient <IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
//var mailSender = app.Services.GetService<AbstractMailWorker>();
//mailSender?.MailConfig(new MailConfigBindingModel
//{
//MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
//MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
//SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
//SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
//PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty,
//PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
//});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AbstractShopRestApi v1"));
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

View File

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

View File

@@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "coursework@gmail.com",
"MailPassword": "123"
}

View File

@@ -15,6 +15,7 @@ namespace StoreKeeperClient
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
@@ -28,16 +29,37 @@ namespace StoreKeeperClient
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);
}
}
public static R? PostRequestWithResult<T, R>(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)
{
return JsonConvert.DeserializeObject<R>(result);
}
else
{
return default;
}
}
}
}

View File

@@ -18,47 +18,8 @@ namespace StoreKeeperClient.Controllers
[HttpGet]
public IActionResult Index()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<PurchaseViewModel>>($"api/main/getpurchases?clientId={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Client);
}
[HttpPost]
public void Privacy(string login, string password, string fio)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/updatedata", new StoreKeeperBindingModel
{
Id = APIClient.Client.Id,
Name = fio,
Login = login,
Password = password
});
APIClient.Client.Name = fio;
APIClient.Client.Login = login;
APIClient.Client.Password = password;
Response.Redirect("Index");
}
return View();
}
[HttpGet]
public IActionResult Enter()
@@ -66,12 +27,44 @@ namespace StoreKeeperClient.Controllers
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите почту и пароль");
}
APIClient.Client = APIClient.GetRequest<StoreKeeperViewModel>($"api/storekeeper/login?login={login}&password={password}");
if (APIClient.Client == null)
{
throw new Exception("Неверные почта и/или пароль");
}
Response.Redirect("Home/Index");
return;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string name, string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин, name, пароль");
}
APIClient.PostRequest("api/storekeeper/register", new StoreKeeperBindingModel
{
Name = name,
Login = login,
Password = password,
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult AddBuildToPurchase()
@@ -164,13 +157,103 @@ namespace StoreKeeperClient.Controllers
}
[HttpGet]
public IActionResult ProductsList()
public IActionResult Products()
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
return View(new List<BuildViewModel>());
return View(new List<ProductViewModel>());
}
public IActionResult CreateProduct()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Components = APIClient.GetRequest<List<ComponentViewModel>>($"api/component/getcomponents?userId={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void CreateProduct([FromBody] ProductBindingModel productModel)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (string.IsNullOrEmpty(productModel.Name))
{
throw new Exception("Название не должно быть пустым");
}
if (productModel.Price <= 0)
{
throw new Exception("Цена должна быть больше 0");
}
productModel.StoreKeeperId = APIClient.Client.Id;
APIClient.PostRequest("api/product/createproduct", productModel);
}
public IActionResult UpdateProduct(int productid)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
ViewBag.Components = APIClient.GetRequest<List<ComponentViewModel>>($"api/component/getcomponents?userId={APIClient.Client.Id}");
return View(productid);
}
[HttpPost]
public void UpdateProduct([FromBody] ProductBindingModel productModel)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (string.IsNullOrEmpty(productModel.Name))
{
throw new Exception("Название не должно быть пустым");
}
if (productModel.Price <= 0)
{
throw new Exception("Цена должна быть больше 0");
}
productModel.StoreKeeperId = APIClient.Client.Id;
APIClient.PostRequest("api/product/updatedata", productModel);
}
[HttpPost]
public void DeleteGood(int model)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (model <= 0)
{
throw new Exception($"Идентификатор товара не может быть меньше или равен 0");
}
APIClient.PostRequest("api/product/deleteproduct", new ProductBindingModel
{
Id = model
});
}
[HttpGet]
public ProductViewModel? GetProduct(int Id)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (Id <= 0)
{
throw new Exception($"Идентификатор товара не может быть меньше или равен 0");
}
var result = APIClient.GetRequest<ProductViewModel>($"api/product/getproduct?id={Id}");
return result;
}
[HttpGet]
@@ -203,16 +286,6 @@ namespace StoreKeeperClient.Controllers
return View(new List<PurchaseViewModel>());
}
[HttpGet]
public IActionResult PurchaseUpdate()
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
return View();
}
[HttpGet]
public IActionResult Report()
{
@@ -233,7 +306,16 @@ namespace StoreKeeperClient.Controllers
Response.Redirect("ReportOnly");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/storekeeper/getmessages?storekeeperId={APIClient.Client.Id}"));
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });

View File

@@ -20,6 +20,6 @@ app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
pattern: "{controller=Home}/{action=Enter}/{id?}");
app.Run();

View File

@@ -34,3 +34,96 @@
</div>
</div>
</form>
@section Scripts
{
<script>
let list = [];
const name = document.getElementById("name");
const submitComponentBtn = document.getElementById("savecomponent");
const saveBtn = document.getElementById("createproduct");
const countElem = document.getElementById("count");
const resultTable = document.getElementById("result");
const totalPrice = document.getElementById("price");
submitComponentBtn.addEventListener("click", () => {
console.log('try to add component')
var count = $('#count').val();
var component = $('#component').val();
if (component && count && count > 0) {
$.ajax({
method: "GET",
url: `/Storekeeper/GetComponent`,
data: { Id: component },
success: function (result) {
let flag = false
if (list.length > 0) {
list.forEach((elem) => {
if (elem.component.id === parseInt(result.id)) {
console.log('component already added')
flag = true
}
})
}
if (!flag) list.push({ component: result, count: count })
reloadTable()
countElem.value = '1'
}
}).fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
})
}
})
saveBtn.addEventListener("click", () => {
console.log('try to add product')
if (list.length == 0) {
alert('failed add product. components are empty')
return
}
let components = []
let counts = []
list.forEach((x) => {
components.push(x.component);
counts.push(parseInt(x.count))
})
$.ajax(
{
url: `/Storekeeper/CreateProduct`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
"Name": name.value, "Price": parseFloat(totalPrice.value),
"ProductComponentsComponents": components, "ProductComponentsCounts": counts
})
}
).done(() => window.location.href = '/Storekeeper/Products')
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
})
})
function reloadTable() {
resultTable.innerHTML = ''
let price = 0;
let count = 0;
list.forEach((elem) => {
resultTable.innerHTML += `<tr><td>${elem.component.componentName}</td><td>${elem.component.cost}</td><td>${elem.count}</td><td>${Math.round(elem.component.cost * elem.count * 100) / 100}</td><td> \
<div> \
<button onclick="deleteComponent(${count})" type="button" class="btn btn-danger"> \
<i class="fa fa-trash" aria-hidden="true"></i> \
</button> \
</div><td/></tr>`
count++;
price += elem.component.cost * elem.count
})
totalPrice.value = Math.round(price * 100) / 100
}
function deleteComponent(id) {
list = list.filter(value => value.component.componentName != resultTable.rows[id].cells[0].innerText)
reloadTable()
}
</script>
}

View File

@@ -1,5 +1,4 @@
@using ComputerHardwareStoreContracts.ViewModels
@model List<OrderViewModel>
@{
ViewData["Title"] = "Home Page";
}
@@ -11,54 +10,8 @@
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
<h3 class="display-4">Добро пожаловать</h3>
return;
}
<p>
<a asp-action="Create">Создать заказ</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<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.DateCreate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sum)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

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

View File

@@ -7,52 +7,53 @@
<h1 class="display-4">Товары</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Надо войти!</h3>
return;
}
<p>
<a class="text-decoration-none me-3 text-black h5" asp-action="CreateProduct">Создать товар</a>
<a class="text-decoration-none me-3 text-black h5" asp-action="UpdateProduct">Изменить товар</a>
<a class="text-decoration-none text-black h5" asp-action="DeleteProduct">Удалить товар</a>
</p>
@{
if (Model == null)
{
<h3 class="display-4">Надо войти!</h3>
return;
}
<p>
<a class="text-decoration-none me-3 text-black h5" asp-action="CreateProduct">Создать товар</a>
<a class="text-decoration-none me-3 text-black h5" asp-action="UpdateProduct">Изменить товар</a>
<a class="text-decoration-none text-black h5" asp-action="DeleteProduct">Удалить товар</a>
</p>
<table class="productTable">
<thead>
<tr>
<th>
Номер
</th>
<th>
Название
</th>
<th>
Цена
</th>
<table class="productTable">
<thead>
<tr>
<th>
Номер
</th>
<th>
Название
</th>
</tr>
</thead>
<tbody>
<tbody>
@foreach (var Product in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => Product.Id)
</td>
<td>
@Html.DisplayFor(modelItem => Product.Name)
</td>
<td>
@Html.DisplayFor(modelItem => Product.Price)
</td>
</tr>
}
</tbody>
</tbody>
</table>
}
<th>
Цена
</th>
</tr>
</thead>
<tbody>
<tbody>
@foreach (var Product in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => Product.Id)
</td>
<td>
@Html.DisplayFor(modelItem => Product.Name)
</td>
<td>
@Html.DisplayFor(modelItem => Product.Price)
</td>
</tr>
}
</tbody>
</tbody>
</table>
}
</div>

View File

@@ -7,7 +7,7 @@
<form method="post">
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8"><input type="text" name="storeKeeperName" /></div>
<div class="col-8"><input type="text" name="name" /></div>
</div>
<div class="row">
<div class="col-4">Логин:</div>

View File

@@ -0,0 +1,5 @@
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

View File

@@ -22,4 +22,4 @@
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>
</p>

View File

@@ -1,34 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - ComputerStoreWorkerApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<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="~/ComputerStoreWorkerApp.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">
<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">ComputerStoreWorkerApp</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>
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="Privacy">Личные данные</a>
</li>
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Components">Комплектующие</a>
</li>
<li class="nav-item">
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Products">Товары</a>
</li>
<li class="nav-item">
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Orders">Заказы на товары</a>
</li>
<li class="nav-item">
@@ -36,32 +33,32 @@
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="ComponentsByPurchasesAndOrdersReport">Отчёт по комплектующим за период</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" 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="Register">Регистрация</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" 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="Register">Регистрация</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">
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2024 - ComputerStoreWorkerApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
</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>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
</html>

View File

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

View File

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

View File

@@ -5,16 +5,19 @@ using System.Text;
namespace VendorClient
{
public static class APIClient
public class APIClient
{
private static readonly HttpClient _client = new();
public static StoreKeeperViewModel? Client { get; set; } = null;
public static VendorViewModel? Vendor { 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);
@@ -28,16 +31,37 @@ namespace VendorClient
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);
}
}
public static R? PostRequestWithResult<T, R>(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)
{
return JsonConvert.DeserializeObject<R>(result);
}
else
{
return default;
}
}
}
}

View File

@@ -1,4 +1,5 @@
using ComputerHardwareStoreContracts.ViewModels;
using ComputerHardwareStoreContracts.BindingModels;
using ComputerHardwareStoreContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using VendorClient.Models;
@@ -17,13 +18,46 @@ namespace VendorClient.Controllers
[HttpGet]
public IActionResult Index()
{
return View();
if (APIClient.Vendor == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Vendor);
}
[HttpGet]
public IActionResult Privacy()
{
return View();
if (APIClient.Vendor == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Vendor);
}
[HttpPost]
public void Privacy(string login, string password, string fio)
{
if (APIClient.Vendor == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/vendor/updatedata", new VendorBindingModel
{
Id = APIClient.Vendor.Id,
Name = fio,
Login = login,
Password = password
});
APIClient.Vendor.Name = fio;
APIClient.Vendor.Login = login;
APIClient.Vendor.Password = password;
Response.Redirect("Index");
}
[HttpGet]
@@ -32,13 +66,46 @@ namespace VendorClient.Controllers
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите почту и пароль");
}
APIClient.Vendor = APIClient.GetRequest<VendorViewModel>($"api/vendor/login?login={login}&password={password}");
if (APIClient.Vendor == null)
{
throw new Exception("Неверные почта и/или пароль");
}
Response.Redirect("Index");
return;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpGet]
return View();
}
[HttpPost]
public void Register(string name, string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин, name, пароль");
}
APIClient.PostRequest("api/vendor/register", new VendorBindingModel
{
Name = name,
Login = login,
Password = password,
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult AddBuildToPurchase()
{
return View();