@redcumbrecl/cli 0.1.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +129 -16
- package/dist/cli.js +2531 -488
- package/dist/plantillas/dotnet/_comun.cs +101 -0
- package/dist/plantillas/dotnet/capa/AGENTS.md +31 -0
- package/dist/plantillas/dotnet/capa/Directory.Build.props +9 -0
- package/dist/plantillas/dotnet/recetas/boleta-honorarios/redcumbre/BoletaHonorarios.cs +30 -0
- package/dist/plantillas/dotnet/recetas/boleta-terceros/redcumbre/BoletaTerceros.cs +28 -0
- package/dist/plantillas/dotnet/recetas/consultar-rut/redcumbre/ConsultarRut.cs +23 -0
- package/dist/plantillas/dotnet/recetas/factura/redcumbre/Factura.cs +33 -0
- package/dist/plantillas/php/_comun.php +135 -0
- package/dist/plantillas/php/capa/AGENTS.md +31 -0
- package/dist/plantillas/php/recetas/boleta-honorarios/redcumbre/boleta-honorarios.php +24 -0
- package/dist/plantillas/php/recetas/boleta-terceros/redcumbre/boleta-terceros.php +22 -0
- package/dist/plantillas/php/recetas/consultar-rut/redcumbre/consultar-rut.php +25 -0
- package/dist/plantillas/php/recetas/factura/redcumbre/factura.php +34 -0
- package/dist/plantillas/python/_comun.py +105 -0
- package/dist/plantillas/python/capa/AGENTS.md +31 -0
- package/dist/plantillas/python/recetas/boleta-honorarios/redcumbre_boleta_honorarios.py +27 -0
- package/dist/plantillas/python/recetas/boleta-terceros/redcumbre_boleta_terceros.py +25 -0
- package/dist/plantillas/python/recetas/consultar-rut/redcumbre_consultar_rut.py +21 -0
- package/dist/plantillas/python/recetas/factura/redcumbre_factura.py +30 -0
- package/dist/plantillas/typescript/_comun.ts +98 -0
- package/dist/plantillas/typescript/capa/AGENTS.md +31 -0
- package/dist/plantillas/typescript/recetas/boleta-honorarios/redcumbre/boleta-honorarios.ts +23 -0
- package/dist/plantillas/typescript/recetas/boleta-terceros/redcumbre/boleta-terceros.ts +21 -0
- package/dist/plantillas/typescript/recetas/consultar-rut/redcumbre/consultar-rut.ts +17 -0
- package/dist/plantillas/typescript/recetas/factura/redcumbre/factura.ts +24 -0
- package/package.json +1 -1
- package/dist/plantillas/dotnet/AGENTS.md +0 -24
- package/dist/plantillas/dotnet/Program.cs +0 -106
- package/dist/plantillas/dotnet/Redcumbre/LlaveRedcumbre.cs +0 -48
- package/dist/plantillas/php/AGENTS.md +0 -24
- package/dist/plantillas/php/redcumbre/ejemplo.php +0 -117
- package/dist/plantillas/php/redcumbre/llave.php +0 -48
- package/dist/plantillas/python/AGENTS.md +0 -24
- package/dist/plantillas/python/redcumbre_ejemplo.py +0 -97
- package/dist/plantillas/python/redcumbre_llave.py +0 -38
- package/dist/plantillas/typescript/AGENTS.md +0 -24
- package/dist/plantillas/typescript/redcumbre/ejemplo.ts +0 -82
- package/dist/plantillas/typescript/redcumbre/llave.ts +0 -44
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// ── Lo común a las recetas de REDCUMBRE: la llave del proyecto y las llamadas a la API ──────────────────────────
|
|
2
|
+
// El `.env` no guarda el secreto: guarda la ruta al archivo de la llave (REDCUMBRE_LLAVE_PRUEBA=keys/redcumbre-prueba.json).
|
|
3
|
+
// El archivo queda fuera del control de versiones. Sin paquetes NuGet. Documentación: https://docs.redcumbre.cl
|
|
4
|
+
static class Redcumbre
|
|
5
|
+
{
|
|
6
|
+
public const string ComandoInit = "npx @redcumbrecl/cli init";
|
|
7
|
+
static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(60) };
|
|
8
|
+
|
|
9
|
+
static string Api => (Environment.GetEnvironmentVariable("REDCUMBRE_API_URL") is { Length: > 0 } url ? url : "https://api.redcumbre.cl").TrimEnd('/');
|
|
10
|
+
|
|
11
|
+
/// <summary>Carga el `.env` del proyecto sin pisar las variables que ya vienen del entorno.</summary>
|
|
12
|
+
static void CargarEnv()
|
|
13
|
+
{
|
|
14
|
+
if (!File.Exists(".env")) return;
|
|
15
|
+
foreach (var linea in File.ReadAllLines(".env"))
|
|
16
|
+
{
|
|
17
|
+
var m = Regex.Match(linea, @"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$");
|
|
18
|
+
if (m.Success && Environment.GetEnvironmentVariable(m.Groups[1].Value) is null)
|
|
19
|
+
Environment.SetEnvironmentVariable(m.Groups[1].Value, m.Groups[2].Value.Trim('"', '\''));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
public static int Terminar(string mensaje, int codigo)
|
|
24
|
+
{
|
|
25
|
+
Console.Error.WriteLine(mensaje);
|
|
26
|
+
Environment.Exit(codigo);
|
|
27
|
+
return codigo;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
static JsonNode? LeerLlave(string modo)
|
|
31
|
+
{
|
|
32
|
+
var puntero = Environment.GetEnvironmentVariable($"REDCUMBRE_LLAVE_{modo.ToUpperInvariant()}");
|
|
33
|
+
if (string.IsNullOrEmpty(puntero)) return null;
|
|
34
|
+
if (!File.Exists(puntero)) Terminar($"El .env apunta a {puntero}, pero el archivo no está. Vuelve a conectar el proyecto con «{ComandoInit}».", 1);
|
|
35
|
+
return JsonNode.Parse(File.ReadAllText(puntero));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/// <summary>La respuesta de la API: sólo <c>data</c> o, con <paramref name="completa"/>, el envoltorio entero (con el modo y el cobro).</summary>
|
|
39
|
+
public static async Task<JsonNode?> Pedir(HttpMethod metodo, JsonNode llave, string ruta, object? cuerpo = null, bool completa = false)
|
|
40
|
+
{
|
|
41
|
+
var url = $"{Api}/{Uri.EscapeDataString((string)llave["tenantSlug"]!)}{ruta}";
|
|
42
|
+
using var peticion = new HttpRequestMessage(metodo, url);
|
|
43
|
+
peticion.Headers.Authorization = new AuthenticationHeaderValue("Bearer", (string)llave["token"]!);
|
|
44
|
+
peticion.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
|
45
|
+
if (cuerpo is not null) peticion.Content = new StringContent(JsonSerializer.Serialize(cuerpo), Encoding.UTF8, "application/json");
|
|
46
|
+
using var respuesta = await Http.SendAsync(peticion);
|
|
47
|
+
var texto = await respuesta.Content.ReadAsStringAsync();
|
|
48
|
+
JsonNode? json = null;
|
|
49
|
+
try { json = string.IsNullOrEmpty(texto) ? null : JsonNode.Parse(texto); } catch (JsonException) { json = null; }
|
|
50
|
+
if (!respuesta.IsSuccessStatusCode)
|
|
51
|
+
{
|
|
52
|
+
var detalle = json?["message"]?.ToJsonString() ?? texto[..Math.Min(texto.Length, 300)];
|
|
53
|
+
Terminar($"La API respondió {(int)respuesta.StatusCode} a {metodo} {ruta}: {detalle}", 1);
|
|
54
|
+
}
|
|
55
|
+
if (!completa && json is JsonObject o && o["success"] is JsonValue exito && exito.TryGetValue<bool>(out _) && o.ContainsKey("data")) return o["data"];
|
|
56
|
+
return json;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// <summary>
|
|
60
|
+
/// La llave de prueba del proyecto. Con sólo la llave real, la comprueba con `whoami`, explica y sale con el código 8
|
|
61
|
+
/// sin emitir nada. Sin llave, sale con el código 1 sin llamar a la API.
|
|
62
|
+
/// </summary>
|
|
63
|
+
public static async Task<JsonNode> LlaveDePrueba()
|
|
64
|
+
{
|
|
65
|
+
CargarEnv();
|
|
66
|
+
if (LeerLlave("prueba") is { } prueba) return prueba;
|
|
67
|
+
var real = LeerLlave("real");
|
|
68
|
+
if (real is null)
|
|
69
|
+
{
|
|
70
|
+
Terminar($"El proyecto no tiene llave. Conéctalo con «{ComandoInit}» y vuelve a correr la receta.", 1);
|
|
71
|
+
throw new InvalidOperationException();
|
|
72
|
+
}
|
|
73
|
+
var yo = await Pedir(HttpMethod.Get, real, "/whoami");
|
|
74
|
+
Terminar($"La llave del proyecto es la llave real de {yo?["tenant"]?["nombre"]} ({yo?["tenant"]?["slug"]}). Esta receta funciona sólo en el modo de prueba, " +
|
|
75
|
+
$"así que no emití nada. Agrega la llave de prueba con «{ComandoInit}».", 8);
|
|
76
|
+
throw new InvalidOperationException();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
public static async Task<JsonNode> Escenarios(JsonNode llave) => (await Pedir(HttpMethod.Get, llave, "/modo-prueba/escenarios"))!;
|
|
80
|
+
|
|
81
|
+
/// <summary>Un RUT del registro de prueba que sirve de contraparte en una boleta: persona que no es emisor de prueba.</summary>
|
|
82
|
+
public static string ContraparteDeBoleta(JsonNode e)
|
|
83
|
+
{
|
|
84
|
+
var emisores = e["emisoresTributarios"]!.AsArray().Select(t => (string)t!["rut"]!).ToHashSet();
|
|
85
|
+
foreach (var r in e["ruts"]!.AsArray())
|
|
86
|
+
if ((string)r!["rol"]! == "proveedor" && !emisores.Contains((string)r["rut"]!)) return (string)r["rut"]!;
|
|
87
|
+
Terminar("El modo de prueba de la empresa no trae un RUT de prueba para la contraparte de la boleta.", 1);
|
|
88
|
+
throw new InvalidOperationException();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
public static string EmisorTributario(JsonNode e, string servicio)
|
|
92
|
+
{
|
|
93
|
+
foreach (var t in e["emisoresTributarios"]!.AsArray())
|
|
94
|
+
if ((string)t!["servicio"]! == servicio) return t["id"]!.ToString();
|
|
95
|
+
Terminar($"El modo de prueba de la empresa no trae el emisor de prueba de {servicio}.", 1);
|
|
96
|
+
throw new InvalidOperationException();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
public static string PrimerRut(JsonNode e, string rol) =>
|
|
100
|
+
e["ruts"]!.AsArray().Select(r => r!).FirstOrDefault(r => (string)r["rol"]! == rol)?["rut"]?.ToString() ?? "";
|
|
101
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Instrucciones para agentes de código
|
|
2
|
+
|
|
3
|
+
Este proyecto se integra con **REDCUMBRE** y ya quedó conectado con `npx @redcumbrecl/cli init`: la llave de
|
|
4
|
+
prueba está instalada y el proyecto trae la receta `factura`. Trabaja con el CLI `redcumbre` (o
|
|
5
|
+
`npx @redcumbrecl/cli`): todos sus comandos aceptan `--json` y terminan con un código de salida estable (la tabla está
|
|
6
|
+
en https://docs.redcumbre.cl/cli/).
|
|
7
|
+
|
|
8
|
+
## Modo de prueba y modo real
|
|
9
|
+
|
|
10
|
+
- El proyecto parte en el **modo de prueba**: lo que emites ahí no llega al SII, no consume folios y no se cobra.
|
|
11
|
+
- La **llave real** se agrega con `redcumbre pasar-a-real`, y lo hace una persona: confirma la empresa y los servicios.
|
|
12
|
+
Un documento emitido con la llave real es real ante el SII y no se deshace.
|
|
13
|
+
- `redcumbre estado` dice en qué modo está cada llave; `redcumbre escenarios` lista los emisores y los RUT de prueba.
|
|
14
|
+
|
|
15
|
+
## La llave
|
|
16
|
+
|
|
17
|
+
- Vive en `keys/redcumbre-prueba.json` (y `keys/redcumbre-real.json` cuando la haya). **Nunca** la copies a otro
|
|
18
|
+
archivo, al chat ni a un commit.
|
|
19
|
+
- El `.env` sólo guarda **la ruta** al archivo: `REDCUMBRE_LLAVE_PRUEBA=keys/redcumbre-prueba.json`. `keys/` y
|
|
20
|
+
`.redcumbre/` están en `.gitignore`.
|
|
21
|
+
- `.redcumbre/estado.json` registra la empresa y, por modo, la variable que apunta a la llave. No guarda el secreto.
|
|
22
|
+
|
|
23
|
+
## Qué usar
|
|
24
|
+
|
|
25
|
+
- Las recetas: `redcumbre receta <consultar-rut|factura|boleta-honorarios|boleta-terceros>` agrega una al proyecto,
|
|
26
|
+
sin tocar tus archivos. La de factura se corre con `dotnet run --file redcumbre/Factura.cs`.
|
|
27
|
+
- Cualquier operación de la API: `redcumbre api` las lista, `redcumbre api describir <operación>` explica una y
|
|
28
|
+
`redcumbre api <operación> --json` la ejecuta con la llave de prueba.
|
|
29
|
+
- Los webhooks en tu computador: `redcumbre webhooks escuchar --reenviar-a <url local>`.
|
|
30
|
+
- Si algo falla: `redcumbre doctor` revisa la sesión, la llave y las exclusiones de git.
|
|
31
|
+
- La documentación para agentes: https://docs.redcumbre.cl/llms.txt
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
Agregado por `npx @redcumbrecl/cli init`. Las recetas de REDCUMBRE (`redcumbre/*.cs`) son apps de un solo archivo que
|
|
3
|
+
se corren con `dotnet run` con la ruta del archivo: el proyecto no las compila.
|
|
4
|
+
-->
|
|
5
|
+
<Project>
|
|
6
|
+
<PropertyGroup>
|
|
7
|
+
<DefaultItemExcludes>$(DefaultItemExcludes);redcumbre/**</DefaultItemExcludes>
|
|
8
|
+
</PropertyGroup>
|
|
9
|
+
</Project>
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Receta «boleta-honorarios» de REDCUMBRE, agregada por `redcumbre receta boleta-honorarios`.
|
|
2
|
+
// Se corre con: dotnet run --file redcumbre/BoletaHonorarios.cs
|
|
3
|
+
//
|
|
4
|
+
// Emite una boleta de honorarios en el modo de prueba con el emisor de prueba de tu empresa: no llega al SII. Con sólo
|
|
5
|
+
// la llave real no emite nada. Es una app de un solo archivo (.NET 10 o superior).
|
|
6
|
+
// Sin AOT: las apps de un solo archivo lo traen activo y apaga la serialización JSON de tipos anónimos.
|
|
7
|
+
#:property PublishAot=false
|
|
8
|
+
using System.Net.Http.Headers;
|
|
9
|
+
using System.Text;
|
|
10
|
+
using System.Text.Json;
|
|
11
|
+
using System.Text.Json.Nodes;
|
|
12
|
+
using System.Text.RegularExpressions;
|
|
13
|
+
|
|
14
|
+
var llave = await Redcumbre.LlaveDePrueba();
|
|
15
|
+
var e = await Redcumbre.Escenarios(llave);
|
|
16
|
+
var emitida = await Redcumbre.Pedir(HttpMethod.Post, llave, "/bhe", new
|
|
17
|
+
{
|
|
18
|
+
emisorTributarioId = Redcumbre.EmisorTributario(e, "BHE"),
|
|
19
|
+
sinDestinatario = false,
|
|
20
|
+
lookupRut = Redcumbre.ContraparteDeBoleta(e),
|
|
21
|
+
prestaciones = new[] { new { descripcion = "Asesoría de prueba", valor = "150000" } },
|
|
22
|
+
tipoRetencion = "RETCONTRIBUYENTE",
|
|
23
|
+
enviarBoletaPorEmail = false,
|
|
24
|
+
idempotencyKey = Guid.NewGuid().ToString(),
|
|
25
|
+
});
|
|
26
|
+
var id = emitida?["id"] is { } valor ? $": id {valor}" : "";
|
|
27
|
+
Console.WriteLine($"Boleta de honorarios emitida en el modo de prueba{id}. No llega al SII.");
|
|
28
|
+
return 0;
|
|
29
|
+
|
|
30
|
+
// @redcumbre-comun
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Receta «boleta-terceros» de REDCUMBRE, agregada por `redcumbre receta boleta-terceros`.
|
|
2
|
+
// Se corre con: dotnet run --file redcumbre/BoletaTerceros.cs
|
|
3
|
+
//
|
|
4
|
+
// Emite una boleta de prestación de servicios de terceros en el modo de prueba con el emisor de prueba de tu empresa:
|
|
5
|
+
// no llega al SII. Con sólo la llave real no emite nada. Es una app de un solo archivo (.NET 10 o superior).
|
|
6
|
+
// Sin AOT: las apps de un solo archivo lo traen activo y apaga la serialización JSON de tipos anónimos.
|
|
7
|
+
#:property PublishAot=false
|
|
8
|
+
using System.Net.Http.Headers;
|
|
9
|
+
using System.Text;
|
|
10
|
+
using System.Text.Json;
|
|
11
|
+
using System.Text.Json.Nodes;
|
|
12
|
+
using System.Text.RegularExpressions;
|
|
13
|
+
|
|
14
|
+
var llave = await Redcumbre.LlaveDePrueba();
|
|
15
|
+
var e = await Redcumbre.Escenarios(llave);
|
|
16
|
+
var emitida = await Redcumbre.Pedir(HttpMethod.Post, llave, "/bhet", new
|
|
17
|
+
{
|
|
18
|
+
emisorTributarioId = Redcumbre.EmisorTributario(e, "BHET"),
|
|
19
|
+
lookupRut = Redcumbre.ContraparteDeBoleta(e),
|
|
20
|
+
prestaciones = new[] { new { descripcion = "Servicio de prueba", valor = "100000" } },
|
|
21
|
+
enviarBoletaPorEmail = false,
|
|
22
|
+
idempotencyKey = Guid.NewGuid().ToString(),
|
|
23
|
+
});
|
|
24
|
+
var id = emitida?["id"] is { } valor ? $": id {valor}" : "";
|
|
25
|
+
Console.WriteLine($"Boleta de terceros emitida en el modo de prueba{id}. No llega al SII.");
|
|
26
|
+
return 0;
|
|
27
|
+
|
|
28
|
+
// @redcumbre-comun
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Receta «consultar-rut» de REDCUMBRE, agregada por `redcumbre receta consultar-rut`.
|
|
2
|
+
// Se corre con: dotnet run --file redcumbre/ConsultarRut.cs
|
|
3
|
+
//
|
|
4
|
+
// Consulta en el modo de prueba un RUT del registro de prueba: la respuesta es un dato de prueba, no la del SII.
|
|
5
|
+
// Es una app de un solo archivo (.NET 10 o superior).
|
|
6
|
+
// Sin AOT: las apps de un solo archivo lo traen activo y apaga la serialización JSON de tipos anónimos.
|
|
7
|
+
#:property PublishAot=false
|
|
8
|
+
using System.Net.Http.Headers;
|
|
9
|
+
using System.Text;
|
|
10
|
+
using System.Text.Json;
|
|
11
|
+
using System.Text.Json.Nodes;
|
|
12
|
+
using System.Text.RegularExpressions;
|
|
13
|
+
|
|
14
|
+
var llave = await Redcumbre.LlaveDePrueba();
|
|
15
|
+
var e = await Redcumbre.Escenarios(llave);
|
|
16
|
+
var rut = Redcumbre.PrimerRut(e, "cliente");
|
|
17
|
+
if (rut == "") return Redcumbre.Terminar("El modo de prueba de la empresa no trae un RUT de prueba.", 1);
|
|
18
|
+
var respuesta = await Redcumbre.Pedir(HttpMethod.Post, llave, "/herramientas/lookup-rut", new { rut }, completa: true);
|
|
19
|
+
Console.WriteLine($"RUT {rut}: es un dato de prueba, no la respuesta del SII.");
|
|
20
|
+
Console.WriteLine(respuesta?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
|
21
|
+
return 0;
|
|
22
|
+
|
|
23
|
+
// @redcumbre-comun
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Receta «factura» de REDCUMBRE, agregada por `redcumbre receta factura`. Se corre con: dotnet run --file redcumbre/Factura.cs
|
|
2
|
+
//
|
|
3
|
+
// Emite una factura electrónica en el modo de prueba con el emisor de prueba de tu empresa: no llega al SII ni consume
|
|
4
|
+
// folios. Con sólo la llave real no emite nada. Es una app de un solo archivo (.NET 10 o superior).
|
|
5
|
+
// Sin AOT: las apps de un solo archivo lo traen activo y apaga la serialización JSON de tipos anónimos.
|
|
6
|
+
#:property PublishAot=false
|
|
7
|
+
using System.Net.Http.Headers;
|
|
8
|
+
using System.Text;
|
|
9
|
+
using System.Text.Json;
|
|
10
|
+
using System.Text.Json.Nodes;
|
|
11
|
+
using System.Text.RegularExpressions;
|
|
12
|
+
|
|
13
|
+
var llave = await Redcumbre.LlaveDePrueba();
|
|
14
|
+
var e = await Redcumbre.Escenarios(llave);
|
|
15
|
+
var receptor = Redcumbre.PrimerRut(e, "cliente");
|
|
16
|
+
if (e["emisorDte"] is null || receptor == "")
|
|
17
|
+
return Redcumbre.Terminar("El modo de prueba de la empresa no trae el emisor de prueba o un RUT cliente de prueba.", 1);
|
|
18
|
+
var emitido = await Redcumbre.Pedir(HttpMethod.Post, llave, "/dte", new
|
|
19
|
+
{
|
|
20
|
+
emisorDteId = e["emisorDte"]!["id"]!.ToString(),
|
|
21
|
+
tipoDte = "FACTURA_AFECTA",
|
|
22
|
+
receptor = new { rut = receptor, razonSocial = "CLIENTE DE PRUEBA", giro = "SERVICIOS", direccion = "AV PRUEBA 123", comuna = "PROVIDENCIA", ciudad = "SANTIAGO" },
|
|
23
|
+
lineas = new[] { new { nombre = "Servicio de prueba", cantidad = 1, precioUnitario = 1000, subtotal = 1000 } },
|
|
24
|
+
formaPago = "CONTADO",
|
|
25
|
+
fechaEmision = DateTime.Now.ToString("yyyy-MM-dd"),
|
|
26
|
+
idempotencyKey = Guid.NewGuid().ToString(),
|
|
27
|
+
});
|
|
28
|
+
var dte = emitido!["dte"]!;
|
|
29
|
+
var folio = dte["folio"] is null ? "" : $", folio {dte["folio"]}";
|
|
30
|
+
Console.WriteLine($"Factura emitida en el modo de prueba: id {dte["id"]}{folio}. No llega al SII ni consume folios.");
|
|
31
|
+
return 0;
|
|
32
|
+
|
|
33
|
+
// @redcumbre-comun
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// ── Lo común a las recetas de REDCUMBRE: la llave del proyecto y las llamadas a la API ──────────────────────────
|
|
2
|
+
// El `.env` no guarda el secreto: guarda la ruta al archivo de la llave (REDCUMBRE_LLAVE_PRUEBA=keys/redcumbre-prueba.json).
|
|
3
|
+
// El archivo queda fuera del control de versiones. Sin dependencias de Composer. Documentación: https://docs.redcumbre.cl
|
|
4
|
+
|
|
5
|
+
const REDCUMBRE_COMANDO_INIT = 'npx @redcumbrecl/cli init';
|
|
6
|
+
|
|
7
|
+
function redcumbreApi(): string
|
|
8
|
+
{
|
|
9
|
+
$url = getenv('REDCUMBRE_API_URL');
|
|
10
|
+
return rtrim($url !== false && $url !== '' ? $url : 'https://api.redcumbre.cl', '/');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Carga el `.env` del proyecto sin pisar las variables que ya vienen del entorno. */
|
|
14
|
+
function redcumbreCargarEnv(): void
|
|
15
|
+
{
|
|
16
|
+
if (!is_file('.env')) {
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
foreach (file('.env', FILE_IGNORE_NEW_LINES) as $linea) {
|
|
20
|
+
if (preg_match('/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/', $linea, $m) && getenv($m[1]) === false) {
|
|
21
|
+
putenv($m[1] . '=' . trim($m[2], "\"'"));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function redcumbreTerminar(string $mensaje, int $codigo): never
|
|
27
|
+
{
|
|
28
|
+
fwrite(STDERR, $mensaje . PHP_EOL);
|
|
29
|
+
exit($codigo);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @return array{tenantSlug: string, token: string}|null */
|
|
33
|
+
function redcumbreLeerLlave(string $modo): ?array
|
|
34
|
+
{
|
|
35
|
+
$puntero = getenv('REDCUMBRE_LLAVE_' . strtoupper($modo));
|
|
36
|
+
if ($puntero === false || $puntero === '') {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
if (!is_file($puntero)) {
|
|
40
|
+
redcumbreTerminar("El .env apunta a {$puntero}, pero el archivo no está. Vuelve a conectar el proyecto con «" . REDCUMBRE_COMANDO_INIT . '».', 1);
|
|
41
|
+
}
|
|
42
|
+
return json_decode((string) file_get_contents($puntero), true, 512, JSON_THROW_ON_ERROR);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* La respuesta de la API: sólo `data` o, con `$completa`, el envoltorio entero (con el modo y el cobro).
|
|
47
|
+
*
|
|
48
|
+
* @param array{tenantSlug: string, token: string} $llave
|
|
49
|
+
*/
|
|
50
|
+
function redcumbrePedir(string $metodo, array $llave, string $ruta, mixed $cuerpo = null, bool $completa = false): mixed
|
|
51
|
+
{
|
|
52
|
+
$cabeceras = ['Authorization: Bearer ' . $llave['token'], 'Accept: application/json'];
|
|
53
|
+
$opciones = ['method' => $metodo, 'ignore_errors' => true, 'timeout' => 60];
|
|
54
|
+
if ($cuerpo !== null) {
|
|
55
|
+
$cabeceras[] = 'Content-Type: application/json';
|
|
56
|
+
$opciones['content'] = json_encode($cuerpo, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
|
57
|
+
}
|
|
58
|
+
$opciones['header'] = implode("\r\n", $cabeceras);
|
|
59
|
+
$url = redcumbreApi() . '/' . rawurlencode($llave['tenantSlug']) . $ruta;
|
|
60
|
+
$texto = @file_get_contents($url, false, stream_context_create(['http' => $opciones]));
|
|
61
|
+
if ($texto === false) {
|
|
62
|
+
redcumbreTerminar("No pude conectarme con la API en {$url}.", 1);
|
|
63
|
+
}
|
|
64
|
+
preg_match('#^HTTP/\S+\s+(\d{3})#', $http_response_header[0] ?? '', $m);
|
|
65
|
+
$estado = (int) ($m[1] ?? 0);
|
|
66
|
+
$json = $texto === '' ? null : json_decode($texto, true);
|
|
67
|
+
if ($estado < 200 || $estado >= 300) {
|
|
68
|
+
$detalle = is_array($json) && isset($json['message']) ? (is_string($json['message']) ? $json['message'] : json_encode($json['message'])) : substr($texto, 0, 300);
|
|
69
|
+
redcumbreTerminar("La API respondió {$estado} a {$metodo} {$ruta}: {$detalle}", 1);
|
|
70
|
+
}
|
|
71
|
+
if (!$completa && is_array($json) && is_bool($json['success'] ?? null) && array_key_exists('data', $json)) {
|
|
72
|
+
return $json['data'];
|
|
73
|
+
}
|
|
74
|
+
return $json;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* La llave de prueba del proyecto. Con sólo la llave real, la comprueba con `whoami`, explica y sale con el código 8
|
|
79
|
+
* sin emitir nada. Sin llave, sale con el código 1 sin llamar a la API.
|
|
80
|
+
*
|
|
81
|
+
* @return array{tenantSlug: string, token: string}
|
|
82
|
+
*/
|
|
83
|
+
function redcumbreLlaveDePrueba(): array
|
|
84
|
+
{
|
|
85
|
+
redcumbreCargarEnv();
|
|
86
|
+
$prueba = redcumbreLeerLlave('prueba');
|
|
87
|
+
if ($prueba !== null) {
|
|
88
|
+
return $prueba;
|
|
89
|
+
}
|
|
90
|
+
$real = redcumbreLeerLlave('real');
|
|
91
|
+
if ($real === null) {
|
|
92
|
+
redcumbreTerminar('El proyecto no tiene llave. Conéctalo con «' . REDCUMBRE_COMANDO_INIT . '» y vuelve a correr la receta.', 1);
|
|
93
|
+
}
|
|
94
|
+
$yo = redcumbrePedir('GET', $real, '/whoami');
|
|
95
|
+
redcumbreTerminar(
|
|
96
|
+
"La llave del proyecto es la llave real de {$yo['tenant']['nombre']} ({$yo['tenant']['slug']}). Esta receta funciona sólo en el modo de prueba, "
|
|
97
|
+
. 'así que no emití nada. Agrega la llave de prueba con «' . REDCUMBRE_COMANDO_INIT . '».',
|
|
98
|
+
8,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function redcumbreEscenarios(array $llave): array
|
|
103
|
+
{
|
|
104
|
+
return redcumbrePedir('GET', $llave, '/modo-prueba/escenarios');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Un RUT del registro de prueba que sirve de contraparte en una boleta: persona que no es emisor de prueba. */
|
|
108
|
+
function redcumbreContraparteDeBoleta(array $e): string
|
|
109
|
+
{
|
|
110
|
+
$emisores = array_column($e['emisoresTributarios'], 'rut');
|
|
111
|
+
foreach ($e['ruts'] as $r) {
|
|
112
|
+
if ($r['rol'] === 'proveedor' && !in_array($r['rut'], $emisores, true)) {
|
|
113
|
+
return $r['rut'];
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
redcumbreTerminar('El modo de prueba de la empresa no trae un RUT de prueba para la contraparte de la boleta.', 1);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function redcumbreEmisorTributario(array $e, string $servicio): string
|
|
120
|
+
{
|
|
121
|
+
foreach ($e['emisoresTributarios'] as $t) {
|
|
122
|
+
if ($t['servicio'] === $servicio) {
|
|
123
|
+
return (string) $t['id'];
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
redcumbreTerminar("El modo de prueba de la empresa no trae el emisor de prueba de {$servicio}.", 1);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function redcumbreUuid(): string
|
|
130
|
+
{
|
|
131
|
+
$b = random_bytes(16);
|
|
132
|
+
$b[6] = chr((ord($b[6]) & 0x0f) | 0x40);
|
|
133
|
+
$b[8] = chr((ord($b[8]) & 0x3f) | 0x80);
|
|
134
|
+
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
|
|
135
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Instrucciones para agentes de código
|
|
2
|
+
|
|
3
|
+
Este proyecto se integra con **REDCUMBRE** y ya quedó conectado con `npx @redcumbrecl/cli init`: la llave de
|
|
4
|
+
prueba está instalada y el proyecto trae la receta `factura`. Trabaja con el CLI `redcumbre` (o
|
|
5
|
+
`npx @redcumbrecl/cli`): todos sus comandos aceptan `--json` y terminan con un código de salida estable (la tabla está
|
|
6
|
+
en https://docs.redcumbre.cl/cli/).
|
|
7
|
+
|
|
8
|
+
## Modo de prueba y modo real
|
|
9
|
+
|
|
10
|
+
- El proyecto parte en el **modo de prueba**: lo que emites ahí no llega al SII, no consume folios y no se cobra.
|
|
11
|
+
- La **llave real** se agrega con `redcumbre pasar-a-real`, y lo hace una persona: confirma la empresa y los servicios.
|
|
12
|
+
Un documento emitido con la llave real es real ante el SII y no se deshace.
|
|
13
|
+
- `redcumbre estado` dice en qué modo está cada llave; `redcumbre escenarios` lista los emisores y los RUT de prueba.
|
|
14
|
+
|
|
15
|
+
## La llave
|
|
16
|
+
|
|
17
|
+
- Vive en `keys/redcumbre-prueba.json` (y `keys/redcumbre-real.json` cuando la haya). **Nunca** la copies a otro
|
|
18
|
+
archivo, al chat ni a un commit.
|
|
19
|
+
- El `.env` sólo guarda **la ruta** al archivo: `REDCUMBRE_LLAVE_PRUEBA=keys/redcumbre-prueba.json`. `keys/` y
|
|
20
|
+
`.redcumbre/` están en `.gitignore`.
|
|
21
|
+
- `.redcumbre/estado.json` registra la empresa y, por modo, la variable que apunta a la llave. No guarda el secreto.
|
|
22
|
+
|
|
23
|
+
## Qué usar
|
|
24
|
+
|
|
25
|
+
- Las recetas: `redcumbre receta <consultar-rut|factura|boleta-honorarios|boleta-terceros>` agrega una al proyecto,
|
|
26
|
+
sin tocar tus archivos. La de factura se corre con `php redcumbre/factura.php`.
|
|
27
|
+
- Cualquier operación de la API: `redcumbre api` las lista, `redcumbre api describir <operación>` explica una y
|
|
28
|
+
`redcumbre api <operación> --json` la ejecuta con la llave de prueba.
|
|
29
|
+
- Los webhooks en tu computador: `redcumbre webhooks escuchar --reenviar-a <url local>`.
|
|
30
|
+
- Si algo falla: `redcumbre doctor` revisa la sesión, la llave y las exclusiones de git.
|
|
31
|
+
- La documentación para agentes: https://docs.redcumbre.cl/llms.txt
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
// Receta «boleta-honorarios» de REDCUMBRE, agregada por `redcumbre receta boleta-honorarios`.
|
|
3
|
+
// Se corre con: php redcumbre/boleta-honorarios.php
|
|
4
|
+
//
|
|
5
|
+
// Emite una boleta de honorarios en el modo de prueba con el emisor de prueba de tu empresa: no llega al SII. Con sólo
|
|
6
|
+
// la llave real no emite nada.
|
|
7
|
+
|
|
8
|
+
declare(strict_types=1);
|
|
9
|
+
|
|
10
|
+
// @redcumbre-comun
|
|
11
|
+
|
|
12
|
+
$llave = redcumbreLlaveDePrueba();
|
|
13
|
+
$e = redcumbreEscenarios($llave);
|
|
14
|
+
$emitida = redcumbrePedir('POST', $llave, '/bhe', [
|
|
15
|
+
'emisorTributarioId' => redcumbreEmisorTributario($e, 'BHE'),
|
|
16
|
+
'sinDestinatario' => false,
|
|
17
|
+
'lookupRut' => redcumbreContraparteDeBoleta($e),
|
|
18
|
+
'prestaciones' => [['descripcion' => 'Asesoría de prueba', 'valor' => '150000']],
|
|
19
|
+
'tipoRetencion' => 'RETCONTRIBUYENTE',
|
|
20
|
+
'enviarBoletaPorEmail' => false,
|
|
21
|
+
'idempotencyKey' => redcumbreUuid(),
|
|
22
|
+
]);
|
|
23
|
+
$id = is_array($emitida) && isset($emitida['id']) ? ": id {$emitida['id']}" : '';
|
|
24
|
+
echo "Boleta de honorarios emitida en el modo de prueba{$id}. No llega al SII." . PHP_EOL;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
// Receta «boleta-terceros» de REDCUMBRE, agregada por `redcumbre receta boleta-terceros`.
|
|
3
|
+
// Se corre con: php redcumbre/boleta-terceros.php
|
|
4
|
+
//
|
|
5
|
+
// Emite una boleta de prestación de servicios de terceros en el modo de prueba con el emisor de prueba de tu empresa:
|
|
6
|
+
// no llega al SII. Con sólo la llave real no emite nada.
|
|
7
|
+
|
|
8
|
+
declare(strict_types=1);
|
|
9
|
+
|
|
10
|
+
// @redcumbre-comun
|
|
11
|
+
|
|
12
|
+
$llave = redcumbreLlaveDePrueba();
|
|
13
|
+
$e = redcumbreEscenarios($llave);
|
|
14
|
+
$emitida = redcumbrePedir('POST', $llave, '/bhet', [
|
|
15
|
+
'emisorTributarioId' => redcumbreEmisorTributario($e, 'BHET'),
|
|
16
|
+
'lookupRut' => redcumbreContraparteDeBoleta($e),
|
|
17
|
+
'prestaciones' => [['descripcion' => 'Servicio de prueba', 'valor' => '100000']],
|
|
18
|
+
'enviarBoletaPorEmail' => false,
|
|
19
|
+
'idempotencyKey' => redcumbreUuid(),
|
|
20
|
+
]);
|
|
21
|
+
$id = is_array($emitida) && isset($emitida['id']) ? ": id {$emitida['id']}" : '';
|
|
22
|
+
echo "Boleta de terceros emitida en el modo de prueba{$id}. No llega al SII." . PHP_EOL;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
// Receta «consultar-rut» de REDCUMBRE, agregada por `redcumbre receta consultar-rut`.
|
|
3
|
+
// Se corre con: php redcumbre/consultar-rut.php
|
|
4
|
+
//
|
|
5
|
+
// Consulta en el modo de prueba un RUT del registro de prueba: la respuesta es un dato de prueba, no la del SII.
|
|
6
|
+
|
|
7
|
+
declare(strict_types=1);
|
|
8
|
+
|
|
9
|
+
// @redcumbre-comun
|
|
10
|
+
|
|
11
|
+
$llave = redcumbreLlaveDePrueba();
|
|
12
|
+
$e = redcumbreEscenarios($llave);
|
|
13
|
+
$rut = null;
|
|
14
|
+
foreach ($e['ruts'] as $r) {
|
|
15
|
+
if ($r['rol'] === 'cliente') {
|
|
16
|
+
$rut = $r['rut'];
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if ($rut === null) {
|
|
21
|
+
redcumbreTerminar('El modo de prueba de la empresa no trae un RUT de prueba.', 1);
|
|
22
|
+
}
|
|
23
|
+
$respuesta = redcumbrePedir('POST', $llave, '/herramientas/lookup-rut', ['rut' => $rut], completa: true);
|
|
24
|
+
echo "RUT {$rut}: es un dato de prueba, no la respuesta del SII." . PHP_EOL;
|
|
25
|
+
echo json_encode($respuesta, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
// Receta «factura» de REDCUMBRE, agregada por `redcumbre receta factura`. Se corre con: php redcumbre/factura.php
|
|
3
|
+
//
|
|
4
|
+
// Emite una factura electrónica en el modo de prueba con el emisor de prueba de tu empresa: no llega al SII ni consume
|
|
5
|
+
// folios. Con sólo la llave real no emite nada.
|
|
6
|
+
|
|
7
|
+
declare(strict_types=1);
|
|
8
|
+
|
|
9
|
+
// @redcumbre-comun
|
|
10
|
+
|
|
11
|
+
$llave = redcumbreLlaveDePrueba();
|
|
12
|
+
$e = redcumbreEscenarios($llave);
|
|
13
|
+
$receptor = null;
|
|
14
|
+
foreach ($e['ruts'] as $r) {
|
|
15
|
+
if ($r['rol'] === 'cliente') {
|
|
16
|
+
$receptor = $r['rut'];
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (empty($e['emisorDte']) || $receptor === null) {
|
|
21
|
+
redcumbreTerminar('El modo de prueba de la empresa no trae el emisor de prueba o un RUT cliente de prueba.', 1);
|
|
22
|
+
}
|
|
23
|
+
$emitido = redcumbrePedir('POST', $llave, '/dte', [
|
|
24
|
+
'emisorDteId' => $e['emisorDte']['id'],
|
|
25
|
+
'tipoDte' => 'FACTURA_AFECTA',
|
|
26
|
+
'receptor' => ['rut' => $receptor, 'razonSocial' => 'CLIENTE DE PRUEBA', 'giro' => 'SERVICIOS', 'direccion' => 'AV PRUEBA 123', 'comuna' => 'PROVIDENCIA', 'ciudad' => 'SANTIAGO'],
|
|
27
|
+
'lineas' => [['nombre' => 'Servicio de prueba', 'cantidad' => 1, 'precioUnitario' => 1000, 'subtotal' => 1000]],
|
|
28
|
+
'formaPago' => 'CONTADO',
|
|
29
|
+
'fechaEmision' => date('Y-m-d'),
|
|
30
|
+
'idempotencyKey' => redcumbreUuid(),
|
|
31
|
+
]);
|
|
32
|
+
$dte = $emitido['dte'];
|
|
33
|
+
$folio = empty($dte['folio']) ? '' : ", folio {$dte['folio']}";
|
|
34
|
+
echo "Factura emitida en el modo de prueba: id {$dte['id']}{$folio}. No llega al SII ni consume folios." . PHP_EOL;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# ── Lo común a las recetas de REDCUMBRE: la llave del proyecto y las llamadas a la API ──────────────────────────
|
|
2
|
+
# El `.env` no guarda el secreto: guarda la ruta al archivo de la llave (REDCUMBRE_LLAVE_PRUEBA=keys/redcumbre-prueba.json).
|
|
3
|
+
# El archivo queda fuera del control de versiones. Sólo usa la biblioteca estándar. Documentación: https://docs.redcumbre.cl
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
import uuid
|
|
12
|
+
from datetime import date
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
API = os.environ.get("REDCUMBRE_API_URL", "https://api.redcumbre.cl").rstrip("/")
|
|
16
|
+
COMANDO_INIT = "npx @redcumbrecl/cli init"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def cargar_env() -> None:
|
|
20
|
+
"""Carga el `.env` del proyecto sin pisar las variables que ya vienen del entorno."""
|
|
21
|
+
ruta = Path(".env")
|
|
22
|
+
if not ruta.exists():
|
|
23
|
+
return
|
|
24
|
+
for linea in ruta.read_text(encoding="utf-8").splitlines():
|
|
25
|
+
m = re.match(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$", linea)
|
|
26
|
+
if m and m.group(1) not in os.environ:
|
|
27
|
+
os.environ[m.group(1)] = m.group(2).strip("\"'")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def terminar(mensaje: str, codigo: int):
|
|
31
|
+
print(mensaje, file=sys.stderr)
|
|
32
|
+
sys.exit(codigo)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def leer_llave(modo: str):
|
|
36
|
+
puntero = os.environ.get(f"REDCUMBRE_LLAVE_{modo.upper()}")
|
|
37
|
+
if not puntero:
|
|
38
|
+
return None
|
|
39
|
+
ruta = Path(puntero).resolve()
|
|
40
|
+
if not ruta.exists():
|
|
41
|
+
terminar(f"El .env apunta a {puntero}, pero el archivo no está. Vuelve a conectar el proyecto con «{COMANDO_INIT}».", 1)
|
|
42
|
+
return json.loads(ruta.read_text(encoding="utf-8"))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def pedir(metodo: str, llave: dict, ruta: str, cuerpo=None, completa=False):
|
|
46
|
+
"""La respuesta de la API: sólo `data` o, con `completa`, el envoltorio entero (con el modo y el cobro)."""
|
|
47
|
+
url = f"{API}/{urllib.parse.quote(llave['tenantSlug'], safe='')}{ruta}"
|
|
48
|
+
datos = None if cuerpo is None else json.dumps(cuerpo).encode("utf-8")
|
|
49
|
+
peticion = urllib.request.Request(url, data=datos, method=metodo)
|
|
50
|
+
peticion.add_header("Authorization", f"Bearer {llave['token']}")
|
|
51
|
+
peticion.add_header("Accept", "application/json")
|
|
52
|
+
if datos is not None:
|
|
53
|
+
peticion.add_header("Content-Type", "application/json")
|
|
54
|
+
try:
|
|
55
|
+
with urllib.request.urlopen(peticion, timeout=60) as respuesta:
|
|
56
|
+
texto = respuesta.read().decode("utf-8")
|
|
57
|
+
except urllib.error.HTTPError as error:
|
|
58
|
+
texto = error.read().decode("utf-8", "replace")
|
|
59
|
+
try:
|
|
60
|
+
detalle = json.loads(texto).get("message", texto[:300])
|
|
61
|
+
except (ValueError, AttributeError):
|
|
62
|
+
detalle = texto[:300]
|
|
63
|
+
terminar(f"La API respondió {error.code} a {metodo} {ruta}: {detalle}", 1)
|
|
64
|
+
resultado = json.loads(texto) if texto else None
|
|
65
|
+
if not completa and isinstance(resultado, dict) and isinstance(resultado.get("success"), bool) and "data" in resultado:
|
|
66
|
+
return resultado["data"]
|
|
67
|
+
return resultado
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def llave_de_prueba() -> dict:
|
|
71
|
+
"""La llave de prueba del proyecto. Con sólo la llave real, la comprueba con `whoami`, explica y sale con el
|
|
72
|
+
código 8 sin emitir nada. Sin llave, sale con el código 1 sin llamar a la API."""
|
|
73
|
+
cargar_env()
|
|
74
|
+
prueba = leer_llave("prueba")
|
|
75
|
+
if prueba:
|
|
76
|
+
return prueba
|
|
77
|
+
real = leer_llave("real")
|
|
78
|
+
if not real:
|
|
79
|
+
terminar(f"El proyecto no tiene llave. Conéctalo con «{COMANDO_INIT}» y vuelve a correr la receta.", 1)
|
|
80
|
+
yo = pedir("GET", real, "/whoami")
|
|
81
|
+
terminar(
|
|
82
|
+
f"La llave del proyecto es la llave real de {yo['tenant']['nombre']} ({yo['tenant']['slug']}). Esta receta funciona "
|
|
83
|
+
f"sólo en el modo de prueba, así que no emití nada. Agrega la llave de prueba con «{COMANDO_INIT}».",
|
|
84
|
+
8,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def escenarios(llave: dict) -> dict:
|
|
89
|
+
return pedir("GET", llave, "/modo-prueba/escenarios")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def contraparte_de_boleta(e: dict) -> str:
|
|
93
|
+
"""Un RUT del registro de prueba que sirve de contraparte en una boleta: persona que no es emisor de prueba."""
|
|
94
|
+
emisores = {t["rut"] for t in e["emisoresTributarios"]}
|
|
95
|
+
for r in e["ruts"]:
|
|
96
|
+
if r["rol"] == "proveedor" and r["rut"] not in emisores:
|
|
97
|
+
return r["rut"]
|
|
98
|
+
terminar("El modo de prueba de la empresa no trae un RUT de prueba para la contraparte de la boleta.", 1)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def emisor_tributario(e: dict, servicio: str) -> str:
|
|
102
|
+
for t in e["emisoresTributarios"]:
|
|
103
|
+
if t["servicio"] == servicio:
|
|
104
|
+
return t["id"]
|
|
105
|
+
terminar(f"El modo de prueba de la empresa no trae el emisor de prueba de {servicio}.", 1)
|