< Summary

Information
Class: OzonOrdersWeb.Areas.Studio2.Controllers.OzonProductAttributesController
Assembly: OzonOrdersWeb
File(s): /home/runner/work/Studio2Prod/Studio2Prod/OzonOrdersWeb/Areas/Studio2/Controllers/OzonProductAttributesController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 59
Coverable lines: 59
Total lines: 126
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%
GetByOrderId()0%1056320%
<GetByOrderId()100%210%

File(s)

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

#LineLine coverage
 1using Microsoft.AspNetCore.Authorization;
 2using Microsoft.AspNetCore.Mvc;
 3using Microsoft.Extensions.Caching.Memory;
 4using OzonDomains.Models;
 5using Services.ApiServices.OzonApi;
 6using Services.ApiServices.OzonApi.Filters;
 7using Services.DataServices;
 8
 9namespace OzonOrdersWeb.Areas.Studio2.Controllers;
 10
 11[Area("Studio2")]
 12[Authorize(Roles = "User,Admin")]
 13public class OzonProductAttributesController : Controller
 14{
 15    private readonly OrdersDataServices _ordersDataServices;
 16    private readonly OzonApiDataManager _ozonApiDataManager;
 17    private readonly OzonClientServices _ozonClientServices;
 18    private readonly IMemoryCache _cache;
 19
 020    public OzonProductAttributesController(
 021        OrdersDataServices ordersDataServices,
 022        OzonApiDataManager ozonApiDataManager,
 023        OzonClientServices ozonClientServices,
 024        IMemoryCache cache)
 25    {
 026        _ordersDataServices = ordersDataServices;
 027        _ozonApiDataManager = ozonApiDataManager;
 028        _ozonClientServices = ozonClientServices;
 029        _cache = cache;
 030    }
 31
 32    /// <summary>
 33    /// Получить описание характеристик товара Ozon по id заказа.
 34    /// Для фильтра используется `product_id`, равный `order.ProductInfo.OzonProductId`.
 35    /// </summary>
 36    /// <param name="orderId">Id заказа.</param>
 37    /// <param name="lastId">last_id для постраничной навигации (пусто для первого запроса).</param>
 38    /// <param name="limit">Количество элементов на странице.</param>
 39    /// <param name="sortBy">Параметр сортировки: sku / offer_id / id / title.</param>
 40    /// <param name="sortDir">Направление сортировки: ASC / DESC.</param>
 41    [HttpGet]
 42    public async Task<IActionResult> GetByOrderId(
 43        int orderId,
 44        string lastId = "",
 45        int limit = 100,
 46        string sortBy = "id",
 47        string sortDir = "ASC")
 48    {
 049        if (orderId <= 0)
 50        {
 051            return BadRequest("Parameter `orderId` must be > 0.");
 52        }
 53
 054        limit = Math.Clamp(limit, 1, 1000);
 055        sortBy = string.IsNullOrWhiteSpace(sortBy) ? "id" : sortBy;
 056        sortDir = string.IsNullOrWhiteSpace(sortDir) ? "ASC" : sortDir;
 57
 058        var order = await _ordersDataServices.GetOrder(orderId).ConfigureAwait(false);
 059        if (order == null)
 60        {
 061            return NotFound();
 62        }
 63
 064        if (order.OzonClientId == null || order.OzonClientId.Value <= 0)
 65        {
 066            return BadRequest("Order does not have a valid `OzonClientId`.");
 67        }
 68
 069        var ozonClient = await _ozonClientServices.GetOzonClientAsync(order.OzonClientId.Value).ConfigureAwait(false);
 070        if (ozonClient == null)
 71        {
 072            return BadRequest("Ozon client not found.");
 73        }
 74
 075        var clientId = ozonClient.DecryptClientId ?? ozonClient.ClientId ?? "";
 076        var apiKey = ozonClient.DecryptApiKey ?? ozonClient.ApiKey ?? "";
 077        if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(apiKey))
 78        {
 079            return BadRequest("Ozon client credentials are missing.");
 80        }
 81
 082        var ozonProductId = order.ProductInfo?.OzonProductId;
 083        if (string.IsNullOrWhiteSpace(ozonProductId))
 84        {
 085            return BadRequest("Order does not have `ProductInfo.OzonProductId`.");
 86        }
 87
 088        _ozonApiDataManager.SetClient(clientId, apiKey);
 89
 090        var normalizedLastId = lastId ?? "";
 091        var cacheKey = string.Join("_",
 092            "OzonProductAttributes",
 093            ozonClient.Id,
 094            ozonProductId,
 095            normalizedLastId,
 096            limit,
 097            sortBy,
 098            sortDir);
 99
 100        try
 101        {
 0102            var response = await _cache.GetOrCreateAsync(
 0103                    cacheKey,
 0104                    async entry =>
 0105                    {
 0106                        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
 0107
 0108                        return await _ozonApiDataManager.GetProductAttributesAsync(
 0109                                productIds: [ozonProductId],
 0110                                lastId: normalizedLastId,
 0111                                limit: limit,
 0112                                sortBy: sortBy,
 0113                                sortDir: sortDir)
 0114                            .ConfigureAwait(false);
 0115                    })
 0116                .ConfigureAwait(false);
 117
 0118            return Ok(response);
 119        }
 0120        catch (Exception ex)
 121        {
 0122            return StatusCode(502, new { error = "Ошибка при запросе к Ozon API", details = ex.Message });
 123        }
 0124    }
 125}
 126