Commit beedbc3b authored by TTrueBenji's avatar TTrueBenji

Вынес создание телефона в сервис.

#1
parent cfc19982
...@@ -5,9 +5,8 @@ using System.Linq; ...@@ -5,9 +5,8 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting; using PhoneStore.Helpers;
using PhoneStore.Models; using PhoneStore.Models;
using PhoneStore.Services;
using PhoneStore.Services.Abstractions; using PhoneStore.Services.Abstractions;
using PhoneStore.ViewModels; using PhoneStore.ViewModels;
...@@ -16,28 +15,21 @@ namespace PhoneStore.Controllers ...@@ -16,28 +15,21 @@ namespace PhoneStore.Controllers
public class PhonesController : Controller public class PhonesController : Controller
{ {
private readonly MobileContext _db; private readonly MobileContext _db;
private readonly IHostEnvironment _environment; private readonly IPhoneService _phoneService;
private readonly UploadService _uploadService;
private readonly IDefaultPhoneImagePathProvider _imagePathProvider;
public PhonesController( public PhonesController(
MobileContext db, MobileContext db,
IHostEnvironment environment, IPhoneService phoneService)
UploadService uploadService,
IDefaultPhoneImagePathProvider imagePathProvider)
{ {
_db = db; _db = db;
_environment = environment; _phoneService = phoneService;
_uploadService = uploadService;
_imagePathProvider = imagePathProvider;
} }
[HttpGet] [HttpGet]
public IActionResult Index(int? brandId, string name) public IActionResult Index(int? brandId)
{ {
IEnumerable<Brand> brands = _db.Brands; IEnumerable<Brand> brands = _db.Brands;
IQueryable<Phone> phones = _db.Phones IQueryable<Phone> phones = _db.Phones.AsQueryable();
.AsQueryable();
if (brandId is > 0) if (brandId is > 0)
phones = _db.Phones.Where(p => p.BrandId == brandId); phones = _db.Phones.Where(p => p.BrandId == brandId);
...@@ -66,38 +58,23 @@ namespace PhoneStore.Controllers ...@@ -66,38 +58,23 @@ namespace PhoneStore.Controllers
{ {
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
string imagePath; await _phoneService.CreateAsync(model);
if (model.File is null)
imagePath = _imagePathProvider.GetPathToDefaultImage();
else
{
var brand = _db.Brands.FirstOrDefault(b => b.Id == model.BrandId);
string dirPath = Path.Combine(_environment.ContentRootPath, $"wwwroot\\images\\phoneImages\\{brand!.Name}");
string fileName = $"{model.File.FileName}";
await _uploadService.UploadAsync(dirPath, fileName, model.File);
imagePath = $"images\\phoneImages\\{brand!.Name}\\{fileName}";
}
_db.Phones.Add(new Phone
{
Image = imagePath,
Name = model.Name,
Price = (decimal)model.Price!,
BrandId = model.BrandId
});
await _db.SaveChangesAsync();
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
model.Brands = _db.Brands.ToList();
return View("Create", model);
} }
//TODO: Добавить кастомный exception //TODO: Добавить кастомный exception
catch (FileNotFoundException e) catch (FileNotFoundException)
{ {
return RedirectToAction("Error", "Errors", new {statusCode = 666}); return RedirectToAction("Error", "Errors", new {statusCode = 666});
} }
catch(Exception)
model.Brands = _db.Brands.ToList(); {
return View("Create", model); return RedirectToAction("Error", "Errors", new {statusCode = 777});
}
} }
[HttpGet] [HttpGet]
...@@ -105,7 +82,7 @@ namespace PhoneStore.Controllers ...@@ -105,7 +82,7 @@ namespace PhoneStore.Controllers
{ {
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId); var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null) if (phone is null)
return BadRequest(); return RedirectToAction("Error", "Errors", new {statusCode = 777});
return View(phone); return View(phone);
} }
...@@ -114,6 +91,7 @@ namespace PhoneStore.Controllers ...@@ -114,6 +91,7 @@ namespace PhoneStore.Controllers
[ActionName("Delete")] [ActionName("Delete")]
public IActionResult Confirm(int phoneId) public IActionResult Confirm(int phoneId)
{ {
//TODO: Добавить удаление файла изображения.
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId); var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null) if (phone is null)
return BadRequest(); return BadRequest();
...@@ -129,50 +107,34 @@ namespace PhoneStore.Controllers ...@@ -129,50 +107,34 @@ namespace PhoneStore.Controllers
var brands = _db.Brands.ToList(); var brands = _db.Brands.ToList();
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId); var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null) if (phone is null)
{ return RedirectToAction("Error", "Errors", new {statusCode = 777});
return BadRequest();
}
PhoneCreateViewModel model = new PhoneCreateViewModel PhoneCreateViewModel model = new PhoneCreateViewModel
{ {
Id = phone.Id, Id = phone.Id,
Name = phone.Name, Name = phone.Name,
Price = phone.Price, Price = phone.Price,
BrandId = (int)phone.BrandId, BrandId = (int)phone.BrandId,
Image = phone.Image,
Brands = brands Brands = brands
}; };
return View(model); return View(model);
} }
[HttpPost] [HttpPost]
public IActionResult Edit(Phone phone) public IActionResult Edit(PhoneCreateViewModel model)
{ {
if (phone is null) if (model is null)
{ return RedirectToAction("Error", "Errors", new {statusCode = 777});
return BadRequest(); string imagePath = string.Empty;
} if (model.File is null)
imagePath = model.Image;
_db.Phones.Update(phone);
_db.Phones.Update(model.MapToPhone(imagePath));
_db.SaveChanges(); _db.SaveChanges();
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
[HttpGet]
public IActionResult UploadFile()
{
return View();
}
[HttpPost]
public async Task<IActionResult> UploadFile(FileViewModel model)
{
string dirPath = Path.Combine(_environment.ContentRootPath, "wwwroot/Files");
string fileName = $"{model.File.FileName}";
await _uploadService.UploadAsync(dirPath, fileName, model.File);
return Ok("Файл успешно загружен");
}
[HttpGet] [HttpGet]
public IActionResult About(int? id) public IActionResult About(int? id)
{ {
......
using PhoneStore.Models;
using PhoneStore.ViewModels;
namespace PhoneStore.Helpers
{
public static class PhoneMapper
{
public static Phone MapToPhone(this PhoneCreateViewModel self, string imagePath = null)
{
Phone phone = new Phone
{
Name = self.Name,
Price = (decimal) self.Price!,
BrandId = self.BrandId,
Image = imagePath,
Id = self.Id
};
return phone;
}
}
}
\ No newline at end of file
using System.Threading.Tasks;
namespace PhoneStore.Services.Abstractions
{
public interface ICreatable<in T> where T : class
{
Task CreateAsync(T entity);
}
}
\ No newline at end of file
using PhoneStore.ViewModels;
namespace PhoneStore.Services.Abstractions
{
public interface IPhoneService : ICreatable<PhoneCreateViewModel>
{
}
}
\ No newline at end of file
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using PhoneStore.Helpers;
using PhoneStore.Models;
using PhoneStore.Services.Abstractions;
using PhoneStore.ViewModels;
namespace PhoneStore.Services
{
public class PhoneService : IPhoneService
{
private readonly MobileContext _db;
private readonly IDefaultPhoneImagePathProvider _imagePathProvider;
private readonly UploadService _uploadService;
private readonly IHostEnvironment _environment;
public PhoneService(
MobileContext db,
IDefaultPhoneImagePathProvider imagePathProvider,
UploadService uploadService,
IHostEnvironment environment)
{
_db = db;
_imagePathProvider = imagePathProvider;
_uploadService = uploadService;
_environment = environment;
}
public async Task CreateAsync(PhoneCreateViewModel entity)
{
string imagePath;
if (entity.File is null)
imagePath = _imagePathProvider.GetPathToDefaultImage();
else
{
var brand = _db.Brands.FirstOrDefault(b => b.Id == entity.BrandId);
if (brand is null)
throw new Exception();
string dirPath = Path.Combine(_environment.ContentRootPath, $"wwwroot\\images\\phoneImages\\{brand.Name}");
string fileName = $"{entity.File.FileName}";
await _uploadService.UploadAsync(dirPath, fileName, entity.File);
imagePath = $"images\\phoneImages\\{brand!.Name}\\{fileName}";
}
_db.Phones.Add(entity.MapToPhone(imagePath));
await _db.SaveChangesAsync();
}
}
}
\ No newline at end of file
...@@ -31,6 +31,7 @@ namespace PhoneStore ...@@ -31,6 +31,7 @@ namespace PhoneStore
services.AddTransient<UploadService>(); services.AddTransient<UploadService>();
services.AddTransient<IDefaultPhoneImagePathProvider>(_ => services.AddTransient<IDefaultPhoneImagePathProvider>(_ =>
new DefaultPhoneImagePathProvider(Configuration["PathToDefaultAvatar:Path"])); new DefaultPhoneImagePathProvider(Configuration["PathToDefaultAvatar:Path"]));
services.AddTransient<IPhoneService, PhoneService>();
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
......
...@@ -19,5 +19,6 @@ namespace PhoneStore.ViewModels ...@@ -19,5 +19,6 @@ namespace PhoneStore.ViewModels
public int BrandId { get; set; } public int BrandId { get; set; }
public List<Brand> Brands { get; set; } public List<Brand> Brands { get; set; }
public IFormFile File { get; set; } public IFormFile File { get; set; }
public string Image { get; set; }
} }
} }
\ No newline at end of file
...@@ -11,8 +11,11 @@ ...@@ -11,8 +11,11 @@
await Html.RenderPartialAsync("PartialViews/PhoneFormPartialView"); await Html.RenderPartialAsync("PartialViews/PhoneFormPartialView");
} }
<input type="text" hidden asp-for="@Model.Id"> <input type="text" hidden asp-for="@Model.Id">
<input type="text" hidden asp-for="@Model.Image">
<button type="submit" <button type="submit"
class="btn btn-outline-warning">Изменить</button> class="btn btn-outline-warning">
Изменить
</button>
</form> </form>
</div> </div>
</div> </div>
......
@model FileViewModel
@{
ViewBag.Title = "Загрузка файла";
Layout = "_Layout";
}
<h2>Загрузите файл на сервер</h2>
<form asp-action="UploadFile" asp-controller="Phones" method="post" enctype="multipart/form-data">
<fieldset>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="file" asp-for="File">
<label class="form-check-label" asp-for="File">
Добавьте файл
</label>
</div>
</div>
<button type="submit" class="btn btn-outline-info">Добавить</button>
</fieldset>
</form>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment