{
  "info": {
    "name": "Factux API · Sandbox",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
    "description": "# Integración sandbox paso a paso\n\nImporte esta colección y configure **sus variables locales de colección**: `apiKey` = llave fx_test_ completa, `issuerId` = UUID del emisor (vacío solo con un único emisor), `baseUrl` = https://factuxapi.com. No use variables de entorno/globales con estos nombres. No comparta ni sincronice la llave.\n\nEjecute **Run collection**, todas las solicitudes en orden, una iteración. Los IDs se guardan solo durante la ejecución. Cada recorrido crea tres documentos nuevos: factura $107.100, crédito $23.800, débito $11.900. Los errores 401, 400 y 422 son esperados y tienen pruebas automáticas. Una prueba fallida detiene el Runner.\n\nSolo sandbox: bloquea fx_live_, no transmite a DIAN; XML sin firma ni valor fiscal. Para webhooks use el portal y receptor-webhooks.mjs del kit; no existe un endpoint público de registro en esta colección.\n\nGuía completa: https://factuxapi.com/sandbox/POSTMAN.md\nDocumentación: https://factuxapi.com/docs\nKit: https://factuxapi.com/factux-sandbox.zip"
  },
  "auth": {
    "type": "bearer",
    "bearer": [
      {
        "key": "token",
        "value": "{{apiKey}}",
        "type": "string"
      }
    ]
  },
  "variable": [
    {
      "key": "baseUrl",
      "value": "https://factuxapi.com",
      "type": "string"
    },
    {
      "key": "apiKey",
      "value": "",
      "type": "string"
    },
    {
      "key": "issuerId",
      "value": "",
      "type": "string"
    }
  ],
  "event": [
    {
      "listen": "prerequest",
      "script": {
        "type": "text/javascript",
        "exec": [
          "(function () {",
          "const key = String(pm.collectionVariables.get('apiKey') || '').trim();",
          "const base = String(pm.collectionVariables.get('baseUrl') || '').trim();",
          "function stop(message) {",
          "  pm.test('Configuración sandbox', function () { throw new Error(message); });",
          "  pm.execution.skipRequest();",
          "  pm.execution.setNextRequest(null);",
          "  throw new Error(message);",
          "}",
          "if (!/^fx_test_[0-9a-f]{48}$/.test(key)) stop('Configure apiKey con una llave sandbox fx_test_ completa. Producción está bloqueada.');",
          "let url;",
          "try { url = require('url').parse(base); } catch (_) { stop('baseUrl no es una URL válida.'); }",
          "const local = ['localhost', '127.0.0.1', '::1'].includes(url.hostname);",
          "if (!url.hostname || (url.protocol !== 'https:' && !(local && url.protocol === 'http:')) || url.auth || url.search || url.hash || (url.pathname && url.pathname !== '/')) stop('baseUrl debe ser un origen HTTPS sin rutas ni credenciales (HTTP solo en localhost).');",
          "pm.variables.set('baseUrl', url.protocol + '//' + url.host);",
          "pm.variables.set('apiKey', key);",
          "const issuer = String(pm.collectionVariables.get('issuerId') || '').trim();",
          "if (issuer && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(issuer)) stop('issuerId debe ser un UUID, no el NIT.');",
          "if (issuer) pm.variables.set('issuerId', issuer);",
          "})();"
        ]
      }
    }
  ],
  "item": [
    {
      "name": "01 · Conexión sin llave (401 esperado)",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/ping",
        "description": "Prueba de seguridad: no envía Authorization. HTTP 401 es el resultado correcto.",
        "auth": {
          "type": "noauth"
        }
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "for (const key of ['invoiceId', 'creditNoteId', 'debitNoteId', 'runId', 'sandboxReady', 'issuerId']) pm.variables.unset(key);",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 401', () => pm.expect(pm.response.code).to.eql(401));",
              "verify('Error esperado invalid_api_key', () => pm.expect(pm.response.json().error.code).to.eql('invalid_api_key'));",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "02 · Conexión sandbox",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/ping",
        "description": "Confirma que la llave pertenece al sandbox."
      },
      "event": [
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 200', () => pm.expect(pm.response.code).to.eql(200));",
              "verify('Sandbox conectado', () => { pm.expect(pm.response.json().ok).to.eql(true); pm.expect(pm.response.json().environment).to.eql('sandbox'); });",
              "pm.variables.set('sandboxReady', true);",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "03 · Listar y seleccionar emisor",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/issuers",
        "description": "Selecciona el único emisor o valida issuerId si hay varios."
      },
      "event": [
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 200', () => pm.expect(pm.response.code).to.eql(200));",
              "const data = pm.response.json().data;",
              "verify('Emisor disponible en esta cuenta', () => {",
              "  pm.expect(data).to.be.an('array');",
              "  const configured = String(pm.collectionVariables.get('issuerId') || '').trim();",
              "  const issuer = configured ? data.find(item => item.id === configured) : data.length === 1 ? data[0] : null;",
              "  pm.expect(Boolean(issuer), 'Configure issuerId si hay cero o varios emisores').to.eql(true);",
              "  pm.variables.set('issuerId', issuer.id);",
              "});",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "04 · Factura incompleta (400 esperado)",
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/api/public/v1/invoices",
        "description": "Valida el rechazo de un cuerpo incompleto; no crea documentos.",
        "body": {
          "mode": "raw",
          "raw": "{}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        }
      },
      "event": [
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 400', () => pm.expect(pm.response.code).to.eql(400));",
              "verify('Error esperado validation_error', () => pm.expect(pm.response.json().error.code).to.eql('validation_error'));",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "05 · Emitir factura $107.100",
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/api/public/v1/invoices",
        "description": "Dos licencias de $50.000, descuento $10.000 antes del IVA 19%. Guarda invoiceId temporalmente.",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"issuer_id\": \"{{issuerId}}\",\n  \"external_id\": \"postman-{{runId}}-factura\",\n  \"payment_form\": \"contado\",\n  \"payment_method\": \"transferencia\",\n  \"notes\": \"Prueba Postman sin valor fiscal. No enviada a la DIAN.\",\n  \"customer\": {\n    \"person_type\": \"natural\",\n    \"doc_type\": \"CC\",\n    \"doc_number\": \"1234567890\",\n    \"name\": \"Comprador de prueba\",\n    \"city\": \"Bogotá\",\n    \"department\": \"Bogotá\"\n  },\n  \"lines\": [\n    {\n      \"code\": \"DEMO-01\",\n      \"description\": \"Licencia de prueba\",\n      \"quantity\": 2,\n      \"unit_price\": 50000,\n      \"discount\": 10000,\n      \"tax_category\": \"gravado\",\n      \"tax_rate\": 19\n    }\n  ]\n}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        }
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (pm.variables.get('sandboxReady') !== true || !pm.variables.get('issuerId')) {",
              "  pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute primero los pasos 01 a 03.');",
              "}",
              "pm.variables.set('runId', pm.variables.replaceIn('{{$guid}}'));",
              "for (const key of ['invoiceId', 'creditNoteId', 'debitNoteId']) pm.variables.unset(key);",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 201', () => pm.expect(pm.response.code).to.eql(201));",
              "const doc = pm.response.json().data;",
              "verify('Documento sandbox aceptado y total 107100', () => {",
              "  pm.expect(doc.environment).to.eql('sandbox');",
              "  pm.expect(doc.status).to.eql('aceptada');",
              "  pm.expect(doc.type).to.eql('invoice');",
              "  pm.expect(doc.total).to.eql(107100);",
              "  pm.expect(doc.id).to.match(/^[0-9a-f-]{36}$/i);",
              "  pm.expect(doc.cufe).to.match(/^[0-9a-f]{96}$/i);",
              "});",
              "verify('IVA de factura $17.100', () => pm.expect(doc.tax_total).to.eql(17100));",
              "pm.variables.set('invoiceId', doc.id);",
              "pm.variables.set('invoiceIdCufe', doc.cufe);",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "06 · Nota crédito $23.800",
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/api/public/v1/credit-notes",
        "description": "Devolución parcial. Saldo de factura después del crédito: $83.300.",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"invoice_id\": \"{{invoiceId}}\",\n  \"external_id\": \"postman-{{runId}}-credito\",\n  \"reason_code\": \"1\",\n  \"description\": \"Devolución parcial de prueba\",\n  \"lines\": [\n    {\n      \"description\": \"Ajuste de prueba\",\n      \"quantity\": 1,\n      \"unit_price\": 20000,\n      \"tax_category\": \"gravado\",\n      \"tax_rate\": 19\n    }\n  ]\n}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        }
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('invoiceId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener invoiceId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 201', () => pm.expect(pm.response.code).to.eql(201));",
              "const doc = pm.response.json().data;",
              "verify('Documento sandbox aceptado y total 23800', () => {",
              "  pm.expect(doc.environment).to.eql('sandbox');",
              "  pm.expect(doc.status).to.eql('aceptada');",
              "  pm.expect(doc.type).to.eql('credit_note');",
              "  pm.expect(doc.total).to.eql(23800);",
              "  pm.expect(doc.id).to.match(/^[0-9a-f-]{36}$/i);",
              "  pm.expect(doc.cufe).to.match(/^[0-9a-f]{96}$/i);",
              "});",
              "verify('Referencia a factura de esta ejecución', () => pm.expect(doc.reference_id).to.eql(pm.variables.get('invoiceId')));",
              "pm.variables.set('creditNoteId', doc.id);",
              "pm.variables.set('creditNoteIdCufe', doc.cufe);",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "07 · Crédito excesivo (422 esperado)",
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/api/public/v1/credit-notes",
        "description": "Intenta acreditar $119.000, superior al saldo de $83.300. No crea documento.",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"invoice_id\": \"{{invoiceId}}\",\n  \"external_id\": \"postman-{{runId}}-exceso\",\n  \"reason_code\": \"1\",\n  \"description\": \"Crédito excesivo de prueba\",\n  \"lines\": [\n    {\n      \"description\": \"Ajuste de prueba\",\n      \"quantity\": 1,\n      \"unit_price\": 100000,\n      \"tax_category\": \"gravado\",\n      \"tax_rate\": 19\n    }\n  ]\n}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        }
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('creditNoteId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener creditNoteId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 422', () => pm.expect(pm.response.code).to.eql(422));",
              "verify('Error esperado credit_exceeds_balance', () => pm.expect(pm.response.json().error.code).to.eql('credit_exceeds_balance'));",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "08 · Nota débito $11.900",
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "url": "{{baseUrl}}/api/public/v1/debit-notes",
        "description": "Intereses de prueba: $10.000 más IVA 19%.",
        "body": {
          "mode": "raw",
          "raw": "{\n  \"invoice_id\": \"{{invoiceId}}\",\n  \"external_id\": \"postman-{{runId}}-debito\",\n  \"reason_code\": \"1\",\n  \"description\": \"Intereses de prueba\",\n  \"lines\": [\n    {\n      \"description\": \"Ajuste de prueba\",\n      \"quantity\": 1,\n      \"unit_price\": 10000,\n      \"tax_category\": \"gravado\",\n      \"tax_rate\": 19\n    }\n  ]\n}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        }
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('invoiceId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener invoiceId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 201', () => pm.expect(pm.response.code).to.eql(201));",
              "const doc = pm.response.json().data;",
              "verify('Documento sandbox aceptado y total 11900', () => {",
              "  pm.expect(doc.environment).to.eql('sandbox');",
              "  pm.expect(doc.status).to.eql('aceptada');",
              "  pm.expect(doc.type).to.eql('debit_note');",
              "  pm.expect(doc.total).to.eql(11900);",
              "  pm.expect(doc.id).to.match(/^[0-9a-f-]{36}$/i);",
              "  pm.expect(doc.cufe).to.match(/^[0-9a-f]{96}$/i);",
              "});",
              "verify('Referencia a factura de esta ejecución', () => pm.expect(doc.reference_id).to.eql(pm.variables.get('invoiceId')));",
              "pm.variables.set('debitNoteId', doc.id);",
              "pm.variables.set('debitNoteIdCufe', doc.cufe);",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "09 · Consultar factura",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/documents/{{invoiceId}}",
        "description": "Verifica la factura creada en esta ejecución."
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('invoiceId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener invoiceId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 200', () => pm.expect(pm.response.code).to.eql(200));",
              "verify('Factura consultada coincide', () => { const doc = pm.response.json().data; pm.expect(doc.id).to.eql(pm.variables.get('invoiceId')); pm.expect(doc.total).to.eql(107100); pm.expect(doc.status).to.eql('aceptada'); pm.expect(doc.environment).to.eql('sandbox'); });",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "10 · XML Invoice",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/documents/{{invoiceId}}?format=xml",
        "description": "XML sandbox sin firma ni valor fiscal. El Runner valida el contenido, no guarda archivos."
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('invoiceId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener invoiceId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 200', () => pm.expect(pm.response.code).to.eql(200));",
              "verify('XML Invoice y CUFE/CUDE de esta ejecución', () => { pm.expect(pm.response.headers.get('content-type')).to.include('xml'); pm.expect(pm.response.text()).to.include('<Invoice'); pm.expect(pm.response.text()).to.include(pm.variables.get('invoiceIdCufe')); });",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "11 · XML CreditNote",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/documents/{{creditNoteId}}?format=xml",
        "description": "XML sandbox sin firma ni valor fiscal. El Runner valida el contenido, no guarda archivos."
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('creditNoteId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener creditNoteId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 200', () => pm.expect(pm.response.code).to.eql(200));",
              "verify('XML CreditNote y CUFE/CUDE de esta ejecución', () => { pm.expect(pm.response.headers.get('content-type')).to.include('xml'); pm.expect(pm.response.text()).to.include('<CreditNote'); pm.expect(pm.response.text()).to.include(pm.variables.get('creditNoteIdCufe')); });",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "12 · XML DebitNote",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/documents/{{debitNoteId}}?format=xml",
        "description": "XML sandbox sin firma ni valor fiscal. El Runner valida el contenido, no guarda archivos."
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('debitNoteId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener debitNoteId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 200', () => pm.expect(pm.response.code).to.eql(200));",
              "verify('XML DebitNote y CUFE/CUDE de esta ejecución', () => { pm.expect(pm.response.headers.get('content-type')).to.include('xml'); pm.expect(pm.response.text()).to.include('<DebitNote'); pm.expect(pm.response.text()).to.include(pm.variables.get('debitNoteIdCufe')); });",
              "})();"
            ]
          }
        }
      ],
      "response": []
    },
    {
      "name": "13 · Listar documentos",
      "request": {
        "method": "GET",
        "header": [],
        "url": "{{baseUrl}}/api/public/v1/invoices?limit=100",
        "description": "Confirma que factura, crédito y débito aparecen en el listado de sandbox."
      },
      "event": [
        {
          "listen": "prerequest",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "if (!pm.variables.get('debitNoteId')) { pm.execution.skipRequest(); pm.execution.setNextRequest(null); throw new Error('Ejecute la colección completa en orden para obtener debitNoteId.'); }",
              "})();"
            ]
          }
        },
        {
          "listen": "test",
          "script": {
            "type": "text/javascript",
            "exec": [
              "(function () {",
              "function verify(name, fn) {",
              "  let failed = false;",
              "  pm.test(name, function () { try { fn(); } catch (e) { failed = true; throw e; } });",
              "  if (failed) { pm.execution.setNextRequest(null); throw new Error('Prueba fallida: ' + name + '. Corrija la causa y reinicie desde el paso 01.'); }",
              "}",
              "verify('HTTP 200', () => pm.expect(pm.response.code).to.eql(200));",
              "verify('Tres documentos disponibles', () => { const docs = pm.response.json().data; pm.expect(docs).to.be.an('array'); for (const key of ['invoiceId', 'creditNoteId', 'debitNoteId']) pm.expect(docs.some(doc => doc.id === pm.variables.get(key) && doc.environment === 'sandbox')).to.eql(true); });",
              "})();"
            ]
          }
        }
      ],
      "response": []
    }
  ]
}
