| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using iText.Kernel.Pdf; |
| | | 3 | | using System.Text; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using iText.Kernel.Utils; |
| | | 6 | | using Microsoft.AspNetCore.Authorization; |
| | | 7 | | using Microsoft.AspNetCore.Mvc; |
| | | 8 | | using Microsoft.EntityFrameworkCore; |
| | | 9 | | using Microsoft.Extensions.Caching.Memory; |
| | | 10 | | using OzonDomains.Models; |
| | | 11 | | using OzonRepositories.Context; |
| | | 12 | | using Services.ApiServices.OzonApi; |
| | | 13 | | using Services.DataServices; |
| | | 14 | | |
| | | 15 | | namespace OzonOrdersWeb.Areas.Public.Controllers; |
| | | 16 | | |
| | | 17 | | [Area("Public")] |
| | | 18 | | [AllowAnonymous] |
| | | 19 | | public class AssemblyListController : Controller |
| | | 20 | | { |
| | 0 | 21 | | private static readonly JsonSerializerOptions CamelCaseOptions = new() |
| | 0 | 22 | | { |
| | 0 | 23 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 0 | 24 | | }; |
| | | 25 | | |
| | | 26 | | private readonly ApplicationDbContext _db; |
| | | 27 | | private readonly OzonClientServices _ozonClientServices; |
| | | 28 | | private readonly IMemoryCache _cache; |
| | | 29 | | private readonly AssemblyListGenerationOrchestrator _orchestrator; |
| | | 30 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 31 | | private readonly ILogger<AssemblyListController> _logger; |
| | | 32 | | |
| | 0 | 33 | | public AssemblyListController( |
| | 0 | 34 | | ApplicationDbContext db, |
| | 0 | 35 | | OzonClientServices ozonClientServices, |
| | 0 | 36 | | IMemoryCache cache, |
| | 0 | 37 | | AssemblyListGenerationOrchestrator orchestrator, |
| | 0 | 38 | | IHttpClientFactory httpClientFactory, |
| | 0 | 39 | | ILogger<AssemblyListController> logger) |
| | | 40 | | { |
| | 0 | 41 | | _db = db; |
| | 0 | 42 | | _ozonClientServices = ozonClientServices; |
| | 0 | 43 | | _cache = cache; |
| | 0 | 44 | | _orchestrator = orchestrator; |
| | 0 | 45 | | _httpClientFactory = httpClientFactory; |
| | 0 | 46 | | _logger = logger; |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | // ─── Key validation ─────────────────────────────────────────────────────── |
| | | 50 | | |
| | | 51 | | private async Task<AssemblyListAccessKey?> ValidateKeyAsync(string accessKey, int clientId) |
| | | 52 | | { |
| | 0 | 53 | | var key = await _db.AssemblyListAccessKeys |
| | 0 | 54 | | .FirstOrDefaultAsync(k => k.AccessKey == accessKey |
| | 0 | 55 | | && k.IsActive |
| | 0 | 56 | | && (k.ExpiresAt == null || k.ExpiresAt > DateTime.UtcNow)); |
| | 0 | 57 | | if (key == null) return null; |
| | 0 | 58 | | if (!key.AllowedClientIdList.Contains(clientId)) return null; |
| | 0 | 59 | | return key; |
| | 0 | 60 | | } |
| | | 61 | | |
| | | 62 | | private static bool IsStatusAllowed(AssemblyListAccessKey key, string status) => |
| | 0 | 63 | | key.AllowedStatusList.Count == 0 |
| | 0 | 64 | | || key.AllowedStatusList.Contains(status, StringComparer.OrdinalIgnoreCase); |
| | | 65 | | |
| | | 66 | | private static bool IsWarehouseAllowed(AssemblyListAccessKey key, string warehouse) => |
| | 0 | 67 | | key.AllowedWarehouseList.Count == 0 |
| | 0 | 68 | | || key.AllowedWarehouseList.Contains(warehouse, StringComparer.OrdinalIgnoreCase); |
| | | 69 | | |
| | | 70 | | private IActionResult InvalidAccessStub() |
| | | 71 | | { |
| | 0 | 72 | | Response.StatusCode = StatusCodes.Status404NotFound; |
| | 0 | 73 | | if (HttpMethods.IsHead(Request.Method)) |
| | 0 | 74 | | return new EmptyResult(); |
| | | 75 | | |
| | 0 | 76 | | return View("AccessDenied"); |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | // ─── GET /public/assembly/{accessKey} ──────────────────────────────────── |
| | | 80 | | |
| | | 81 | | [AcceptVerbs("GET", "HEAD")] |
| | | 82 | | [Route("public/assembly/{accessKey}")] |
| | | 83 | | public async Task<IActionResult> Index(string accessKey) |
| | | 84 | | { |
| | 0 | 85 | | if (!int.TryParse(Request.Query["clientId"], out var clientId)) |
| | 0 | 86 | | return InvalidAccessStub(); |
| | | 87 | | |
| | 0 | 88 | | var key = await ValidateKeyAsync(accessKey, clientId); |
| | 0 | 89 | | if (key == null) |
| | | 90 | | { |
| | 0 | 91 | | _logger.LogWarning("Public assembly denied: invalid key or client, key={AccessKey}, clientId={ClientId}", ac |
| | 0 | 92 | | return InvalidAccessStub(); |
| | | 93 | | } |
| | | 94 | | |
| | 0 | 95 | | var status = Request.Query["status"].ToString(); |
| | 0 | 96 | | if (string.IsNullOrEmpty(status)) status = "awaiting_deliver"; |
| | 0 | 97 | | if (!IsStatusAllowed(key, status)) |
| | | 98 | | { |
| | 0 | 99 | | _logger.LogWarning("Public assembly denied: status not allowed, keyId={KeyId}, status={Status}", key.Id, sta |
| | 0 | 100 | | return InvalidAccessStub(); |
| | | 101 | | } |
| | | 102 | | |
| | 0 | 103 | | var warehouse = Request.Query["warehouse"].ToString(); |
| | 0 | 104 | | if (!string.IsNullOrEmpty(warehouse) && !IsWarehouseAllowed(key, warehouse)) |
| | | 105 | | { |
| | 0 | 106 | | _logger.LogWarning("Public assembly denied: warehouse not allowed, keyId={KeyId}, warehouse={Warehouse}", ke |
| | 0 | 107 | | return InvalidAccessStub(); |
| | | 108 | | } |
| | | 109 | | |
| | 0 | 110 | | var (periodFrom, periodTo) = key.ResolvePeriod(); |
| | 0 | 111 | | var from = periodFrom.ToString("yyyy-MM-dd"); |
| | 0 | 112 | | var to = periodTo.ToString("yyyy-MM-dd"); |
| | | 113 | | |
| | 0 | 114 | | var ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; |
| | 0 | 115 | | _logger.LogInformation("Public assembly view: key={KeyId} client={ClientId} warehouse={Warehouse} ip={Ip}", |
| | 0 | 116 | | key.Id, clientId, warehouse, ip); |
| | | 117 | | |
| | 0 | 118 | | var host = $"{Request.Scheme}://{Request.Host}"; |
| | 0 | 119 | | ViewBag.AccessKey = accessKey; |
| | 0 | 120 | | ViewBag.ClientId = clientId; |
| | 0 | 121 | | ViewBag.Status = status; |
| | 0 | 122 | | ViewBag.Warehouse = warehouse; |
| | 0 | 123 | | ViewBag.From = from; |
| | 0 | 124 | | ViewBag.To = to; |
| | 0 | 125 | | ViewBag.OgTitle = AssemblyListOgMetadata.BuildTitle(); |
| | 0 | 126 | | ViewBag.OgDescription = AssemblyListOgMetadata.BuildDescription(from, to, warehouse, status); |
| | 0 | 127 | | ViewBag.OgSiteName = "Interparts"; |
| | 0 | 128 | | ViewBag.OgImageAlt = AssemblyListOgMetadata.BuildImageAlt(warehouse); |
| | 0 | 129 | | ViewBag.OgImageUrl = $"{host}/images/og-assembly-list.jpg"; |
| | 0 | 130 | | ViewBag.OgUrl = $"{host}{Request.Path}{Request.QueryString}"; |
| | | 131 | | |
| | 0 | 132 | | if (HttpMethods.IsHead(Request.Method)) |
| | 0 | 133 | | return new EmptyResult(); |
| | | 134 | | |
| | 0 | 135 | | return View(); |
| | 0 | 136 | | } |
| | | 137 | | |
| | | 138 | | // ─── POST /public/assembly/{accessKey}/generate ────────────────────────── |
| | | 139 | | |
| | | 140 | | [HttpPost] |
| | | 141 | | [Route("public/assembly/{accessKey}/generate")] |
| | | 142 | | public async Task<IActionResult> Generate(string accessKey, [FromBody] PublicGenerateRequest body) |
| | | 143 | | { |
| | 0 | 144 | | if (!IsValidClientId(body.ClientId)) return NotFound(); |
| | | 145 | | |
| | 0 | 146 | | var key = await ValidateKeyAsync(accessKey, body.ClientId); |
| | 0 | 147 | | if (key == null) return NotFound(); |
| | | 148 | | |
| | 0 | 149 | | var status = string.IsNullOrEmpty(body.Status) ? "awaiting_deliver" : body.Status; |
| | 0 | 150 | | if (!IsStatusAllowed(key, status)) return NotFound(); |
| | | 151 | | |
| | 0 | 152 | | var warehouse = body.Warehouse ?? ""; |
| | 0 | 153 | | if (!string.IsNullOrEmpty(warehouse) && !IsWarehouseAllowed(key, warehouse)) return NotFound(); |
| | | 154 | | |
| | 0 | 155 | | var client = await _ozonClientServices.GetOzonClientAsync(body.ClientId); |
| | 0 | 156 | | if (client?.DecryptClientId == null || client.DecryptApiKey == null) |
| | 0 | 157 | | return NotFound(); |
| | | 158 | | |
| | 0 | 159 | | var (cutoffFrom, cutoffTo) = key.ResolvePeriod(); |
| | | 160 | | |
| | 0 | 161 | | var ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; |
| | 0 | 162 | | _logger.LogInformation("Public assembly generate: key={KeyId} client={ClientId} warehouse={Warehouse} ip={Ip}", |
| | 0 | 163 | | key.Id, body.ClientId, warehouse, ip); |
| | | 164 | | |
| | 0 | 165 | | var req = new GenerationRequest( |
| | 0 | 166 | | OzonClientId: body.ClientId, |
| | 0 | 167 | | OzonClientName: client.Name ?? client.DecryptClientId, |
| | 0 | 168 | | DecryptedClientId: client.DecryptClientId, |
| | 0 | 169 | | DecryptedApiKey: client.DecryptApiKey, |
| | 0 | 170 | | CutoffFrom: cutoffFrom, |
| | 0 | 171 | | CutoffTo: cutoffTo, |
| | 0 | 172 | | Status: status, |
| | 0 | 173 | | WarehouseFilter: string.IsNullOrEmpty(warehouse) ? null : warehouse, |
| | 0 | 174 | | PersistItemsInBackground: true); |
| | | 175 | | |
| | 0 | 176 | | var (jobId, dbRunId) = await _orchestrator.StartAsync(req); |
| | 0 | 177 | | return Ok(new { jobId, dbRunId }); |
| | 0 | 178 | | } |
| | | 179 | | |
| | | 180 | | // ─── GET /public/assembly/{accessKey}/progress?jobId= ──────────────────── |
| | | 181 | | |
| | | 182 | | [HttpGet] |
| | | 183 | | [Route("public/assembly/{accessKey}/progress")] |
| | | 184 | | public async Task Progress(string accessKey, string jobId) |
| | | 185 | | { |
| | 0 | 186 | | Response.Headers["Content-Type"] = "text/event-stream"; |
| | 0 | 187 | | Response.Headers["Cache-Control"] = "no-cache"; |
| | 0 | 188 | | Response.Headers["Connection"] = "keep-alive"; |
| | | 189 | | |
| | 0 | 190 | | var timeout = DateTime.UtcNow.AddMinutes(10); |
| | | 191 | | |
| | 0 | 192 | | ConcurrentQueue<AssemblyListProgress>? queue = null; |
| | 0 | 193 | | for (var attempt = 0; attempt < 10 && queue == null; attempt++) |
| | | 194 | | { |
| | 0 | 195 | | queue = _cache.Get<ConcurrentQueue<AssemblyListProgress>>($"al_progress_{jobId}"); |
| | 0 | 196 | | if (queue == null) await Task.Delay(500); |
| | | 197 | | } |
| | | 198 | | |
| | 0 | 199 | | if (queue == null) |
| | | 200 | | { |
| | 0 | 201 | | await WriteSSE(Response, "progress", |
| | 0 | 202 | | JsonSerializer.Serialize(new AssemblyListProgress { IsError = true, ErrorMessage = "Job not found" }, Ca |
| | 0 | 203 | | await Response.Body.FlushAsync(); |
| | 0 | 204 | | return; |
| | | 205 | | } |
| | | 206 | | |
| | 0 | 207 | | while (DateTime.UtcNow < timeout) |
| | | 208 | | { |
| | 0 | 209 | | while (queue.TryDequeue(out var prog)) |
| | | 210 | | { |
| | 0 | 211 | | await WriteSSE(Response, "progress", JsonSerializer.Serialize(prog, CamelCaseOptions)); |
| | 0 | 212 | | await Response.Body.FlushAsync(); |
| | 0 | 213 | | if (prog.IsComplete || prog.IsError) return; |
| | | 214 | | } |
| | 0 | 215 | | await Task.Delay(400); |
| | | 216 | | } |
| | 0 | 217 | | } |
| | | 218 | | |
| | | 219 | | // ─── GET /public/assembly/{accessKey}/result?jobId= ────────────────────── |
| | | 220 | | |
| | | 221 | | [HttpGet] |
| | | 222 | | [Route("public/assembly/{accessKey}/result")] |
| | | 223 | | public IActionResult Result(string accessKey, string jobId) |
| | | 224 | | { |
| | 0 | 225 | | var result = _cache.Get<AssemblyListResult>($"al_result_{jobId}"); |
| | 0 | 226 | | if (result == null) return NotFound(); |
| | 0 | 227 | | return Content(JsonSerializer.Serialize(result, CamelCaseOptions), "application/json"); |
| | | 228 | | } |
| | | 229 | | |
| | | 230 | | // ─── GET /public/assembly/{accessKey}/download-labels?jobId= ───────────── |
| | | 231 | | |
| | | 232 | | [HttpGet] |
| | | 233 | | [Route("public/assembly/{accessKey}/download-labels")] |
| | | 234 | | public async Task<IActionResult> DownloadLabels(string accessKey, string jobId, int clientId) |
| | | 235 | | { |
| | 0 | 236 | | if (clientId <= 0) return NotFound(); |
| | | 237 | | |
| | 0 | 238 | | var key = await ValidateKeyAsync(accessKey, clientId); |
| | 0 | 239 | | if (key == null) return NotFound(); |
| | | 240 | | |
| | 0 | 241 | | var result = _cache.Get<AssemblyListResult>($"al_result_{jobId}"); |
| | 0 | 242 | | if (result == null) return NotFound(); |
| | | 243 | | |
| | 0 | 244 | | var labelUrls = result.Items |
| | 0 | 245 | | .Select(i => i.LabelUrl) |
| | 0 | 246 | | .Where(u => !string.IsNullOrWhiteSpace(u)) |
| | 0 | 247 | | .Distinct(StringComparer.Ordinal) |
| | 0 | 248 | | .ToList(); |
| | | 249 | | |
| | 0 | 250 | | if (labelUrls.Count == 0) |
| | 0 | 251 | | return BadRequest("Нет доступных этикеток для скачивания."); |
| | | 252 | | |
| | 0 | 253 | | var httpClient = _httpClientFactory.CreateClient(); |
| | 0 | 254 | | await using var mergedStream = new MemoryStream(); |
| | 0 | 255 | | using var mergedPdf = new PdfDocument(new PdfWriter(mergedStream)); |
| | 0 | 256 | | var mergedAnyPage = false; |
| | | 257 | | |
| | 0 | 258 | | foreach (var labelUrl in labelUrls) |
| | | 259 | | { |
| | 0 | 260 | | if (labelUrl == null || !IsValidOzonUrl(labelUrl)) |
| | | 261 | | continue; |
| | | 262 | | |
| | | 263 | | try |
| | | 264 | | { |
| | 0 | 265 | | var bytes = await httpClient.GetByteArrayAsync(labelUrl); |
| | 0 | 266 | | await using var sourceStream = new MemoryStream(bytes); |
| | 0 | 267 | | using var sourcePdf = new PdfDocument(new PdfReader(sourceStream)); |
| | 0 | 268 | | if (sourcePdf.GetNumberOfPages() <= 0) |
| | 0 | 269 | | continue; |
| | | 270 | | |
| | 0 | 271 | | sourcePdf.CopyPagesTo(1, sourcePdf.GetNumberOfPages(), mergedPdf); |
| | 0 | 272 | | mergedAnyPage = true; |
| | 0 | 273 | | } |
| | 0 | 274 | | catch |
| | | 275 | | { |
| | | 276 | | // best-effort: пропускаем битый/недоступный PDF, продолжаем склейку остальных. |
| | 0 | 277 | | } |
| | | 278 | | } |
| | | 279 | | |
| | 0 | 280 | | if (!mergedAnyPage) |
| | 0 | 281 | | return BadRequest("Не удалось сформировать общий PDF этикеток."); |
| | | 282 | | |
| | 0 | 283 | | mergedPdf.Close(); |
| | 0 | 284 | | var fileName = $"assembly_labels_{DateTime.Now:yyyyMMdd_HHmm}.pdf"; |
| | 0 | 285 | | return File(mergedStream.ToArray(), "application/pdf", fileName); |
| | 0 | 286 | | } |
| | | 287 | | |
| | | 288 | | // ─── GET /public/assembly/{accessKey}/image-proxy?url= ─────────────────── |
| | | 289 | | |
| | | 290 | | [HttpGet] |
| | | 291 | | [Route("public/assembly/{accessKey}/image-proxy")] |
| | | 292 | | public async Task<IActionResult> ImageProxy(string accessKey, string url) |
| | | 293 | | { |
| | 0 | 294 | | if (!IsValidOzonUrl(url)) return BadRequest(); |
| | | 295 | | try |
| | | 296 | | { |
| | 0 | 297 | | var bytes = await _httpClientFactory.CreateClient().GetByteArrayAsync(url); |
| | 0 | 298 | | return File(bytes, "image/jpeg"); |
| | | 299 | | } |
| | 0 | 300 | | catch { return NotFound(); } |
| | 0 | 301 | | } |
| | | 302 | | |
| | | 303 | | // ─── GET /public/assembly/{accessKey}/label-proxy?url= ─────────────────── |
| | | 304 | | |
| | | 305 | | [HttpGet] |
| | | 306 | | [Route("public/assembly/{accessKey}/label-proxy")] |
| | | 307 | | public async Task<IActionResult> LabelProxy(string accessKey, string url) |
| | | 308 | | { |
| | 0 | 309 | | if (!IsValidOzonUrl(url, out var uri)) return BadRequest(); |
| | | 310 | | try |
| | | 311 | | { |
| | 0 | 312 | | var bytes = await _httpClientFactory.CreateClient().GetByteArrayAsync(url); |
| | 0 | 313 | | var fileName = Path.GetFileName(uri!.LocalPath); |
| | 0 | 314 | | Response.Headers["Content-Disposition"] = $"attachment; filename=\"{fileName}\""; |
| | 0 | 315 | | return File(bytes, "application/pdf"); |
| | | 316 | | } |
| | 0 | 317 | | catch { return NotFound(); } |
| | 0 | 318 | | } |
| | | 319 | | |
| | | 320 | | // ─── Helpers ────────────────────────────────────────────────────────────── |
| | | 321 | | |
| | 0 | 322 | | private static bool IsValidClientId(int id) => id > 0; |
| | | 323 | | |
| | 0 | 324 | | private static bool IsValidOzonUrl(string url) => IsValidOzonUrl(url, out _); |
| | | 325 | | |
| | | 326 | | private static bool IsValidOzonUrl(string url, out Uri? uri) |
| | | 327 | | { |
| | 0 | 328 | | uri = null; |
| | 0 | 329 | | if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out uri)) |
| | 0 | 330 | | return false; |
| | 0 | 331 | | var host = uri.Host; |
| | 0 | 332 | | return host.EndsWith(".ozon.ru", StringComparison.OrdinalIgnoreCase) |
| | 0 | 333 | | || host.EndsWith(".ozone.ru", StringComparison.OrdinalIgnoreCase) |
| | 0 | 334 | | || host.EndsWith(".ozonusercontent.com", StringComparison.OrdinalIgnoreCase); |
| | | 335 | | } |
| | | 336 | | |
| | | 337 | | private static async Task WriteSSE(HttpResponse response, string eventName, string data) |
| | | 338 | | { |
| | 0 | 339 | | var sb = new StringBuilder(); |
| | 0 | 340 | | sb.AppendLine($"event: {eventName}"); |
| | 0 | 341 | | sb.AppendLine($"data: {data}"); |
| | 0 | 342 | | sb.AppendLine(); |
| | 0 | 343 | | await response.WriteAsync(sb.ToString()); |
| | 0 | 344 | | } |
| | | 345 | | } |
| | | 346 | | |
| | | 347 | | public class PublicGenerateRequest |
| | | 348 | | { |
| | | 349 | | public int ClientId { get; set; } |
| | | 350 | | public string? Status { get; set; } |
| | | 351 | | public string? From { get; set; } |
| | | 352 | | public string? To { get; set; } |
| | | 353 | | public string? Warehouse { get; set; } |
| | | 354 | | } |