< Summary

Information
Class: OzonOrdersWeb.Areas.Studio2.Controllers.TransactionFilesController
Assembly: OzonOrdersWeb
File(s): /home/runner/work/Studio2Prod/Studio2Prod/OzonOrdersWeb/Areas/Studio2/Controllers/TransactionFilesController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 90
Coverable lines: 90
Total lines: 172
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 122
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%
UploadFile()0%110100%
DownloadFile()0%620%
GetThumbnail()0%3192560%
GetFileForPreview()0%2970540%

File(s)

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

#LineLine coverage
 1using Microsoft.AspNetCore.Authorization;
 2using Microsoft.AspNetCore.Mvc;
 3using Services.ApiServices.DropBoxApi;
 4using Services.DataServices;
 5
 6namespace OzonOrdersWeb.Areas.Studio2.Controllers;
 7
 8[Authorize(Roles = "Admin")]
 9[Area("Studio2")]
 10public class TransactionFilesController : Controller
 11{
 12    private readonly DropboxApiClient _dropboxClient;
 13    private readonly OrdersDataServices _orderDataServices;
 14
 015    public TransactionFilesController(DropboxApiClient dropboxClient,
 016        OrdersDataServices orderDataServices)
 17    {
 018        _dropboxClient = dropboxClient;
 019        _orderDataServices = orderDataServices;
 020    }
 21
 22    [HttpPost]
 23    public async Task<IActionResult> UploadFile(IFormFile file, [FromForm] List<int> orderIds)
 24    {
 025        if (file == null || file.Length == 0)
 026            return BadRequest(new { error = "Файл не выбран" });
 27
 028        if (orderIds == null || orderIds.Count == 0)
 029            return BadRequest(new { error = "Не указан ни один заказ" });
 30
 31        try
 32        {
 33            // Используем оригинальное имя файла
 034            var fileName = file.FileName;
 35
 36            // Сохраняем временный файл на сервере
 037            var tempFilePath = Path.Combine(Path.GetTempPath(), fileName);
 038            using (var stream = new FileStream(tempFilePath, FileMode.Create))
 39            {
 040                await file.CopyToAsync(stream);
 041            }
 42
 043            var dropboxFolderPath = "/Приложения/Studio2/ФайлыЗаказов";
 044            await _dropboxClient.UploadFileAsync(tempFilePath, dropboxFolderPath, fileName);
 45
 046            var fullPath = $"{dropboxFolderPath}/{fileName}";
 47
 048            foreach (var orderId in orderIds)
 49            {
 050                await _orderDataServices.SetTransactionDocumentAsync(orderId, fullPath);
 51            }
 52
 53            // Удаляем временный файл
 054            System.IO.File.Delete(tempFilePath);
 55
 056            return Ok(new { message = "Файл успешно загружен", fullPath });
 57        }
 058        catch (Exception ex)
 59        {
 060            return StatusCode(500, new { error = $"Ошибка при загрузке файла: {ex.Message}" });
 61        }
 062    }
 63
 64    [HttpGet]
 65    public async Task<IActionResult> DownloadFile(int orderId)
 66    {
 067        var dropboxFilePath = await _orderDataServices.GetTransactionDocument(orderId);
 068        if (string.IsNullOrEmpty(dropboxFilePath))
 069            return NotFound(new { error = "Файл для этого заказа не найден" });
 70        try
 71        {
 072            var lastSlashIndex = dropboxFilePath.LastIndexOf('/');
 073            var folderPath = dropboxFilePath.Substring(0, lastSlashIndex);
 074            var fileName = dropboxFilePath.Substring(lastSlashIndex + 1);
 75
 076            var downloadLink = await _dropboxClient.GetDownloadLinkAsync(folderPath, fileName);
 077            return Redirect(downloadLink);
 78        }
 079        catch (Exception ex)
 80        {
 081            return StatusCode(500, new { error = $"Ошибка при получении ссылки: {ex.Message}" });
 82        }
 083    }
 84
 85    [HttpGet]
 86    [HttpHead]
 87    public async Task<IActionResult> GetThumbnail(int orderId)
 88    {
 89        try
 90        {
 091            var dropboxFilePath = await _orderDataServices.GetTransactionDocument(orderId);
 092            if (string.IsNullOrEmpty(dropboxFilePath))
 093                return NotFound(new { error = "Файл для этого заказа не найден" });
 94
 095            var lastSlashIndex = dropboxFilePath.LastIndexOf('/');
 096            var folderPath = dropboxFilePath.Substring(0, lastSlashIndex);
 097            var fileName = dropboxFilePath.Substring(lastSlashIndex + 1);
 98
 99            // Определяем MIME-тип по расширению файла
 0100            var extension = Path.GetExtension(fileName).ToLowerInvariant();
 0101            var contentType = extension switch
 0102            {
 0103                ".pdf" => "application/pdf",
 0104                ".jpg" or ".jpeg" => "image/jpeg",
 0105                ".png" => "image/png",
 0106                ".gif" => "image/gif",
 0107                ".bmp" => "image/bmp",
 0108                ".webp" => "image/webp",
 0109                ".doc" => "application/msword",
 0110                ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
 0111                ".xls" => "application/vnd.ms-excel",
 0112                ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
 0113                _ => "application/octet-stream"
 0114            };
 115
 116            // Для HEAD запроса возвращаем только заголовки
 0117            if (Request.Method == "HEAD")
 118            {
 0119                Response.ContentType = contentType;
 0120                return NoContent();
 121            }
 122
 123            // Для GET запроса загружаем и возвращаем файл
 0124            var fileBytes = await _dropboxClient.DownloadFileAsync(folderPath, fileName);
 0125            return File(fileBytes, contentType);
 126        }
 0127        catch (Exception ex)
 128        {
 0129            return NotFound($"Ошибка при загрузке миниатюры: {ex.Message}");
 130        }
 0131    }
 132
 133    [HttpGet]
 134    public async Task<IActionResult> GetFileForPreview(int orderId)
 135    {
 136        try
 137        {
 0138            var dropboxFilePath = await _orderDataServices.GetTransactionDocument(orderId);
 0139            if (string.IsNullOrEmpty(dropboxFilePath))
 0140                return NotFound(new { error = "Файл для этого заказа не найден" });
 141
 0142            var lastSlashIndex = dropboxFilePath.LastIndexOf('/');
 0143            var folderPath = dropboxFilePath.Substring(0, lastSlashIndex);
 0144            var fileName = dropboxFilePath.Substring(lastSlashIndex + 1);
 145
 0146            var fileBytes = await _dropboxClient.DownloadFileAsync(folderPath, fileName);
 147
 148            // Определяем MIME-тип по расширению файла
 0149            var extension = Path.GetExtension(fileName).ToLowerInvariant();
 0150            var contentType = extension switch
 0151            {
 0152                ".pdf" => "application/pdf",
 0153                ".jpg" or ".jpeg" => "image/jpeg",
 0154                ".png" => "image/png",
 0155                ".gif" => "image/gif",
 0156                ".bmp" => "image/bmp",
 0157                ".webp" => "image/webp",
 0158                ".doc" => "application/msword",
 0159                ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
 0160                ".xls" => "application/vnd.ms-excel",
 0161                ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
 0162                _ => "application/octet-stream"
 0163            };
 164
 0165            return File(fileBytes, contentType);
 166        }
 0167        catch (Exception ex)
 168        {
 0169            return NotFound($"Ошибка при загрузке файла: {ex.Message}");
 170        }
 0171    }
 172}