< Summary

Information
Class: OzonOrdersWeb.Areas.Studio2.Controllers.PriceHistoryController
Assembly: OzonOrdersWeb
File(s): /home/runner/work/Studio2Prod/Studio2Prod/OzonOrdersWeb/Areas/Studio2/Controllers/PriceHistoryController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 70
Coverable lines: 70
Total lines: 178
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 32
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
Index()0%7280%
SearchByArticle(...)100%210%
SearchByBitrixId()100%210%
Create()100%210%
Create()0%110100%
Details()0%620%
Edit()0%620%
Edit()0%2040%
Delete()0%620%

File(s)

/home/runner/work/Studio2Prod/Studio2Prod/OzonOrdersWeb/Areas/Studio2/Controllers/PriceHistoryController.cs

#LineLine coverage
 1using Microsoft.AspNetCore.Authorization;
 2using Microsoft.AspNetCore.Mvc;
 3using OzonRepositories.Data.Bitrix;
 4using Services.DataServices;
 5
 6namespace OzonOrdersWeb.Areas.Studio2.Controllers;
 7
 8[Authorize(Roles = "User,Admin")]
 9[Area("Studio2")]
 10public class PriceHistoryController : Controller
 11{
 12    private const int LastRecordsLimit = 1000;
 13
 14    private readonly IPriceHistoryDataService _priceHistoryService;
 15
 016    public PriceHistoryController(IPriceHistoryDataService priceHistoryService)
 17    {
 018        _priceHistoryService = priceHistoryService;
 019    }
 20
 21    /// <summary>Последние записи (или все записи артикула) для грида AG Grid: фильтры и сортировка — на клиенте.</summa
 22    public async Task<IActionResult> Index(string? article)
 23    {
 024        ViewBag.Article = article?.Trim();
 025        ViewBag.LastLimit = LastRecordsLimit;
 26        try
 27        {
 028            var records = string.IsNullOrWhiteSpace(article)
 029                ? await _priceHistoryService.GetLastPriceHistoriesAsync(LastRecordsLimit)
 030                : await _priceHistoryService.GetPriceHistoriesByArticleAsync(article.Trim());
 031            return View(records);
 32        }
 033        catch (Exception ex)
 34        {
 035            ModelState.AddModelError("", $"Ошибка при загрузке данных: {ex.Message}");
 036            return View(new List<PriceHistory>());
 37        }
 038    }
 39
 40    /// <summary>Старый адрес поиска (ссылка из карточки записи) — теперь поиск в гриде Index.</summary>
 41    [HttpGet, HttpPost]
 042    public IActionResult SearchByArticle(string? article) => RedirectToAction(nameof(Index), new { article });
 43
 44    [HttpGet]
 45    public async Task<IActionResult> SearchByBitrixId(int bitrixId)
 46    {
 47        try
 48        {
 049            var results = await _priceHistoryService.GetPriceHistoriesByBitrixIdAsync(bitrixId);
 050            return Ok(results);
 51        }
 052        catch (Exception ex)
 53        {
 054            return StatusCode(500, new { error = $"Ошибка при поиске: {ex.Message}" });
 55        }
 056    }
 57
 58    public IActionResult Create()
 59    {
 060        return View();
 61    }
 62
 63    [HttpPost]
 64    public async Task<IActionResult> Create(PriceHistory model)
 65    {
 066        if (!ModelState.IsValid)
 67        {
 068            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
 69            {
 070                var errors = ModelState.ToDictionary(
 071                    k => k.Key,
 072                    v => v.Value?.Errors.Select(e => e.ErrorMessage).ToArray() ?? Array.Empty<string>()
 073                );
 074                return BadRequest(new { errors });
 75            }
 76
 077            return View(model);
 78        }
 79
 80        try
 81        {
 082            if (model.CreateDateTime == default)
 83            {
 084                model.CreateDateTime = DateTime.Now;
 85            }
 86
 087            await _priceHistoryService.AddPriceHistory(model);
 88
 089            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
 90            {
 091                return Ok(new { success = true, message = "Запись успешно создана!" });
 92            }
 93
 094            TempData["SuccessMessage"] = "Запись успешно создана!";
 095            return RedirectToAction(nameof(Index));
 96        }
 097        catch (Exception ex)
 98        {
 099            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
 100            {
 0101                return StatusCode(500, new { error = $"Ошибка при создании записи: {ex.Message}" });
 102            }
 103
 0104            ModelState.AddModelError("", $"Ошибка при создании записи: {ex.Message}");
 0105            return View(model);
 106        }
 0107    }
 108
 109    public async Task<IActionResult> Details(int id)
 110    {
 0111        var priceHistory = await _priceHistoryService.GetPriceHistoryAsync(id);
 0112        if (priceHistory == null)
 113        {
 0114            return NotFound();
 115        }
 116
 0117        return View(priceHistory);
 0118    }
 119
 120    public async Task<IActionResult> Edit(int id)
 121    {
 0122        var priceHistory = await _priceHistoryService.GetPriceHistoryAsync(id);
 0123        if (priceHistory == null)
 124        {
 0125            return NotFound();
 126        }
 127
 0128        return View(priceHistory);
 0129    }
 130
 131    [HttpPost]
 132    [ValidateAntiForgeryToken]
 133    public async Task<IActionResult> Edit(int id, PriceHistory model)
 134    {
 0135        if (id != model.Id)
 136        {
 0137            return BadRequest();
 138        }
 139
 0140        if (!ModelState.IsValid)
 141        {
 0142            return View(model);
 143        }
 144
 145        try
 146        {
 0147            await _priceHistoryService.UpdatePriceHistory(model);
 0148            TempData["SuccessMessage"] = "Запись успешно обновлена!";
 0149            return RedirectToAction(nameof(Details), new { id = model.Id });
 150        }
 0151        catch (Exception ex)
 152        {
 0153            ModelState.AddModelError("", $"Ошибка при обновлении записи: {ex.Message}");
 0154            return View(model);
 155        }
 0156    }
 157
 158    [HttpPost]
 159    [ValidateAntiForgeryToken]
 160    public async Task<IActionResult> Delete(int id)
 161    {
 162        try
 163        {
 0164            var priceHistory = await _priceHistoryService.GetPriceHistoryAsync(id);
 0165            if (priceHistory == null)
 166            {
 0167                return NotFound();
 168            }
 169
 0170            await _priceHistoryService.DeletePriceHistory(priceHistory);
 0171            return Content("ok");
 172        }
 0173        catch (Exception ex)
 174        {
 0175            return BadRequest($"Ошибка при удалении записи: {ex.Message}");
 176        }
 0177    }
 178}