{
  "name": "LicitaIA - buscar licitaciones y upsert en Google Sheets",
  "nodes": [
    {
      "parameters": {},
      "id": "manual-trigger",
      "name": "Ejecutar manualmente",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        260,
        300
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "query",
              "name": "query",
              "value": "",
              "type": "string"
            },
            {
              "id": "cpv",
              "name": "cpv",
              "value": "",
              "type": "string"
            },
            {
              "id": "provincia",
              "name": "provincia",
              "value": "",
              "type": "string"
            },
            {
              "id": "organismo",
              "name": "organismo",
              "value": "",
              "type": "string"
            },
            {
              "id": "page",
              "name": "page",
              "value": 1,
              "type": "number"
            },
            {
              "id": "limit",
              "name": "limit",
              "value": 20,
              "type": "number"
            },
            {
              "id": "spreadsheet-id",
              "name": "spreadsheetId",
              "value": "REEMPLAZAR_CON_ID_DEL_DOCUMENTO",
              "type": "string"
            },
            {
              "id": "sheet-name",
              "name": "sheetName",
              "value": "Licitaciones",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "configuration",
      "name": "Configuración (editar filtros)",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        480,
        300
      ]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "https://api.licitaia.org/api/v1/licitaciones",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "specifyQuery": "json",
        "jsonQuery": "={{ JSON.stringify(Object.fromEntries(Object.entries({query: String($json.query || '').trim(), cpv: String($json.cpv || '').trim(), provincia: String($json.provincia || '').trim(), organismo: String($json.organismo || '').trim(), page: Math.min(Math.max(Math.trunc(Number($json.page) || 1), 1), 2), limit: Math.min(Math.max(Math.trunc(Number($json.limit) || 20), 1), 20)}).filter(([key, value]) => value !== ''))) }}",
        "options": {
          "timeout": 30000,
          "response": {
            "response": {
              "responseFormat": "json",
              "neverError": true,
              "fullResponse": true
            }
          }
        }
      },
      "id": "licitaia-search",
      "name": "LicitaIA API (Header Auth)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        720,
        300
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "",
          "name": "LicitaIA API key (x-api-key)"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const input = $json;\nconst status = Number(input.statusCode ?? 200);\nconst body = input.body && typeof input.body === 'object' ? input.body : input;\nconst esFree = body.meta && typeof body.meta === 'object';\nconst esPro = body.page !== undefined && body.totalPages !== undefined;\nconst ok = status >= 200 && status < 300 && Array.isArray(body.data) && (esFree || esPro);\nif (!ok) return [{ json: { ok: false, tipoRegistro: 'ERROR', statusCode: status, codigo: body.code || 'API_ERROR', mensaje: body.message || 'La API no devolvió una respuesta válida. No se guardaron filas.' } }];\nconst items = body.data;\nconst meta = body.meta ?? { total: body.total, page: body.page, limit: body.limit, totalPages: body.totalPages, truncado: Number(body.totalPages ?? 1) > Number(body.page ?? 1) };\nconst page = Number(meta.page ?? 1);\nconst totalPages = Number(meta.totalPages ?? 1);\nconst safeText = (value) => { if (value === null || value === undefined) return ''; const text = String(value); return /^[\\s\\u0000-\\u001f=+\\-@]/.test(text) ? \"'\" + text : text; };\nconst safeNumber = (value) => typeof value === 'number' && Number.isFinite(value) ? value : '';\nconst validId = (value) => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);\nconst alerta = meta.truncado === true || totalPages > page ? 'Muestra limitada; puede haber resultados fuera del alcance o de esta página.' : 'Resultado limitado a la página solicitada; no es una vigilancia exhaustiva.';\nif (items.length === 0) return [{ json: { ok: true, tipoRegistro: 'RESUMEN', alerta: 'No se encontraron licitaciones con estos filtros.', total: Number(meta.total ?? 0), pagina: page, totalPaginas: totalPages } }];\nreturn items.map((item) => {\n  if (!validId(item?.id)) return { json: { ok: false, tipoRegistro: 'ERROR', statusCode: 200, codigo: 'ID_INVALIDO', mensaje: 'La respuesta contiene una licitación sin UUID válido. No se hizo upsert.' } };\n  return { json: { ok: true, tipoRegistro: 'LICITACION', id: item.id, titulo: safeText(item.title), organismo: safeText(item.organismo), presupuesto: safeNumber(item.presupuestoBase), plazo: safeText(item.fechaLimite), enlaceOficial: safeText(item.enlaces?.oficial ?? item.urlAnuncio), enlaceLicitaIA: safeText(item.enlaces?.licitaia ?? `https://licitaia.org/licitaciones/${item.id}/`), cpv: safeText(item.cpv ?? item.cpvCode), provincia: safeText(item.lugar ?? item.lugarEjecucion), pagina: page, totalPaginas: totalPages, alerta: safeText(alerta), actualizadoEn: new Date().toISOString() } };\n});"
      },
      "id": "normalize-response",
      "name": "Normalizar y proteger datos",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        300
      ]
    },
    {
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "ok-condition",
              "leftValue": "={{$json.ok}}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      },
      "id": "api-ok",
      "name": "¿Respuesta válida?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1180,
        300
      ]
    },
    {
      "parameters": {
        "options": {
          "caseSensitive": true,
          "leftValue": "",
          "typeValidation": "strict",
          "version": 2
        },
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "row-condition",
              "leftValue": "={{$json.tipoRegistro}}",
              "rightValue": "LICITACION",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        }
      },
      "id": "has-row",
      "name": "¿Hay licitación?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1400,
        220
      ]
    },
    {
      "parameters": {
        "operation": "appendOrUpdate",
        "authentication": "oAuth2",
        "documentId": {
          "__rl": true,
          "value": "={{$('Configuración (editar filtros)').first().json.spreadsheetId}}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "={{$('Configuración (editar filtros)').first().json.sheetName}}",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "id": "={{$json.id}}",
            "titulo": "={{$json.titulo}}",
            "organismo": "={{$json.organismo}}",
            "presupuesto": "={{$json.presupuesto}}",
            "plazo": "={{$json.plazo}}",
            "enlaceOficial": "={{$json.enlaceOficial}}",
            "enlaceLicitaIA": "={{$json.enlaceLicitaIA}}",
            "cpv": "={{$json.cpv}}",
            "provincia": "={{$json.provincia}}",
            "pagina": "={{$json.pagina}}",
            "totalPaginas": "={{$json.totalPaginas}}",
            "alerta": "={{$json.alerta}}",
            "actualizadoEn": "={{$json.actualizadoEn}}"
          },
          "matchingColumns": [
            "id"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": true,
              "defaultMatch": true,
              "display": true,
              "type": "string"
            },
            {
              "id": "titulo",
              "displayName": "titulo",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "organismo",
              "displayName": "organismo",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "presupuesto",
              "displayName": "presupuesto",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number"
            },
            {
              "id": "plazo",
              "displayName": "plazo",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "enlaceOficial",
              "displayName": "enlaceOficial",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "enlaceLicitaIA",
              "displayName": "enlaceLicitaIA",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "cpv",
              "displayName": "cpv",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "provincia",
              "displayName": "provincia",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "pagina",
              "displayName": "pagina",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number"
            },
            {
              "id": "totalPaginas",
              "displayName": "totalPaginas",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number"
            },
            {
              "id": "alerta",
              "displayName": "alerta",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            },
            {
              "id": "actualizadoEn",
              "displayName": "actualizadoEn",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string"
            }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "google-sheets-upsert",
      "name": "Google Sheets: upsert por id",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1640,
        220
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets OAuth2"
        }
      }
    }
  ],
  "connections": {
    "Ejecutar manualmente": {
      "main": [
        [
          {
            "node": "Configuración (editar filtros)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Configuración (editar filtros)": {
      "main": [
        [
          {
            "node": "LicitaIA API (Header Auth)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "LicitaIA API (Header Auth)": {
      "main": [
        [
          {
            "node": "Normalizar y proteger datos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar y proteger datos": {
      "main": [
        [
          {
            "node": "¿Respuesta válida?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Respuesta válida?": {
      "main": [
        [
          {
            "node": "¿Hay licitación?",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "¿Hay licitación?": {
      "main": [
        [
          {
            "node": "Google Sheets: upsert por id",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    }
  },
  "pinData": {},
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "1771b2dc-132a-48c5-b296-e02961e109b2",
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
