Commit beedbc3b authored by TTrueBenji's avatar TTrueBenji

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

#1
parent cfc19982
......@@ -5,9 +5,8 @@ using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using PhoneStore.Helpers;
using PhoneStore.Models;
using PhoneStore.Services;
using PhoneStore.Services.Abstractions;
using PhoneStore.ViewModels;
......@@ -16,28 +15,21 @@ namespace PhoneStore.Controllers
public class PhonesController : Controller
{
private readonly MobileContext _db;
private readonly IHostEnvironment _environment;
private readonly UploadService _uploadService;
private readonly IDefaultPhoneImagePathProvider _imagePathProvider;
private readonly IPhoneService _phoneService;
public PhonesController(
MobileContext db,
IHostEnvironment environment,
UploadService uploadService,
IDefaultPhoneImagePathProvider imagePathProvider)
IPhoneService phoneService)
{
_db = db;
_environment = environment;
_uploadService = uploadService;
_imagePathProvider = imagePathProvider;
_phoneService = phoneService;
}
[HttpGet]
public IActionResult Index(int? brandId, string name)
public IActionResult Index(int? brandId)
{
IEnumerable<Brand> brands = _db.Brands;
IQueryable<Phone> phones = _db.Phones
.AsQueryable();
IQueryable<Phone> phones = _db.Phones.AsQueryable();
if (brandId is > 0)
phones = _db.Phones.Where(p => p.BrandId == brandId);
......@@ -66,38 +58,23 @@ namespace PhoneStore.Controllers
{
if (ModelState.IsValid)
{
string imagePath;
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();
await _phoneService.CreateAsync(model);
return RedirectToAction("Index");
}
model.Brands = _db.Brands.ToList();
return View("Create", model);
}
//TODO: Добавить кастомный exception
catch (FileNotFoundException e)
catch (FileNotFoundException)
{
return RedirectToAction("Error", "Errors", new {statusCode = 666});
}
model.Brands = _db.Brands.ToList();
return View("Create", model);
catch(Exception)
{
return RedirectToAction("Error", "Errors", new {statusCode = 777});
}
}
[HttpGet]
......@@ -105,7 +82,7 @@ namespace PhoneStore.Controllers
{
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null)
return BadRequest();
return RedirectToAction("Error", "Errors", new {statusCode = 777});
return View(phone);
}
......@@ -114,6 +91,7 @@ namespace PhoneStore.Controllers
[ActionName("Delete")]
public IActionResult Confirm(int phoneId)
{
//TODO: Добавить удаление файла изображения.
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null)
return BadRequest();
......@@ -129,50 +107,34 @@ namespace PhoneStore.Controllers
var brands = _db.Brands.ToList();
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
if (phone is null)
{
return BadRequest();
}
return RedirectToAction("Error", "Errors", new {statusCode = 777});
PhoneCreateViewModel model = new PhoneCreateViewModel
{
Id = phone.Id,
Name = phone.Name,
Price = phone.Price,
BrandId = (int)phone.BrandId,
Image = phone.Image,
Brands = brands
};
return View(model);
}
[HttpPost]
public IActionResult Edit(Phone phone)
public IActionResult Edit(PhoneCreateViewModel model)
{
if (phone is null)
{
return BadRequest();
}
if (model is null)
return RedirectToAction("Error", "Errors", new {statusCode = 777});
string imagePath = string.Empty;
if (model.File is null)
imagePath = model.Image;
_db.Phones.Update(phone);
_db.Phones.Update(model.MapToPhone(imagePath));
_db.SaveChanges();
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]
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
services.AddTransient<UploadService>();
services.AddTransient<IDefaultPhoneImagePathProvider>(_ =>
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.
......
......@@ -19,5 +19,6 @@ namespace PhoneStore.ViewModels
public int BrandId { get; set; }
public List<Brand> Brands { get; set; }
public IFormFile File { get; set; }
public string Image { get; set; }
}
}
\ No newline at end of file
......@@ -11,8 +11,11 @@
await Html.RenderPartialAsync("PartialViews/PhoneFormPartialView");
}
<input type="text" hidden asp-for="@Model.Id">
<input type="text" hidden asp-for="@Model.Image">
<button type="submit"
class="btn btn-outline-warning">Изменить</button>
class="btn btn-outline-warning">
Изменить
</button>
</form>
</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