// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV. // // Uso (.NET 10+, aplicación de un solo archivo, sin paquetes): // export INTEGRATION_API_TOKEN=nxl_... // export INTEGRATION_API_URL=http://localhost:4100/integration/v1 # opcional // dotnet run send-batch.cs [ruta/al/archivo.csv] # por defecto ../people.csv // // La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el // programa con el mismo archivo devuelve el resultado original (HTTP 200). using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; const int BatchSize = 1000; const int MaxAttempts = 5; var apiUrl = (Environment.GetEnvironmentVariable("INTEGRATION_API_URL") ?? "http://localhost:4100/integration/v1").TrimEnd('/'); var token = Environment.GetEnvironmentVariable("INTEGRATION_API_TOKEN"); if (string.IsNullOrEmpty(token)) Fail("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones)."); var csvPath = args.Length > 0 ? args[0] : Path.Combine("..", "people.csv"); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var (_, ping) = await Send(HttpMethod.Get, "/ping", null, null); var scopes = string.Join(", ", ping["token"]!["scopes"]!.AsArray().Select(s => s!.GetValue())); Console.WriteLine($"Conectado a {ping["tenant"]!["name"]} · permisos: {scopes}"); // CSV sencillo (sin comas dentro de los campos). En producción use una // biblioteca como CsvHelper. var lines = File.ReadAllLines(csvPath).Where(l => l.Trim() != "").ToArray(); var columns = lines[0].Split(','); var records = lines.Skip(1).Select(line => { var values = line.Split(',').Select(v => v.Trim()).ToArray(); string Get(string name) => values[Array.IndexOf(columns, name)]; var authorization = new JsonObject { ["authorizedOn"] = Get("authorizedOn"), ["channel"] = Get("channel") }; if (Get("policyVersion") != "") authorization["policyVersion"] = Get("policyVersion"); if (Get("evidenceReference") != "") authorization["evidenceReference"] = Get("evidenceReference"); var record = new JsonObject { ["documentType"] = Get("documentType"), ["documentNumber"] = Get("documentNumber"), ["fullName"] = Get("fullName") }; if (Get("email") != "") record["email"] = Get("email"); if (Get("phone") != "") record["phone"] = Get("phone"); record["authorization"] = authorization; return record; }).ToList(); var jsonOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; for (var start = 0; start < records.Count; start += BatchSize) { var chunk = new JsonArray(records.Skip(start).Take(BatchSize).Select(r => (JsonNode)r.DeepClone()).ToArray()); var body = new JsonObject { ["externalReference"] = Path.GetFileName(csvPath), ["records"] = chunk }.ToJsonString(jsonOptions); var key = "personas-" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(body)))[..32]; var (res, batch) = await Send(HttpMethod.Post, "/authorizations", body, key); var replayed = res.Headers.TryGetValues("Idempotent-Replayed", out var v) && v.First() == "true" ? " (reintento: resultado original)" : ""; Console.WriteLine($"\nLote {batch["id"]} · HTTP {(int)res.StatusCode}{replayed}"); Console.WriteLine(" " + string.Join(" · ", batch["counts"]!.AsObject().Select(c => $"{c.Key}: {c.Value}"))); foreach (var r in batch["records"]!.AsArray().Where(r => (string)r!["status"]! == "rejected")) { var issues = string.Join(", ", r!["issues"]!.AsArray().Select(i => $"{i!["field"]} ({i["code"]})")); var line = start + (int)r["index"]! + 2; // la línea 1 es el encabezado Console.WriteLine($" Rechazado · línea {line} del CSV: {issues}"); } } // Envía la solicitud; reintenta errores de red, 409, 429 y 5xx con el mismo cuerpo. async Task<(HttpResponseMessage, JsonNode)> Send(HttpMethod method, string path, string? body, string? idempotencyKey) { for (var attempt = 1; ; attempt++) { var wait = TimeSpan.FromSeconds(Math.Pow(2, attempt - 1)); var request = new HttpRequestMessage(method, apiUrl + path); if (body != null) request.Content = new StringContent(body, Encoding.UTF8, "application/json"); if (idempotencyKey != null) request.Headers.Add("Idempotency-Key", idempotencyKey); try { var res = await http.SendAsync(request); var payload = JsonNode.Parse(await res.Content.ReadAsStringAsync())!; if (res.IsSuccessStatusCode) return (res, payload); var status = (int)res.StatusCode; var retryable = status == 409 || status == 429 || status >= 500; if (!retryable || attempt == MaxAttempts) Fail($"Error {status} {payload["error"]?["code"]}: {payload["error"]?["message"]}"); wait = res.Headers.RetryAfter?.Delta ?? wait; } catch (HttpRequestException e) when (attempt < MaxAttempts) { Console.WriteLine($" Error de red: {e.Message}"); } catch (HttpRequestException e) { Fail($"No se pudo conectar con la API: {e.Message}"); } Console.WriteLine($" Reintento {attempt}/{MaxAttempts - 1} en {wait.TotalSeconds} s…"); await Task.Delay(wait); } } static void Fail(string message) { Console.Error.WriteLine(message); Environment.Exit(1); }