< Summary

Information
Class: OzonOrdersWeb.Areas.Studio2.Controllers.LabelGeneratorController
Assembly: OzonOrdersWeb
File(s): /home/runner/work/Studio2Prod/Studio2Prod/OzonOrdersWeb/Areas/Studio2/Controllers/LabelGeneratorController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 49
Coverable lines: 49
Total lines: 100
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 20
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%
GenerateArticleLabel()0%110100%
PrintLabels(...)0%110100%

File(s)

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

#LineLine coverage
 1using Microsoft.AspNetCore.Authorization;
 2using Microsoft.AspNetCore.Mvc;
 3using Microsoft.EntityFrameworkCore;
 4using System.Security.Claims;
 5using OzonDomains.Models;
 6using Services.DataServices;
 7using Services.LabelServices;
 8
 9namespace OzonOrdersWeb.Areas.Studio2.Controllers;
 10
 11[Area("Studio2")]
 12[Authorize(Roles = "User,Admin")]
 13public class LabelGeneratorController : Controller
 14{
 15    private readonly OrdersDataServices _ordersDataServices;
 16    private readonly BarcodeLabelService _barcodeLabelService;
 17    private readonly ArticleLabelService _articleLabelService;
 18    private readonly ILabelPrintLogService _labelPrintLogService;
 19
 020    public LabelGeneratorController(
 021        OrdersDataServices ordersDataServices,
 022        BarcodeLabelService barcodeLabelService,
 023        ArticleLabelService articleLabelService,
 024        ILabelPrintLogService labelPrintLogService)
 25    {
 026        _ordersDataServices = ordersDataServices;
 027        _barcodeLabelService = barcodeLabelService;
 028        _articleLabelService = articleLabelService;
 029        _labelPrintLogService = labelPrintLogService;
 030    }
 31
 32    /// <summary>
 33    /// GET /Studio2/LabelGenerator/GenerateArticleLabel?orderId=N
 34    /// Генерирует этикетку по артикулу заказа. Если PDF уже есть в хранилище — отдаёт его,
 35    /// иначе создаёт, сохраняет и возвращает.
 36    /// </summary>
 37    [HttpGet]
 38    public async Task<IActionResult> GenerateArticleLabel(int orderId, CancellationToken cancellationToken)
 39    {
 40        // Этикетке нужны пять полей заказа: полный граф (GetOrder: все Include + трекинг + статус корзины)
 41        // на первом обращении после рестарта тянулся до таймаута прокси (504).
 042        var order = await _ordersDataServices.GetAnalyticsQueryable()
 043            .Where(o => o.Id == orderId)
 044            .Select(o => new Order
 045            {
 046                Id = o.Id,
 047                Article = o.Article,
 048                ProductName = o.ProductName,
 049                ProductKey = o.ProductKey,
 050                Quantity = o.Quantity,
 051                EtProducer = o.EtProducer == null ? null : new EtProducer { Name = o.EtProducer.Name }
 052            })
 053            .FirstOrDefaultAsync(cancellationToken);
 054        if (order == null)
 055            return NotFound("Заказ не найден");
 56
 057        if (string.IsNullOrWhiteSpace(order.CleanedArticle))
 058            return BadRequest("У заказа отсутствует артикул");
 59
 060        var result = await _articleLabelService.GetOrCreateWithMetadataAsync(order, cancellationToken);
 061        if (result.WasStored)
 62        {
 063            await _labelPrintLogService.RecordAsync(
 064                [new LabelPrintLogEntry(
 065                    result.FileName,
 066                    order.Id,
 067                    LabelPrintSource.Studio2,
 068                    LabelPrintActorKind.StudioUser,
 069                    User.FindFirstValue(ClaimTypes.NameIdentifier),
 070                    User.Identity?.Name ?? "Неизвестный пользователь")],
 071                cancellationToken);
 72        }
 73
 074        return File(result.Content, "application/pdf");
 075    }
 76
 77    /// <summary>
 78    /// POST /Studio2/LabelGenerator/PrintLabels
 79    /// Принимает список этикеток и возвращает PDF для печати (не сохраняет в Dropbox).
 80    /// </summary>
 81    [HttpPost]
 82    public IActionResult PrintLabels([FromBody] List<LabelRequest> labels)
 83    {
 084        if (labels == null || labels.Count == 0)
 085            return BadRequest("Список этикеток пуст");
 86
 087        if (labels.Count > 500)
 088            return BadRequest("Слишком много этикеток (максимум 500)");
 89
 90        // Для каждой этикетки формируем productName с производителем
 091        foreach (var label in labels)
 92        {
 093            label.ProductName = string.IsNullOrWhiteSpace(label.Producer)
 094                ? label.ProductName
 095                : label.Producer + " " + label.ProductName;
 96        }
 097        var pdfBytes = _barcodeLabelService.GenerateLabelsPdf(labels);
 098        return File(pdfBytes, "application/pdf");
 99    }
 100}