{
  "info": {
    "name": "ecf-hub — Integración del cliente (TesteCF)",
    "description": "Las maneras de integrar un sistema con ecf-hub, cada una con sus pruebas: JSON sin e-NCF (numera ecf-hub), JSON con e-NCF propio, e-NCF repetido (409), e-NCF fuera del tramo (422), XML firmado, e-NCF sin secuencia registrada, ?wait=sent y la consulta del estado hasta Aceptado, y tipoeCF como \"E31\".\n\nUse el entorno «ecf-hub TesteCF» (postman/ecf-hub-testecf.postman_environment.json): apiKey (secreta, nunca en la colección), baseUrl y companyId. Envía comprobantes reales a TesteCF de la DGII (pre-certificación).",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "auth": {
    "type": "apikey",
    "apikey": [
      {
        "key": "key",
        "value": "X-Api-Key",
        "type": "string"
      },
      {
        "key": "value",
        "value": "{{apiKey}}",
        "type": "string"
      },
      {
        "key": "in",
        "value": "header",
        "type": "string"
      }
    ]
  },
  "event": [
    {
      "listen": "prerequest",
      "script": {
        "type": "text/javascript",
        "exec": [
          "for (const name of [\"apiKey\", \"baseUrl\", \"companyId\"]) {",
          "    if (!pm.variables.get(name)) {",
          "        throw new Error(`Falta la variable ${name} en el entorno «ecf-hub TesteCF» (la API key, como valor secreto).`);",
          "    }",
          "}",
          "// Fecha de emisión de hoy en Santo Domingo (UTC−4, sin horario de verano).",
          "pm.collectionVariables.set(\"fechaEmision\", new Date(Date.now() - 4 * 3600 * 1000).toISOString().slice(0, 10));"
        ]
      }
    }
  ],
  "variable": [
    {
      "key": "rncEmisor",
      "value": ""
    },
    {
      "key": "razonSocialEmisor",
      "value": ""
    },
    {
      "key": "direccionEmisor",
      "value": ""
    },
    {
      "key": "fechaEmision",
      "value": ""
    },
    {
      "key": "encfCliente",
      "value": ""
    },
    {
      "key": "encfParaXml",
      "value": ""
    },
    {
      "key": "encfTramoEcfHub",
      "value": ""
    },
    {
      "key": "venceSecuencia",
      "value": ""
    },
    {
      "key": "encfXml",
      "value": ""
    },
    {
      "key": "invoiceIdServicio",
      "value": ""
    },
    {
      "key": "invoiceIdCliente",
      "value": ""
    },
    {
      "key": "invoiceIdXml",
      "value": ""
    },
    {
      "key": "invoiceIdSinRegistrar",
      "value": ""
    },
    {
      "key": "pollAttempts",
      "value": "0"
    },
    {
      "key": "trackIdServicio",
      "value": ""
    },
    {
      "key": "encfServicio",
      "value": ""
    }
  ],
  "item": [
    {
      "name": "0. Preparación",
      "description": "Lee la empresa y la secuencia 31. Envíe 0.2 sola antes de firmar el XML: en la consola dice qué e-NCF usar en el XML (encfParaXml).",
      "item": [
        {
          "name": "0.1 Empresa de la API key",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/companies/{{companyId}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "companies",
                "{{companyId}}"
              ]
            },
            "description": "La empresa del companyId del entorno: sus datos van al emisor de las facturas."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "const c = pm.response.json();",
                  "pm.test(\"Empresa activa\", () => pm.expect(c.isActive).to.be.true);",
                  "pm.test(\"Ambiente TesteCF (pre-certificación)\", () => pm.expect(c.environment).to.eql(\"TestEcf\"));",
                  "pm.collectionVariables.set(\"rncEmisor\", c.rnc);",
                  "pm.collectionVariables.set(\"razonSocialEmisor\", c.legalName);",
                  "pm.collectionVariables.set(\"direccionEmisor\", c.address || \"Santo Domingo\");"
                ]
              }
            }
          ]
        },
        {
          "name": "0.2 Secuencia 31 y tramo del cliente",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/companies/{{companyId}}/sequences",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "companies",
                "{{companyId}}",
                "sequences"
              ]
            },
            "description": "Calcula el próximo e-NCF libre del tramo del cliente (encfCliente), un e-NCF del tramo de ecf-hub (encfTramoEcfHub) y el que debe llevar el XML firmado (encfParaXml)."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "const seq = pm.response.json().filter(s => s.ecfType === \"E31\" && !s.isExpired).sort((a, b) => a.rangeFrom - b.rangeFrom)[0];",
                  "pm.test(\"Hay una secuencia 31 vigente\", () => pm.expect(seq).to.exist);",
                  "if (!seq) { return; }",
                  "pm.test(\"Dividida en tramos (ficha de la empresa → Secuencias → «Tramos»)\", () => pm.expect(seq.allocation).to.eql(\"Split\"));",
                  "const encf = (n) => `E31${String(n).padStart(10, \"0\")}`;",
                  "const last = seq.clientLastUsed;",
                  "const part = (seq.clientRanges || []).find(p => p.free > 0);",
                  "pm.test(\"El tramo del cliente tiene números libres\", () => pm.expect(part).to.exist);",
                  "if (!part) { return; }",
                  "const next = last && last >= part.from && last < part.to ? last + 1 : part.from;",
                  "pm.collectionVariables.set(\"encfCliente\", encf(next));",
                  "pm.collectionVariables.set(\"encfParaXml\", encf(next + 1));",
                  "pm.collectionVariables.set(\"encfTramoEcfHub\", encf(seq.autoFrom));",
                  "pm.collectionVariables.set(\"venceSecuencia\", seq.expiresOn);",
                  "console.log(`Tramo de ecf-hub ${seq.autoFrom}–${seq.autoTo}; JSON con e-NCF propio: ${encf(next)}; vence ${seq.expiresOn}`);",
                  "console.log(`Para el XML firmado: dotnet run postman/firmar-ecf31.cs -- --p12 \"<ruta del .p12>\" --rnc ${pm.collectionVariables.get(\"rncEmisor\")} --razon-social \"${pm.collectionVariables.get(\"razonSocialEmisor\")}\" --encf ${encf(next + 1)} --vence ${seq.expiresOn}`);",
                  "[\"invoiceIdServicio\", \"invoiceIdCliente\", \"invoiceIdXml\", \"invoiceIdSinRegistrar\"].forEach(v => pm.collectionVariables.unset(v));"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "1. JSON sin e-NCF (numera ecf-hub)",
      "description": "Sin encf en el documento: ecf-hub asigna el próximo de su tramo. ?wait=sent espera hasta 6 s el envío a la DGII (con el TrackID por defecto de la cuenta, también sin el parámetro). Con sentWait = Contingency, la DGII no respondió: se imprime con contingency.legend y el envío sigue solo.",
      "item": [
        {
          "name": "1.1 Enviar sin e-NCF",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"tipoeCF\": \"E31\",\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "ecf-hub asigna el e-NCF; vuelve con los datos para imprimir."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"202 Accepted\", () => pm.response.to.have.status(202));",
                  "const body = pm.response.json();",
                  "pm.test(\"e-NCF asignado por ecf-hub, tipo E31\", () => {",
                  "    pm.expect(body.encf).to.match(/^E31\\d{10}$/);",
                  "    pm.expect(body.ecfType).to.eql(\"E31\");",
                  "    pm.expect(body.numberedBy).to.eql(\"Service\");",
                  "});",
                  "pm.test(\"Datos para imprimir: código de seguridad, fecha de firma y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"?wait=sent: la DGII ya lo recibió (sentWait = Sent y trackId)\", () => {",
                  "    pm.expect(body.sentWait, \"TimedOut: siga con la consulta del estado; Contingency: imprima con contingency.legend\").to.eql(\"Sent\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "});",
                  "console.log(`${pm.info.requestName}: ${body.encf} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "pm.collectionVariables.set(\"invoiceIdServicio\", body.id);",
                  "pm.collectionVariables.set(\"trackIdServicio\", body.trackId || \"\");",
                  "pm.collectionVariables.set(\"encfServicio\", body.encf || \"\");"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "2. JSON con e-NCF propio en el tramo del cliente",
      "description": "El e-NCF lo elige su sistema (encfCliente, de 0.2). ecf-hub nunca lo cambia.",
      "item": [
        {
          "name": "2.1 Enviar con e-NCF propio",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"encf\": \"{{encfCliente}}\",\n        \"tipoeCF\": \"E31\",\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "El e-NCF del documento es el de su sistema: se usa tal cual."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"202 Accepted\", () => pm.response.to.have.status(202));",
                  "const body = pm.response.json();",
                  "pm.test(\"Se emitió con el e-NCF de su sistema, sin cambiarlo\", () => {",
                  "    pm.expect(body.encf).to.eql(pm.collectionVariables.get(\"encfCliente\"));",
                  "    pm.expect(body.numberedBy).to.eql(\"Client\");",
                  "});",
                  "pm.test(\"Datos para imprimir: código de seguridad, fecha de firma y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"?wait=sent: la DGII ya lo recibió (sentWait = Sent y trackId)\", () => {",
                  "    pm.expect(body.sentWait, \"TimedOut: siga con la consulta del estado; Contingency: imprima con contingency.legend\").to.eql(\"Sent\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "});",
                  "console.log(`${pm.info.requestName}: ${body.encf} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "pm.collectionVariables.set(\"invoiceIdCliente\", body.id);"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "3. e-NCF repetido → 409",
      "description": "El mismo e-NCF otra vez (con otra Idempotency-Key): se rechaza y no se emite nada. ecf-hub nunca asigna otro número.",
      "item": [
        {
          "name": "3.1 Repetir el e-NCF propio",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"encf\": \"{{encfCliente}}\",\n        \"tipoeCF\": \"E31\",\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "Debe responder 409 invoice.encf_taken con el mensaje claro."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"409\", () => pm.response.to.have.status(409));",
                  "const problem = pm.response.json();",
                  "pm.test(\"code = invoice.encf_taken\", () => pm.expect(problem.code).to.eql(\"invoice.encf_taken\"));",
                  "console.log(`${pm.info.requestName}: ${pm.response.code} ${JSON.stringify(problem)}`);",
                  "pm.test(\"El mensaje dice qué e-NCF y que no se emitió\", () => {",
                  "    pm.expect(problem.title).to.include(`El e-NCF ${pm.collectionVariables.get(\"encfCliente\")} ya fue utilizado; no se emitió el comprobante`);",
                  "    pm.expect(problem.errors[0].field).to.eql(\"Encabezado.IdDoc.eNCF\");",
                  "});"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "4. e-NCF propio fuera del tramo del cliente → 422",
      "description": "Con la secuencia registrada y dividida, el e-NCF de su sistema debe estar en su tramo (el de ecf-hub es para los que asigna ecf-hub).",
      "item": [
        {
          "name": "4.1 e-NCF del tramo de ecf-hub",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"encf\": \"{{encfTramoEcfHub}}\",\n        \"tipoeCF\": \"E31\",\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "Usa el primer número del tramo de ecf-hub: 422 encf.outside_client_range."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"422\", () => pm.response.to.have.status(422));",
                  "const problem = pm.response.json();",
                  "pm.test(\"code = encf.outside_client_range\", () => pm.expect(problem.code).to.eql(\"encf.outside_client_range\"));",
                  "console.log(`${pm.info.requestName}: ${pm.response.code} ${JSON.stringify(problem)}`);",
                  "pm.test(\"Dice cuál es el tramo de su sistema\", () => pm.expect(problem.errors[0].message).to.include(\"tramo de su sistema\"));"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "5. XML firmado por su sistema",
      "description": "Postman no firma: firme antes el XML con postman/firmar-ecf31.cs usando encfParaXml (consola de 0.2) y elíjalo en el campo xml de 5.1 y 5.2 («Select files»); guarde cada petición.",
      "item": [
        {
          "name": "5.1 Subir el XML firmado",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              }
            ],
            "body": {
              "mode": "formdata",
              "formdata": [
                {
                  "key": "xml",
                  "type": "file",
                  "contentType": "application/xml",
                  "description": "El XML firmado por su sistema (aquí, con postman/firmar-ecf31.cs). Elíjalo con «Select files» y guarde la petición. Se envía byte a byte: no lo reformatee."
                }
              ]
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/signed?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "signed"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "Se envía a la DGII byte a byte. ?wait=sent espera el envío, como el JSON."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "// Postman no puede comprobar desde un script que el archivo exista: se revisa que haya uno elegido y, si no, no se envía.",
                  "const xmlField = pm.request.body && pm.request.body.formdata ? pm.request.body.formdata.find(p => p.key === \"xml\" && !p.disabled) : null;",
                  "const xmlSrc = xmlField ? [].concat(xmlField.src || []).filter(Boolean) : [];",
                  "if (xmlSrc.length === 0) {",
                  "    const message = `${pm.info.requestName}: no hay XML adjunto. En Body → xml, pulse «Select files», elija el XML firmado y guarde la petición (Ctrl+S) antes de usar el Runner. No se envió nada.`;",
                  "    console.error(message);",
                  "    pm.test(\"XML firmado adjunto en el campo xml\", () => { throw new Error(message); });",
                  "    pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "// Si Postman no encontró el archivo, manda la petición sin él (file load error) y la API responde 400 sin emitir nada.",
                  "if (pm.response.code === 400 && /xml/i.test(pm.response.text())) {",
                  "    const message = `${pm.info.requestName}: Postman no pudo leer el archivo del campo xml (vea «file load error» en la consola) y la petición salió sin el XML; la API no emitió nada. Vuelva a elegir el archivo con «Select files» y guarde la petición.`;",
                  "    console.error(message);",
                  "    pm.test(\"XML firmado adjunto en el campo xml\", () => { throw new Error(message); });",
                  "    return;",
                  "}",
                  "pm.test(\"202 Accepted\", () => pm.response.to.have.status(202));",
                  "const body = pm.response.json();",
                  "pm.test(\"Firmado por su sistema (PreSigned), tipo E31\", () => {",
                  "    pm.expect(body.mode).to.eql(\"PreSigned\");",
                  "    pm.expect(body.ecfType).to.eql(\"E31\");",
                  "});",
                  "pm.test(\"Datos para imprimir: código de seguridad, fecha de firma y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"?wait=sent: la DGII ya lo recibió (sentWait = Sent y trackId)\", () => {",
                  "    pm.expect(body.sentWait, \"TimedOut: siga con la consulta del estado; Contingency: imprima con contingency.legend\").to.eql(\"Sent\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "});",
                  "console.log(`${pm.info.requestName}: ${body.encf} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "pm.collectionVariables.set(\"invoiceIdXml\", body.id);",
                  "pm.collectionVariables.set(\"encfXml\", body.encf);"
                ]
              }
            }
          ]
        },
        {
          "name": "5.2 Subir el mismo XML otra vez → 409",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              }
            ],
            "body": {
              "mode": "formdata",
              "formdata": [
                {
                  "key": "xml",
                  "type": "file",
                  "contentType": "application/xml",
                  "description": "El XML firmado por su sistema (aquí, con postman/firmar-ecf31.cs). Elíjalo con «Select files» y guarde la petición. Se envía byte a byte: no lo reformatee."
                }
              ]
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/signed?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "signed"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "Mismo e-NCF: 409 invoice.encf_taken; no se emite nada. Elija el mismo archivo que en 5.1."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "// Sin la 5.1 aceptada, este envío no sería un repetido: emitiría un comprobante real.",
                  "if (!pm.collectionVariables.get(\"invoiceIdXml\")) { console.error(\"5.2: la 5.1 no subió el XML en esta corrida; se omite.\"); pm.execution.skipRequest(); }",
                  "// Postman no puede comprobar desde un script que el archivo exista: se revisa que haya uno elegido y, si no, no se envía.",
                  "const xmlField = pm.request.body && pm.request.body.formdata ? pm.request.body.formdata.find(p => p.key === \"xml\" && !p.disabled) : null;",
                  "const xmlSrc = xmlField ? [].concat(xmlField.src || []).filter(Boolean) : [];",
                  "if (xmlSrc.length === 0) {",
                  "    const message = `${pm.info.requestName}: no hay XML adjunto. En Body → xml, pulse «Select files», elija el XML firmado y guarde la petición (Ctrl+S) antes de usar el Runner. No se envió nada.`;",
                  "    console.error(message);",
                  "    pm.test(\"XML firmado adjunto en el campo xml\", () => { throw new Error(message); });",
                  "    pm.execution.skipRequest();",
                  "}"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "// Si Postman no encontró el archivo, manda la petición sin él (file load error) y la API responde 400 sin emitir nada.",
                  "if (pm.response.code === 400 && /xml/i.test(pm.response.text())) {",
                  "    const message = `${pm.info.requestName}: Postman no pudo leer el archivo del campo xml (vea «file load error» en la consola) y la petición salió sin el XML; la API no emitió nada. Vuelva a elegir el archivo con «Select files» y guarde la petición.`;",
                  "    console.error(message);",
                  "    pm.test(\"XML firmado adjunto en el campo xml\", () => { throw new Error(message); });",
                  "    return;",
                  "}",
                  "pm.test(\"409\", () => pm.response.to.have.status(409));",
                  "const problem = pm.response.json();",
                  "pm.test(\"code = invoice.encf_taken\", () => pm.expect(problem.code).to.eql(\"invoice.encf_taken\"));",
                  "console.log(`${pm.info.requestName}: ${pm.response.code} ${JSON.stringify(problem)}`);",
                  "pm.test(\"El mensaje dice qué e-NCF\", () => pm.expect(problem.title).to.include(`El e-NCF ${pm.collectionVariables.get(\"encfXml\")} ya fue utilizado`));"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "6. e-NCF propio sin secuencia registrada",
      "description": "Opcional: ponga en el entorno encfSinRegistrar (un e-NCF 31 que la DGII le autorizó y que NO está en una secuencia registrada en ecf-hub) y venceSinRegistrar (AAAA-MM-DD). Sin ellas, se omite. Si el número no está autorizado, la DGII lo rechaza (135).",
      "item": [
        {
          "name": "6.1 Sin FechaVencimientoSecuencia → 422",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"encf\": \"{{encfSinRegistrar}}\",\n        \"tipoeCF\": \"E31\",\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "Sin secuencia registrada, el documento debe traer la fecha de vencimiento."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.environment.get(\"encfSinRegistrar\")) { console.log(\"6.1: falta encfSinRegistrar en el entorno; se omite.\"); pm.execution.skipRequest(); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"422\", () => pm.response.to.have.status(422));",
                  "const problem = pm.response.json();",
                  "pm.test(\"code = sequence.expiry_required\", () => pm.expect(problem.code).to.eql(\"sequence.expiry_required\"));",
                  "console.log(`${pm.info.requestName}: ${pm.response.code} ${JSON.stringify(problem)}`);"
                ]
              }
            }
          ]
        },
        {
          "name": "6.2 Con FechaVencimientoSecuencia → 202",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"encf\": \"{{encfSinRegistrar}}\",\n        \"tipoeCF\": \"E31\",\n        \"fechaVencimientoSecuencia\": \"{{venceSinRegistrar}}\",\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices?wait=sent",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ],
              "query": [
                {
                  "key": "wait",
                  "value": "sent"
                }
              ]
            },
            "description": "Se valida solo que no esté usado; la autorización la verifica la DGII."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.environment.get(\"encfSinRegistrar\") || !pm.environment.get(\"venceSinRegistrar\")) { console.log(\"6.2: faltan encfSinRegistrar y venceSinRegistrar en el entorno; se omite.\"); pm.execution.skipRequest(); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"202 Accepted\", () => pm.response.to.have.status(202));",
                  "const body = pm.response.json();",
                  "pm.test(\"Se emitió con ese e-NCF\", () => pm.expect(body.encf).to.eql(pm.environment.get(\"encfSinRegistrar\")));",
                  "pm.test(\"Datos para imprimir: código de seguridad, fecha de firma y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"?wait=sent: la DGII ya lo recibió (sentWait = Sent y trackId)\", () => {",
                  "    pm.expect(body.sentWait, \"TimedOut: siga con la consulta del estado; Contingency: imprima con contingency.legend\").to.eql(\"Sent\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "});",
                  "console.log(`${pm.info.requestName}: ${body.encf} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "pm.collectionVariables.set(\"invoiceIdSinRegistrar\", body.id);"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "7. Estado hasta Aceptado (GET)",
      "description": "Consulta cada comprobante emitido hasta el resultado de la DGII y muestra el código de seguridad, la fecha de firma y la URL del QR.",
      "item": [
        {
          "name": "7.1 Estado: JSON sin e-NCF",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/{{invoiceIdServicio}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "{{invoiceIdServicio}}"
              ]
            },
            "description": "Consulta el estado. En el Runner se repite cada 3 s (hasta ~3 min) hasta Aceptado o un estado final; a mano, repítala."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.collectionVariables.get(\"invoiceIdServicio\")) { console.log(\"1. JSON sin e-NCF: no se emitió en esta corrida; se omite.\"); pm.execution.skipRequest(); }",
                  "if (Number(pm.collectionVariables.get(\"pollAttempts\") || 0) > 0) { setTimeout(() => {}, 3000); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json();",
                  "const attempts = Number(pm.collectionVariables.get(\"pollAttempts\") || 0);",
                  "if (![\"Accepted\", \"AcceptedConditional\", \"Rejected\", \"Failed\"].includes(body.status) && attempts < 60) {",
                  "    pm.collectionVariables.set(\"pollAttempts\", attempts + 1);",
                  "    console.log(`1. JSON sin e-NCF: ${body.status} (consulta ${attempts + 1})`);",
                  "    pm.execution.setNextRequest(pm.info.requestName);",
                  "    return;",
                  "}",
                  "pm.collectionVariables.set(\"pollAttempts\", 0);",
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "pm.test(\"Estado final: Accepted\", () => pm.expect(body.status, JSON.stringify(body.dgii)).to.eql(\"Accepted\"));",
                  "pm.test(\"Código de seguridad, fecha de firma, trackId y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"tipo como E31\", () => pm.expect(body.ecfType).to.eql(\"E31\"));",
                  "console.log(`1. JSON sin e-NCF: ${body.encf} ${body.status} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "// La DGII puede responder un mensaje sin texto (p. ej. código 0 al aceptar): no se imprime.",
                  "(body.dgii?.messages || []).filter(m => m.value?.trim() || m.hint).forEach(m => console.log(`  DGII ${m.code}: ${m.value}${m.hint ? \" · Qué significa: \" + m.hint : \"\"}`));"
                ]
              }
            }
          ]
        },
        {
          "name": "7.2 Estado: JSON con e-NCF propio",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/{{invoiceIdCliente}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "{{invoiceIdCliente}}"
              ]
            },
            "description": "Consulta el estado. En el Runner se repite cada 3 s (hasta ~3 min) hasta Aceptado o un estado final; a mano, repítala."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.collectionVariables.get(\"invoiceIdCliente\")) { console.log(\"2. JSON con e-NCF propio: no se emitió en esta corrida; se omite.\"); pm.execution.skipRequest(); }",
                  "if (Number(pm.collectionVariables.get(\"pollAttempts\") || 0) > 0) { setTimeout(() => {}, 3000); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json();",
                  "const attempts = Number(pm.collectionVariables.get(\"pollAttempts\") || 0);",
                  "if (![\"Accepted\", \"AcceptedConditional\", \"Rejected\", \"Failed\"].includes(body.status) && attempts < 60) {",
                  "    pm.collectionVariables.set(\"pollAttempts\", attempts + 1);",
                  "    console.log(`2. JSON con e-NCF propio: ${body.status} (consulta ${attempts + 1})`);",
                  "    pm.execution.setNextRequest(pm.info.requestName);",
                  "    return;",
                  "}",
                  "pm.collectionVariables.set(\"pollAttempts\", 0);",
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "pm.test(\"Estado final: Accepted\", () => pm.expect(body.status, JSON.stringify(body.dgii)).to.eql(\"Accepted\"));",
                  "pm.test(\"Código de seguridad, fecha de firma, trackId y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"tipo como E31\", () => pm.expect(body.ecfType).to.eql(\"E31\"));",
                  "console.log(`2. JSON con e-NCF propio: ${body.encf} ${body.status} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "// La DGII puede responder un mensaje sin texto (p. ej. código 0 al aceptar): no se imprime.",
                  "(body.dgii?.messages || []).filter(m => m.value?.trim() || m.hint).forEach(m => console.log(`  DGII ${m.code}: ${m.value}${m.hint ? \" · Qué significa: \" + m.hint : \"\"}`));"
                ]
              }
            }
          ]
        },
        {
          "name": "7.3 Estado: XML firmado",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/{{invoiceIdXml}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "{{invoiceIdXml}}"
              ]
            },
            "description": "Consulta el estado. En el Runner se repite cada 3 s (hasta ~3 min) hasta Aceptado o un estado final; a mano, repítala."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.collectionVariables.get(\"invoiceIdXml\")) { console.log(\"5. XML firmado: no se emitió en esta corrida; se omite.\"); pm.execution.skipRequest(); }",
                  "if (Number(pm.collectionVariables.get(\"pollAttempts\") || 0) > 0) { setTimeout(() => {}, 3000); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json();",
                  "const attempts = Number(pm.collectionVariables.get(\"pollAttempts\") || 0);",
                  "if (![\"Accepted\", \"AcceptedConditional\", \"Rejected\", \"Failed\"].includes(body.status) && attempts < 60) {",
                  "    pm.collectionVariables.set(\"pollAttempts\", attempts + 1);",
                  "    console.log(`5. XML firmado: ${body.status} (consulta ${attempts + 1})`);",
                  "    pm.execution.setNextRequest(pm.info.requestName);",
                  "    return;",
                  "}",
                  "pm.collectionVariables.set(\"pollAttempts\", 0);",
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "pm.test(\"Estado final: Accepted\", () => pm.expect(body.status, JSON.stringify(body.dgii)).to.eql(\"Accepted\"));",
                  "pm.test(\"Código de seguridad, fecha de firma, trackId y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"tipo como E31\", () => pm.expect(body.ecfType).to.eql(\"E31\"));",
                  "console.log(`5. XML firmado: ${body.encf} ${body.status} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "// La DGII puede responder un mensaje sin texto (p. ej. código 0 al aceptar): no se imprime.",
                  "(body.dgii?.messages || []).filter(m => m.value?.trim() || m.hint).forEach(m => console.log(`  DGII ${m.code}: ${m.value}${m.hint ? \" · Qué significa: \" + m.hint : \"\"}`));"
                ]
              }
            }
          ]
        },
        {
          "name": "7.4 Estado: sin secuencia registrada",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/{{invoiceIdSinRegistrar}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "{{invoiceIdSinRegistrar}}"
              ]
            },
            "description": "Consulta el estado. En el Runner se repite cada 3 s (hasta ~3 min) hasta Aceptado o un estado final; a mano, repítala."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.collectionVariables.get(\"invoiceIdSinRegistrar\")) { console.log(\"6. Sin secuencia registrada: no se emitió en esta corrida; se omite.\"); pm.execution.skipRequest(); }",
                  "if (Number(pm.collectionVariables.get(\"pollAttempts\") || 0) > 0) { setTimeout(() => {}, 3000); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json();",
                  "const attempts = Number(pm.collectionVariables.get(\"pollAttempts\") || 0);",
                  "if (![\"Accepted\", \"AcceptedConditional\", \"Rejected\", \"Failed\"].includes(body.status) && attempts < 60) {",
                  "    pm.collectionVariables.set(\"pollAttempts\", attempts + 1);",
                  "    console.log(`6. Sin secuencia registrada: ${body.status} (consulta ${attempts + 1})`);",
                  "    pm.execution.setNextRequest(pm.info.requestName);",
                  "    return;",
                  "}",
                  "pm.collectionVariables.set(\"pollAttempts\", 0);",
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "pm.test(\"Estado final: Accepted\", () => pm.expect(body.status, JSON.stringify(body.dgii)).to.eql(\"Accepted\"));",
                  "pm.test(\"Código de seguridad, fecha de firma, trackId y URL del QR\", () => {",
                  "    pm.expect(body.securityCode).to.have.lengthOf(6);",
                  "    pm.expect(body.signedAt).to.be.a(\"string\");",
                  "    pm.expect(body.trackId).to.be.a(\"string\").and.not.empty;",
                  "    pm.expect(body.timbreUrl).to.include(`ENCF=${body.encf}`);",
                  "});",
                  "pm.test(\"tipo como E31\", () => pm.expect(body.ecfType).to.eql(\"E31\"));",
                  "console.log(`6. Sin secuencia registrada: ${body.encf} ${body.status} · código ${body.securityCode} · firmado ${body.signedAt} · QR ${body.timbreUrl}`);",
                  "// La DGII puede responder un mensaje sin texto (p. ej. código 0 al aceptar): no se imprime.",
                  "(body.dgii?.messages || []).filter(m => m.value?.trim() || m.hint).forEach(m => console.log(`  DGII ${m.code}: ${m.value}${m.hint ? \" · Qué significa: \" + m.hint : \"\"}`));"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "8. tipoeCF como código",
      "description": "El tipo va como \"E31\" (todos los ejemplos). También se acepta el número solo y la respuesta siempre dice \"E31\". Un código que no existe da 400.",
      "item": [
        {
          "name": "8.1 tipoeCF 31 (número) → responde E31",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"tipoeCF\": 31,\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ]
            },
            "description": "Emite una factura más (numera ecf-hub)."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"202 Accepted\", () => pm.response.to.have.status(202));",
                  "const body = pm.response.json();",
                  "pm.test(\"La respuesta dice ecfType E31\", () => pm.expect(body.ecfType).to.eql(\"E31\"));"
                ]
              }
            }
          ]
        },
        {
          "name": "8.2 tipoeCF E99 → 400",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Idempotency-Key",
                "value": "{{$guid}}",
                "description": "Obligatoria. Una nueva por factura; al reintentar la MISMA factura, reutilícela."
              },
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"companyId\": \"{{companyId}}\",\n  \"document\": {\n    \"encabezado\": {\n      \"idDoc\": {\n        \"tipoeCF\": \"E99\",\n        \"tipoIngresos\": \"IngresosOperaciones\",\n        \"tipoPago\": \"Contado\",\n        \"indicadorMontoGravado\": false\n      },\n      \"emisor\": {\n        \"rncEmisor\": \"{{rncEmisor}}\",\n        \"razonSocialEmisor\": \"{{razonSocialEmisor}}\",\n        \"direccionEmisor\": \"{{direccionEmisor}}\",\n        \"fechaEmision\": \"{{fechaEmision}}\"\n      },\n      \"comprador\": { \"rncComprador\": \"{{compradorRnc}}\", \"razonSocialComprador\": \"{{compradorNombre}}\" },\n      \"totales\": { \"montoGravadoTotal\": 1000, \"montoGravadoI1\": 1000, \"itbis1\": 18, \"totalItbis\": 180, \"totalItbis1\": 180, \"montoTotal\": 1180 }\n    },\n    \"items\": [\n      { \"numeroLinea\": 1, \"indicadorFacturacion\": \"Itbis1\", \"nombreItem\": \"Servicio\", \"indicadorBienoServicio\": \"Servicio\",\n        \"cantidadItem\": 1, \"precioUnitarioItem\": 1000, \"montoItem\": 1000 }\n    ]\n  }\n}",
              "options": {
                "raw": {
                  "language": "json"
                }
              }
            },
            "url": {
              "raw": "{{baseUrl}}/v1/invoices",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices"
              ]
            },
            "description": "Un tipo que no existe no se acepta."
          },
          "event": [
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "pm.test(\"400 Bad Request\", () => pm.response.to.have.status(400));",
                  "console.log(`8.2: ${pm.response.code} ${pm.response.text()}`);"
                ]
              }
            }
          ]
        }
      ]
    },
    {
      "name": "9. Consultas por trackId y por e-NCF",
      "description": "El mismo detalle que GET /v1/invoices/{id}, buscado por lo que guarda el sistema del cliente: el TrackID de la DGII o el e-NCF. Usa el comprobante del paso 1.",
      "item": [
        {
          "name": "9.1 Por trackId",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/by-track-id/{{trackIdServicio}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "by-track-id",
                "{{trackIdServicio}}"
              ]
            },
            "description": "El comprobante por el TrackID que devolvió la DGII. Cada versión de un comprobante tiene el suyo."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.collectionVariables.get(\"trackIdServicio\")) { console.log(\"1. JSON sin e-NCF: no se emitió (o no trae trackId) en esta corrida; se omite.\"); pm.execution.skipRequest(); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json();",
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "pm.test(\"Es el comprobante del paso 1\", () => pm.expect(body.id).to.eql(pm.collectionVariables.get(\"invoiceIdServicio\")));",
                  "pm.test(\"Mismo trackId\", () => pm.expect(body.trackId).to.eql(pm.collectionVariables.get(\"trackIdServicio\")));"
                ]
              }
            }
          ]
        },
        {
          "name": "9.2 Por e-NCF",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "{{baseUrl}}/v1/invoices/by-encf/{{encfServicio}}?companyId={{companyId}}",
              "host": [
                "{{baseUrl}}"
              ],
              "path": [
                "v1",
                "invoices",
                "by-encf",
                "{{encfServicio}}"
              ],
              "query": [
                {
                  "key": "companyId",
                  "value": "{{companyId}}"
                }
              ]
            },
            "description": "El comprobante vigente de ese e-NCF en la empresa. companyId es opcional con una API key restringida a una empresa; environment, por defecto el ambiente actual de la empresa."
          },
          "event": [
            {
              "listen": "prerequest",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "if (!pm.collectionVariables.get(\"trackIdServicio\")) { console.log(\"1. JSON sin e-NCF: no se emitió (o no trae trackId) en esta corrida; se omite.\"); pm.execution.skipRequest(); }"
                ]
              }
            },
            {
              "listen": "test",
              "script": {
                "type": "text/javascript",
                "exec": [
                  "const body = pm.response.json();",
                  "pm.test(\"200 OK\", () => pm.response.to.have.status(200));",
                  "pm.test(\"Es el comprobante del paso 1\", () => pm.expect(body.id).to.eql(pm.collectionVariables.get(\"invoiceIdServicio\")));",
                  "pm.test(\"Mismo e-NCF\", () => pm.expect(body.encf).to.eql(pm.collectionVariables.get(\"encfServicio\")));"
                ]
              }
            }
          ]
        }
      ]
    }
  ]
}
