{
  "name": "LCBP3 Migration Workflow v1.8.1",
  "nodes": [
    {
      "parameters": {
        "formTitle": "LCBP3 Migration - เลือก Model",
        "formDescription": "กรุณาเลือก Ollama Model และตั้งค่าก่อนรัน",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Ollama Model (Primary)",
              "fieldType": "dropdown",
              "fieldOptions": {
                "values": [
                  {
                    "option": "scb10x/typhoon2.1-gemma3-4b (เร็ว + ไทยดี)"
                  },
                  {
                    "option": "qwen2.5:7b-instruct-q4_K_M (สมดุล - แนะนำ)"
                  },
                  {
                    "option": "promptnow/openthaigpt1.5-7b-instruct-q4_k_m (ไทยเฉพาะทาง)"
                  }
                ]
              },
              "requiredField": true
            },
            {
              "fieldLabel": "Batch Size",
              "fieldType": "number",
              "placeholder": "2"
            },
            {
              "fieldLabel": "Excel File Path",
              "placeholder": "/home/node/.n8n-files/staging_ai/C22024.xlsx"
            }
          ]
        },
        "options": {}
      },
      "id": "347a7bdb-b681-45dc-b9eb-2fe15e9d7eb3",
      "name": "Form Trigger",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.2,
      "position": [3952, -26304],
      "webhookId": "8c87176d-fa61-4a82-ab2a-1c14615e720c",
      "notes": "เปิด URL เพื่อเลือก Model ก่อนรัน"
    },
    {
      "parameters": {
        "jsCode": "// Read model selected from Form Trigger dropdown\nconst formData = $('Form Trigger').first()?.json || {};\nconst selectedModelLabel = String(formData['Ollama Model (Primary)'] || '');\n\n// Extract just the model ID (before the space in the label)\nconst MODEL_MAP = {\n  'qwen2.5:7b-instruct-q4_K_M (สมดุล - แนะนำ)': 'qwen2.5:7b-instruct-q4_K_M',\n  'scb10x/typhoon2.1-gemma3-4b (เร็ว + ไทยดี)': 'scb10x/typhoon2.1-gemma3-4b',\n  'promptnow/openthaigpt1.5-7b-instruct-q4_k_m (ไทยเฉพาะทาง)': 'promptnow/openthaigpt1.5-7b-instruct-q4_k_m'\n};\nconst selectedModel = MODEL_MAP[selectedModelLabel] || 'scb10x/typhoon2.1-gemma3-4b';\n\nconst batchSizeInput = parseInt(formData['Batch Size'] || '0');\nconst excelFileInput = String(formData['Excel File Path'] || '').trim();\n\nconst CONFIG = {\n  // Ollama Settings\n  OLLAMA_HOST: 'http://192.168.20.100:11434',\n  // Model selected from Form UI\n  OLLAMA_MODEL_PRIMARY: selectedModel,\n  // Fallback\n  OLLAMA_MODEL_FALLBACK: 'mistral:7b-instruct-q4_K_M',\n  \n  // Backend Settings\n  BACKEND_URL: 'https://backend.np-dms.work',\n  MIGRATION_TOKEN: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im1pZ3JhdGlvbl9ib3QiLCJzdWIiOjUsInNjb3BlIjoiR2xvYmFsIiwiaWF0IjoxNzcyNzc0MzI5LCJleHAiOjQ5Mjg1MzQzMjl9.TtA8zoHy7G9J5jPgYQPv7yw-9X--B_hl-Nv-c9V4PaA',\n  \n  // Batch Settings\n  BATCH_SIZE: batchSizeInput > 0 ? batchSizeInput : 2,\n  BATCH_ID: (() => { const d = new Date(Date.now() + 7 * 3600000); const s = d.toISOString(); return s.substring(0,10).replace(/-/g,'') + ':' + s.substring(11,16).replace(/:/g,''); })(),\n  DELAY_MS: 2000,\n  \n  // Thresholds\n  CONFIDENCE_HIGH: 0.85,\n  CONFIDENCE_LOW: 0.60,\n  MAX_RETRY: 3,\n  FALLBACK_THRESHOLD: 5,\n  \n  // Source Definitions - แก้ไขโฟลเดอร์และไฟล์ทำงานที่นี่\n  EXCEL_FILE: excelFileInput || '/home/node/.n8n-files/staging_ai/C22024.xlsx',\n  SOURCE_PDF_DIR: '/home/node/.n8n-files/staging_ai/Incoming/08C.2/2567',\n  LOG_PATH: '/home/node/.n8n-files/migration_logs',\n  PROJECT_ID: 1\n};\n\nreturn { config: CONFIG };"
      },
      "id": "20824a92-7433-4644-be1a-22ddc665bb44",
      "name": "Set Configuration",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [4112, -26304],
      "notes": "กำหนดค่า Configuration ทั้งหมด - แก้ไขที่นี่ก่อนรัน"
    },
    {
      "parameters": {
        "url": "={{$('Set Configuration').first().json.config.BACKEND_URL}}/api/master/correspondence-types",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "={{$('Set Configuration').first().json.config.MIGRATION_TOKEN}}"
            }
          ]
        },
        "options": {
          "timeout": 10000
        }
      },
      "id": "8a1b921e-def2-4302-bf77-3e0e717bfc11",
      "name": "Fetch Categories",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [4000, -26128],
      "notes": "ดึง Categories จาก Backend"
    },
    {
      "parameters": {
        "url": "={{$('Set Configuration').first().json.config.BACKEND_URL}}/api/master/tags",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "={{$('Set Configuration').first().json.config.MIGRATION_TOKEN}}"
            }
          ]
        },
        "options": {
          "timeout": 10000
        }
      },
      "id": "cac43f4f-eef6-4783-a622-968d15a672b0",
      "name": "Fetch Tags",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [4144, -26128],
      "notes": "ดึง Tags ที่มีอยู่แล้วจาก Backend"
    },
    {
      "parameters": {
        "jsCode": "const fs = require('fs');\nconst config = $('Set Configuration').first().json.config;\n\n// Check file mount and inputs\ntry {\n  if (!fs.existsSync(config.EXCEL_FILE)) {\n    throw new Error(`Excel file not found at: ${config.EXCEL_FILE}`);\n  }\n  if (!fs.existsSync(config.SOURCE_PDF_DIR)) {\n    throw new Error(`PDF Source directory not found at: ${config.SOURCE_PDF_DIR}`);\n  }\n  \n  const files = fs.readdirSync(config.SOURCE_PDF_DIR);\n  \n  // Check write permission to log path\n  if (!fs.existsSync(config.LOG_PATH)) {\n    fs.mkdirSync(config.LOG_PATH, { recursive: true });\n  }\n  fs.writeFileSync(`${config.LOG_PATH}/.preflight_ok`, new Date().toISOString());\n  \n  // Grab categories out of the previous node (Fetch Categories) if available\n  // API returns raw array — each item becomes a separate n8n item\n  let categories = ['Correspondence','RFA','Drawing','Transmittal','Report','Other'];\n  try {\n    const upstreamItems = $('Fetch Categories').all().map(i => i.json);\n    if (upstreamItems && upstreamItems.length > 0) {\n        categories = upstreamItems.map(c => c.typeName || c.typeCode || c); \n    }\n  } catch(e) {}\n  \n  // Grab existing tags from Fetch Tags node\n  // API returns raw array — each item becomes a separate n8n item\n  let existingTags = [];\n  try {\n    const tagItems = $('Fetch Tags').all().map(i => i.json);\n    existingTags = Array.isArray(tagItems) ? tagItems.map(t => t.tag_name || t.name || '').filter(Boolean) : [];\n  } catch(e) {}\n    \n  return [{ json: { \n    preflight_ok: true, \n    pdf_count_in_source: files.length,\n    excel_target: config.EXCEL_FILE,\n    system_categories: categories,\n    existing_tags: existingTags,\n    timestamp: new Date().toISOString()\n  }}];\n} catch (err) {\n  throw new Error(`Pre-flight check failed: ${err.message}`);\n}"
      },
      "id": "5878a59f-a287-4658-90ff-5f47fb2dcf9f",
      "name": "File Mount Check",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [4288, -26128],
      "notes": "ตรวจสอบ File System มีไฟล์ Excel และ Folder ตามตั้งค่า"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT last_processed_index, status FROM migration_progress WHERE batch_id = '{{$('Set Configuration').first().json.config.BATCH_ID}}' LIMIT 1",
        "options": {}
      },
      "id": "96d5491d-d2ad-4f5f-bcb0-899509edae9f",
      "name": "Read Checkpoint",
      "type": "n8n-nodes-base.mySql",
      "typeVersion": 2.4,
      "position": [4320, -25936],
      "alwaysOutputData": true,
      "credentials": {
        "mySql": {
          "id": "CHHfbKhMacNo03V4",
          "name": "MySQL account"
        }
      },
      "onError": "continueErrorOutput",
      "notes": "อ่านตำแหน่งล่าสุดที่ประมวลผล"
    },
    {
      "parameters": {
        "fileSelector": "={{ $json.excel_target }}",
        "options": {}
      },
      "id": "dc51fe19-c41b-4272-9fad-da9977ee3683",
      "name": "Read Excel Binary",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [4000, -25936],
      "notes": "ดึงไฟล์ Excel ขึ้นมาไว้ในหน่วยความจำ"
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "6d6fba87-9a86-4cb2-bd02-0340a8dab023",
      "name": "Read Excel",
      "type": "n8n-nodes-base.spreadsheetFile",
      "typeVersion": 2,
      "position": [4160, -25936],
      "notes": "แปลงข้อมูล Excel เป็น JSON Data"
    },
    {
      "parameters": {
        "jsCode": "const cpJson = $input.first()?.json || {};\nconst startIndex = cpJson.last_processed_index || 0;\nconst config = $('Set Configuration').first().json.config;\n\nconst allItems = $('Read Excel').all().map(i => i.json);\nconst remaining = allItems.slice(startIndex);\nconst currentBatch = remaining.slice(0, config.BATCH_SIZE);\n\n// Encoding Normalization\nconst normalize = (str) => {\n  if (!str) return '';\n  return String(str).normalize('NFC').trim();\n};\n\nreturn currentBatch.map((item, i) => {\n  const getVal = (possibleKeys) => {\n    const exactMatch = possibleKeys.find(k => item[k] !== undefined);\n    if (exactMatch) return item[exactMatch];\n    const lowerTrimmedKeys = Object.keys(item).map(k => ({ original: k, parsed: k.toLowerCase().trim() }));\n    for (const pk of possibleKeys) {\n      const found = lowerTrimmedKeys.find(k => k.parsed === pk.toLowerCase().trim());\n      if (found) return item[found.original];\n    }\n    return '';\n  };\n\n  const docNum = getVal(['document_number', 'correspondence_number', 'Document Number', 'Corr. No.']);\n  const excelFileName = getVal(['File name', 'file_name', 'File Name', 'filename']);\n  \n  if (!excelFileName) {\n    throw new Error(`Missing 'File name' column for row ${i + startIndex + 1}, document: ${docNum}`);\n  }\n  \n  return {\n    json: {\n      document_number: normalize(docNum),\n      subject: normalize(getVal(['Subject', 'subject', 'Title', 'title'])),\n      remarks: normalize(getVal(['remarks'])),\n      excel_revision: getVal(['revision', 'Revision', 'rev']) || 1,\n      original_index: startIndex + i,\n      batch_id: config.BATCH_ID,\n      file_name: normalize(excelFileName),\n      issued_date: normalize(getVal(['issued_date', 'Issued_date', 'Issued Date', 'date', 'Date', 'document_date'])),\n      received_date: normalize(getVal(['received_date', 'Received_date', 'Received Date'])),\n      correspondence_type: getVal(['correspondence_type', 'type', 'Type', 'Category']),\n      sender: normalize(getVal(['sender', 'Sender', 'From', 'from'])),\n      receiver: normalize(getVal(['receiver', 'Receiver', 'To', 'to'])),\n      project_code: normalize(getVal(['project', 'Project', 'project_code']))\n    }\n  };\n});"
      },
      "id": "1f115c9e-ecf0-4c8b-b035-876d6fc2da4f",
      "name": "Process Batch + Encoding",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [4560, -25952],
      "alwaysOutputData": true,
      "notes": "ตัด Batch + Normalize UTF-8"
    },
    {
      "parameters": {
        "jsCode": "const fs = require('fs');\nconst path = require('path');\nconst config = $('Set Configuration').first().json.config;\n\nconst items = $input.all();\nif (!items || items.length === 0) return [];\n\nconst validated = [];\nconst errors = [];\n\nfor (const item of items) {\n  const fileName = item.json?.file_name;\n  if (!fileName) {\n    errors.push({\n      ...item,\n      json: { ...item.json, file_valid: false, error: 'file_name is missing', error_type: 'FILE_NOT_FOUND', file_exists: false }\n    });\n    continue;\n  }\n  \n  let safeName = path.basename(String(fileName)).normalize('NFC');\n  if (!safeName.toLowerCase().endsWith('.pdf')) {\n    safeName += '.pdf';\n  }\n  const filePath = path.resolve(config.SOURCE_PDF_DIR, safeName);\n  \n  if (!filePath.startsWith(path.resolve(config.SOURCE_PDF_DIR))) {\n    errors.push({\n      ...item,\n      json: { ...item.json, file_valid: false, error: 'Path traversal detected', error_type: 'SECURITY', file_exists: false }\n    });\n    continue;\n  }\n  \n  try {\n    if (fs.existsSync(filePath)) {\n      const stats = fs.statSync(filePath);\n      validated.push({\n        ...item,\n        json: { ...item.json, file_valid: true, file_exists: true, file_size: stats.size, file_path: filePath }\n      });\n    } else {\n      errors.push({\n        ...item,\n        json: { ...item.json, file_valid: false, error: `File not found: ${safeName}`, error_type: 'FILE_NOT_FOUND', file_exists: false }\n      });\n    }\n  } catch (err) {\n    errors.push({\n      ...item,\n      json: { ...item.json, file_valid: false, error: err.message, error_type: 'UNKNOWN', file_exists: false }\n    });\n  }\n}\n\n// Log errors inline to CSV (single-output node — errors don't flow downstream)\nif (errors.length > 0) {\n  const csvPath = `${config.LOG_PATH}/error_log.csv`;\n  const header = 'timestamp,document_number,error_type,error_message\\n';\n  const esc = (s) => `\"${String(s || '').replace(/\"/g, '\"\"')}\"`;\n  if (!fs.existsSync(config.LOG_PATH)) fs.mkdirSync(config.LOG_PATH, { recursive: true });\n  if (!fs.existsSync(csvPath)) fs.writeFileSync(csvPath, header, 'utf8');\n  for (const e of errors) {\n    const line = [new Date().toISOString(), esc(e.json.document_number), esc(e.json.error_type), esc(e.json.error)].join(',') + '\\n';\n    fs.appendFileSync(csvPath, line, 'utf8');\n  }\n}\n\nreturn validated;"
      },
      "id": "8fb3d45a-eecb-4415-aee0-841420d3779f",
      "name": "File Validator",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [4704, -25952],
      "notes": "ตรวจสอบไฟล์ PDF ตัวชี้ใน Directory จาก Config"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT is_fallback_active, recent_error_count FROM migration_fallback_state WHERE batch_id = '{{$('Set Configuration').first().json.config.BATCH_ID}}' LIMIT 1",
        "options": {}
      },
      "id": "81bb9e8f-5e11-4787-92ac-7cc660796f06",
      "name": "Check Fallback State",
      "type": "n8n-nodes-base.mySql",
      "typeVersion": 2.4,
      "position": [5056, -26336],
      "alwaysOutputData": true,
      "credentials": {
        "mySql": {
          "id": "CHHfbKhMacNo03V4",
          "name": "MySQL account"
        }
      },
      "onError": "continueErrorOutput",
      "notes": "ตรวจสอบว่าต้องใช้ Fallback Model หรือไม่"
    },
    {
      "parameters": {
        "jsCode": "const config = $('Set Configuration').first().json.config;\nconst fallbackState = $('Check Fallback State').first()?.json || { is_fallback_active: false, recent_error_count: 0 };\nconst isFallback = fallbackState.is_fallback_active || false;\nconst model = isFallback ? config.OLLAMA_MODEL_FALLBACK : config.OLLAMA_MODEL_PRIMARY;\n\n// Read DB Context\nconst dbContext = $('Fetch DB Context').all().map(i => i.json);\nconst dbProjects = dbContext.filter(d => d.type === 'projects').map(d => ({id: d.id, code: d.text1, name: d.text2}));\nconst dbDisciplines = dbContext.filter(d => d.type === 'disciplines').map(d => ({id: d.id, th: d.text1, en: d.text2}));\nconst dbOrgs = dbContext.filter(d => d.type === 'organizations').map(d => ({id: d.id, name: d.text1, code: d.text2}));\nconst dbTags = dbContext.filter(d => d.type === 'tags').map(d => ({id: d.id, name: d.text1}));\nconst dbCorrTypes = dbContext.filter(d => d.type === 'correspondence_types').map(d => ({id: d.id, code: d.text1, name: d.text2}));\n\nlet systemCategories = ['Correspondence','RFA','Drawing','Transmittal','Report','Other'];\ntry { systemCategories = $('File Mount Check').first().json.system_categories || systemCategories; } catch (e) {}\n\nconst pdfItems = $('Extract PDF Text').all();\n// File Validator passes all original Excel JSON fields through (sender, receiver, project_code, etc.)\n// Read PDF File overwrites the JSON with binary data, so we must go back one step\nconst metaItems = $('File Validator').all();\n\nreturn pdfItems.map((pdfItem, i) => {\n  const item = metaItems[i] || pdfItem;\n\n  const docNum = String(item.json.document_number || '');\n  const subject = String(item.json.subject || '');\n  const projectCode = String(item.json.project_code || '');\n  const remarks = String(item.json.remarks || '');\n  const issuedDate = String(item.json.issued_date || '');\n  const receivedDate = String(item.json.received_date || '');\n  const corrType = String(item.json.correspondence_type || '');\n  const senderCode = String(item.json.sender || '');\n  const receiverCode = String(item.json.receiver || '');\n\n  // Resolve correspondence_type from Excel against DB\n  const resolveType = () => {\n    if (!corrType) return { type_id: null, type_code: null };\n    const ct = Number(corrType);\n    if (!isNaN(ct) && ct > 0) {\n      const found = dbCorrTypes.find(t => t.id === ct);\n      return found ? { type_id: found.id, type_code: found.code } : { type_id: null, type_code: null };\n    }\n    const found = dbCorrTypes.find(t =>\n      t.code === corrType || t.name === corrType ||\n      t.code.toLowerCase() === corrType.toLowerCase() ||\n      t.name.toLowerCase() === corrType.toLowerCase()\n    );\n    return found ? { type_id: found.id, type_code: found.code } : { type_id: null, type_code: null };\n  };\n  const resolvedType = resolveType();\n\n  // JavaScript pre-mapping (same as spec)\n  const findOrgId = (code) => {\n    if (!code) return null;\n    const match = dbOrgs.find(o => o.code === code || o.name === code);\n    return match ? match.id : null;\n  };\n\n  const findProjectId = (code) => {\n    if (!code) return config.PROJECT_ID;\n    const match = dbProjects.find(p => p.code === code || p.name === code);\n    return match ? match.id : config.PROJECT_ID;\n  };\n\n  const senderId = findOrgId(senderCode);\n  const receiverId = findOrgId(receiverCode);\n  const projectId = findProjectId(projectCode);\n\n  const isRFA = docNum.includes('-RFA-') || subject.toLowerCase().includes('rfa');\n\n  // ====== System Prompt (from spec — sets AI role) ======\n  const systemPrompt = `You are an expert Document Controller for a construction project (LCBP3) in Thailand.\nThe documents are primarily in THAI and ENGLISH.\nYour task is to classify documents and extract metadata from OCR text.\nRespond ONLY with valid JSON.`;\n\n  // ====== OCR Text (cleaned — from spec) ======\n  // Use pdfItem for the OCR extracted data, NOT the metaItem\n  const pdfText = String(pdfItem.json.data || pdfItem.json.response || '').substring(0, 3500).replace(/[^a-zA-Z0-9\\u0E01-\\u0E5B\\s\\.\\/\\-:\\[\\]\\(\\)]/g, ' ');\n\n  // ====== User Prompt (structured sections — from spec) ======\n  const userPrompt = `Analyze this document:\n[EXCEL METADATA]\nDocument Number: ${docNum || 'Not provided'}\nSubject: ${subject || 'Not provided'}\nIssued Date: ${issuedDate || 'Not provided'}\nReceived Date: ${receivedDate || 'Not provided'}\n\n[DATABASE REFERENCES]\nDisciplines: ${JSON.stringify(dbDisciplines)}\nTags: ${JSON.stringify(dbTags)}\n\n[OCR TEXT EXTRACTION]\n${pdfText}\n\nRules:\n1. Category: Must be one of ${JSON.stringify(systemCategories)}. If Document Number contains \"-RFA-\", category MUST be \"RFA\".\n2. Respond with EXACTLY 8 fields in JSON format:\n   - \"discipline_id\": Find 'id' from Disciplines array analyzing text to match 'th' or 'en'. If no match, use ID=64 (from contract LCBP3-C2).\n   - \"subject\": Document subject. If OCR is close to EXCEL METADATA Subject, use EXCEL METADATA.\n   - \"issued_date\": Verify from OCR text if it matches ${issuedDate}, format YYYY-MM-DD.\n   - \"received_date\": Verify from OCR text. If empty, default to issued_date.\n   - \"status\": Extract status (e.g., For Information, Approve, Reject, Resubmit). This will be exported as \"remark\".\n   - \"summary\": 4-5 lines of Thai summary from OCR. This will be exported as \"body\".\n   - \"tags\": REQUIRED. Identify 2-5 main topics/themes from the document (from Subject, subject matter, and OCR text). For each topic, return an object with:\n      * \"tag_name\": short topic name in Thai (2-5 words), e.g. \"คอนกรีตผสม\", \"ทดสอบวัสดุ\"\n      * \"description\": one sentence in Thai describing this topic (use key point details). e.g. \"การทดสอบค่า slump ของคอนกรีตผสมที่หน้างาน\"\n      Return as: [{\"tag_name\": \"...\", \"description\": \"...\"}, ...]\n   - \"key_points\": Array of 3-5 string key points extracted from the document (in Thai).\n\n3. IMPORTANT: You MUST REPLACE the 'null' values in the template below with the actual Integer IDs or text you found. DO NOT reply with literal 'null' if you found a match!\n\nRespond ONLY with this EXACT JSON structure:\n{\n  \"discipline_id\": 64,\n  \"subject\": \"${subject}\",\n  \"issued_date\": \"${issuedDate}\",\n  \"received_date\": \"${receivedDate || issuedDate}\",\n  \"status\": null,\n  \"summary\": \"สรุปเนื้อหา 4-5 บรรทัด...\",\n  \"tags\": [{\"tag_name\": \"ชื่อหัวข้อ\", \"description\": \"คำอธิบาย key point ของหัวข้อนี้\"}],\n  \"key_points\": [\"จุดสำคัญที่ 1\", \"จุดสำคัญที่ 2\", \"จุดสำคัญที่ 3\"],\n  \"category\": \"${isRFA ? 'RFA' : 'Correspondence'}\",\n  \"confidence\": 0.95\n}`;\n\n  return {\n    json: {\n      ...item.json,\n      active_model: model,\n      is_fallback: isFallback,\n      system_categories: systemCategories,\n      pre_mapped: {\n        project_id: projectId,\n        sender_id: senderId,\n        receiver_id: receiverId,\n        correspondence_type_id: resolvedType.type_id,\n        type_id: resolvedType.type_id,\n        type_code: resolvedType.type_code\n      },\n      _debug_mapping: {\n        excel_project_code: projectCode,\n        excel_sender: senderCode,\n        excel_receiver: receiverCode,\n        excel_corr_type: corrType,\n        matched_project: dbProjects.find(p => p.code === projectCode || p.name === projectCode) || null,\n        first_org_sample: dbOrgs[0] || null\n      },\n      ollama_payload: {\n        model: model,\n        prompt: `${systemPrompt}\\n\\n${userPrompt}`,\n        stream: false,\n        format: 'json',\n        options: {\n          temperature: 0.1,\n          num_ctx: 8192\n        }\n      }\n    }\n  };\n});"
      },
      "id": "08cc5940-194e-486a-bffe-d4ed6a00e252",
      "name": "Build AI Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [4736, -26144],
      "notes": "สร้าง Prompt โดยใช้ Categories จาก System"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$('Set Configuration').first().json.config.OLLAMA_HOST}}/api/generate",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.ollama_payload }}",
        "options": {
          "timeout": 120000
        }
      },
      "id": "8e757be4-1b86-45f6-8ae4-45d6d573bcdb",
      "name": "Ollama AI Analysis",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [4912, -26144],
      "notes": "เรียก Ollama วิเคราะห์เอกสาร"
    },
    {
      "parameters": {
        "jsCode": "const ollamaItems = $input.all();\nconst originalItems = $('Build AI Prompt').all();\nconst results = [];\n\nconst CATEGORY_TO_TYPE_CODE = {\n  'Correspondence': 'LETTER',\n  'RFA': 'RFA',\n  'Transmittal': 'TRANSMITTAL',\n  'Drawing': 'OTHER',\n  'Report': 'OTHER',\n  'Other': 'OTHER',\n};\n\nfor (let i = 0; i < ollamaItems.length; i++) {\n  const ollamaItem = ollamaItems[i];\n  const originalItem = originalItems[i];\n  if (!originalItem) continue;\n  const baseJson = originalItem.json;\n  const preMapped = baseJson.pre_mapped || {};\n\n  try {\n    let raw = ollamaItem.json.response || '';\n    raw = raw.replace(/\\`{3}json/gi, '').replace(/\\`{3}/g, '').trim();\n    if (!raw) throw new Error('Empty response from AI');\n\n    const result = JSON.parse(raw);\n    const isEmptyResponse = Object.keys(result).length === 0;\n\n    const systemCategories = baseJson.system_categories || [];\n    let finalCategory = result.category;\n    if (!finalCategory || !systemCategories.includes(finalCategory)) {\n      finalCategory = String(baseJson.document_number || '').includes('-RFA-') ? 'RFA' : 'Correspondence';\n    }\n\n    // Use Excel correspondence_type (pre_mapped) first, fallback to AI category map\n    const typeCode = preMapped.type_code || CATEGORY_TO_TYPE_CODE[finalCategory] || 'LETTER';\n    const typeId = preMapped.type_id || preMapped.correspondence_type_id || null;\n\n    results.push({\n      json: {\n        ...baseJson,\n        ai_result: {\n          suggested_category: finalCategory,\n          type_code: typeCode,\n          type_id: typeId,\n          confidence: isEmptyResponse ? 0.5 : (result.confidence || 0.8),\n          project_id: preMapped.project_id || null,\n          discipline_id: result.discipline_id || 64,\n          sender_id: preMapped.sender_id || null,\n          receiver_id: preMapped.receiver_id || null,\n          // Spec uses \"summary\" for body content\n          subject: result.subject || baseJson.subject || '',\n          body: result.summary || result.body || '',\n          issued_date: result.issued_date || baseJson.issued_date || '',\n          received_date: result.received_date || baseJson.received_date || '',\n          summary: result.summary || result.body || '',\n          status: result.status || '',\n          key_points: result.key_points || [],\n          tags: (result.tags || []).map(t => (typeof t === 'string' ? { tag_name: t, description: '' } : { tag_name: t.tag_name || t.name || '', description: t.description || '' })).filter(t => t.tag_name),\n          is_valid: result.is_valid !== false,\n          ai_empty: isEmptyResponse\n        }\n      }\n    });\n  } catch (err) {\n    // Parse error — still carry forward Excel data via pre_mapped\n    results.push({\n      json: {\n        ...baseJson,\n        parse_error: err.message,\n        raw_ai_response: ollamaItem.json.response,\n        ai_result: {\n          suggested_category: 'Correspondence',\n          type_code: preMapped.type_code || 'LETTER',\n          type_id: preMapped.type_id || preMapped.correspondence_type_id || null,\n          confidence: 0.3,\n          project_id: preMapped.project_id || null,\n          discipline_id: 64,\n          sender_id: preMapped.sender_id || null,\n          receiver_id: preMapped.receiver_id || null,\n          subject: baseJson.subject || '',\n          body: '',\n          issued_date: baseJson.issued_date || '',\n          received_date: baseJson.received_date || '',\n          summary: '',\n          status: '',\n          key_points: [],\n          tags: [],\n          is_valid: false,\n          ai_empty: true\n        }\n      }\n    });\n  }\n}\n\nreturn results;"
      },
      "id": "9ff12b75-03c6-43f0-8654-855d5da42e56",
      "name": "Parse & Validate AI Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [5104, -26144],
      "notes": "Parse JSON + Validate Schema + Enum Check"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO migration_fallback_state (batch_id, recent_error_count, is_fallback_active) VALUES ('{{$('Set Configuration').first().json.config.BATCH_ID}}', 1, FALSE) ON DUPLICATE KEY UPDATE recent_error_count = recent_error_count + 1, is_fallback_active = CASE WHEN recent_error_count + 1 >= {{$('Set Configuration').first().json.config.FALLBACK_THRESHOLD}} THEN TRUE ELSE is_fallback_active END, updated_at = NOW()",
        "options": {}
      },
      "id": "eb703a14-2670-4cf4-b7d0-762e148bf4f7",
      "name": "Update Fallback State",
      "type": "n8n-nodes-base.mySql",
      "typeVersion": 2.4,
      "position": [4928, -25952],
      "credentials": {
        "mySql": {
          "id": "CHHfbKhMacNo03V4",
          "name": "MySQL account"
        }
      },
      "notes": "เพิ่ม Error count และตรวจสอบ Fallback threshold"
    },
    {
      "parameters": {
        "jsCode": "const config = $('Set Configuration').first().json.config;\nconst items = $('Parse & Validate AI Response').all();\n\nconst results = [];\n\nfor (const item of items) {\n  const data = item.json;\n  let resultItem = { json: { ...data } };\n  \n  if (data.parse_error || !data.ai_result) {\n    resultItem.json.route_index = 3;\n    results.push(resultItem);\n    continue;\n  }\n  \n  const ai = data.ai_result;\n  \n  if (ai.confidence >= config.CONFIDENCE_HIGH) {\n    resultItem.json.route_index = 0;\n    resultItem.json.staging_status = 'PENDING';\n    resultItem.json.staging_remarks = 'Ready for auto-ingest (High Confidence)';\n  } else if (ai.confidence >= config.CONFIDENCE_LOW) {\n    resultItem.json.route_index = 1;\n    resultItem.json.staging_status = 'PENDING';\n    resultItem.json.staging_remarks = 'Flagged for human review (Medium Confidence)';\n  } else {\n    resultItem.json.route_index = 2;\n    resultItem.json.staging_status = 'REJECTED';\n    resultItem.json.staging_remarks = ai.is_valid === false ? 'AI marked invalid' : `Rejected for human review (Low Confidence: ${ai.confidence.toFixed(2)})`;\n  }\n  results.push(resultItem);\n}\n\nreturn results;"
      },
      "id": "a8b9d938-39a0-49c2-98ca-8defcec0d5ab",
      "name": "Confidence Router",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [5312, -26304],
      "notes": "แยกตาม Confidence: Auto(≥0.85) / Review(≥0.60) / Reject(<0.60)"
    },
    {
      "parameters": {
        "jsCode": "const fs = require('fs');\nconst item = $input.first();\nconst config = $('Set Configuration').first().json.config;\n\nconst csvPath = `${config.LOG_PATH}/reject_log.csv`;\nconst header = 'timestamp,document_number,title,reject_reason,ai_confidence,key_points\\n';\nconst esc = (s) => `\"${String(s || '').replace(/\"/g, '\"\"')}\"`;\n\nif (!fs.existsSync(config.LOG_PATH)) {\n  fs.mkdirSync(config.LOG_PATH, { recursive: true });\n}\n\nif (!fs.existsSync(csvPath)) {\n  fs.writeFileSync(csvPath, header, 'utf8');\n}\n\nconst line = [\n  new Date().toISOString(),\n  esc(item.json.document_number),\n  esc(item.json.title),\n  esc(item.json.staging_remarks),\n  item.json.ai_result?.confidence ?? 'N/A',\n  esc(JSON.stringify(item.json.ai_result?.key_points || []))\n].join(',') + '\\n';\n\nfs.appendFileSync(csvPath, line, 'utf8');\n\nreturn [$input.first()];"
      },
      "id": "f8f5484e-5f2f-4124-a3f3-f405e1fc9972",
      "name": "Log Reject to CSV",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [5680, -25920],
      "notes": "บันทึกรายการที่ถูกปฏิเสธลง CSV"
    },
    {
      "parameters": {
        "jsCode": "const fs = require('fs');\nconst items = $input.all();\nconst config = $('Set Configuration').first().json.config;\n\nconst csvPath = `${config.LOG_PATH}/error_log.csv`;\nconst header = 'timestamp,document_number,error_type,error_message,raw_ai_response\\n';\nconst esc = (s) => `\"${String(s || '').replace(/\"/g, '\"\"')}\"`;\n\nif (!fs.existsSync(config.LOG_PATH)) {\n  fs.mkdirSync(config.LOG_PATH, { recursive: true });\n}\n\nif (!fs.existsSync(csvPath)) {\n  fs.writeFileSync(csvPath, header, 'utf8');\n}\n\nfor (const item of items) {\n  const line = [\n    new Date().toISOString(),\n    esc(item.json.document_number),\n    esc(item.json.error_type || 'UNKNOWN'),\n    esc(item.json.error || item.json.parse_error),\n    esc(item.json.raw_ai_response || '')\n  ].join(',') + '\\n';\n  \n  fs.appendFileSync(csvPath, line, 'utf8');\n}\n\nreturn items;"
      },
      "id": "2625fd9a-6623-45f4-9a49-bba0c911bb0f",
      "name": "Log Error to CSV",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [5488, -25856],
      "notes": "บันทึก Error ลง CSV (จาก File Validator)"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$('Set Configuration').first().json.config.BACKEND_URL}}/api/migration/errors",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "={{$('Set Configuration').first().json.config.MIGRATION_TOKEN}}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ batch_id: $('Set Configuration').first().json.config.BATCH_ID, document_number: $json.document_number || '', error_type: $json.error_type || 'UNKNOWN', error_message: $json.error || $json.parse_error || '', raw_ai_response: $json.raw_ai_response || '' }) }}",
        "options": {
          "timeout": 10000
        }
      },
      "id": "b61ff3b1-f11c-4308-a81e-b12d8540d058",
      "name": "Log Error to DB",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [5872, -25856],
      "onError": "continueErrorOutput",
      "notes": "บันทึก Error ผ่าน Backend API (ป้องกัน SQL Injection)"
    },
    {
      "parameters": {
        "amount": "={{$('Set Configuration').first().json.config.DELAY_MS / 1000}}",
        "unit": "seconds"
      },
      "id": "86de1e7b-9142-41ec-9e5e-817677273603",
      "name": "Delay",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1,
      "position": [6096, -25920],
      "webhookId": "38e97a99-4dcc-4b63-977a-a02945a1c369",
      "notes": "หน่วงเวลาระหว่าง Batches"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route_index }}",
                    "rightValue": 0,
                    "operator": {
                      "type": "number",
                      "operation": "equals",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Staging (High)"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route_index }}",
                    "rightValue": 1,
                    "operator": {
                      "type": "number",
                      "operation": "equals",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Staging (Review)"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route_index }}",
                    "rightValue": 2,
                    "operator": {
                      "type": "number",
                      "operation": "equals",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Reject"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route_index }}",
                    "rightValue": 3,
                    "operator": {
                      "type": "number",
                      "operation": "equals",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Error Log"
            }
          ]
        },
        "options": {}
      },
      "id": "6d178e98-238c-419d-bc17-f464a4ea98b1",
      "name": "Route by Confidence",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [5328, -26144]
    },
    {
      "parameters": {
        "fileSelector": "={{ $json.file_path }}",
        "options": {}
      },
      "id": "7ac25b43-80c6-457d-8c40-6fa32de32fae",
      "name": "Read PDF File",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [4560, -26304],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$('Set Configuration').first().json.config.BACKEND_URL}}/api/files/upload",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "={{$('Set Configuration').first().json.config.MIGRATION_TOKEN}}"
            }
          ]
        },
        "sendBody": true,
        "contentType": "multipart-form-data",
        "bodyParameters": {
          "parameters": [
            {
              "parameterType": "formBinaryData",
              "name": "file",
              "inputDataFieldName": "data"
            }
          ]
        },
        "options": {
          "timeout": 60000
        }
      },
      "id": "6a0329ce-99d8-45ee-b997-22f7f6420310",
      "name": "Upload to Backend",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [5712, -26336],
      "notes": "Upload PDF to Backend Temp Storage"
    },
    {
      "parameters": {
        "jsCode": "const item = $input.first();\nconst binaryData = $('Read PDF File').first().binary.data;\n\n// Fix: Override fileName to use NFC-normalized name from Excel\n// Prevents encoding corruption (Thai chars appearing as Chinese)\nconst fileName = String(item.json.file_name || '').normalize('NFC');\nconst safeName = fileName.toLowerCase().endsWith('.pdf') ? fileName : fileName + '.pdf';\n\nreturn {\n  json: { ...item.json },\n  binary: {\n    data: {\n      ...binaryData,\n      fileName: safeName,\n      mimeType: 'application/pdf'\n    }\n  }\n};"
      },
      "id": "fd2c0b17-ba48-488c-89ce-1d95e37e1f75",
      "name": "Restore Binary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [5536, -26336],
      "notes": "Re-attach PDF binary จาก Read PDF File เพื่อส่ง Upload (หลัง AI ตรวจแล้ว)"
    },
    {
      "parameters": {
        "method": "PUT",
        "url": "http://tika:9998/tika",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "maxPages",
              "value": "2"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "text/plain"
            },
            {
              "name": "X-Tika-OCRLanguage",
              "value": "tha+eng"
            },
            {
              "name": "X-Tika-PDFOcrStrategy",
              "value": "ocr_only"
            }
          ]
        },
        "sendBody": true,
        "contentType": "binaryData",
        "inputDataFieldName": "data",
        "options": {
          "timeout": 600000
        }
      },
      "id": "a9ccd66d-ece4-48cb-8fac-6daa9257904a",
      "name": "Extract PDF Text",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [4848, -26320],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT 'projects' as type, id, project_code as text1, project_name as text2 FROM projects\nUNION ALL\nSELECT 'disciplines' as type, id, code_name_th as text1, code_name_en as text2 FROM disciplines\nUNION ALL\nSELECT 'organizations' as type, id, organization_name as text1, organization_code as text2 FROM organizations\nUNION ALL\nSELECT 'tags' as type, id, tag_name as text1, description as text2 FROM tags\nUNION ALL\nSELECT 'correspondence_types' as type, id, type_code as text1, type_name as text2 FROM correspondence_types",
        "options": {}
      },
      "id": "3b941922-b7a0-4ce7-99c7-c16b72ba3b04",
      "name": "Fetch DB Context",
      "type": "n8n-nodes-base.mySql",
      "typeVersion": 2.4,
      "position": [4576, -26144],
      "alwaysOutputData": true,
      "credentials": {
        "mySql": {
          "id": "CHHfbKhMacNo03V4",
          "name": "MySQL account"
        }
      },
      "notes": "ดึงข้อมูลจาก Database ส่งให้ AI"
    },
    {
      "parameters": {
        "jsCode": "const uploadResults = $input.all();\nconst config = $('Set Configuration').first().json.config;\n// Original data is in Restore Binary (before Upload replaced json with HTTP response)\nconst originalItems = $('Restore Binary').all();\n\nreturn uploadResults.map((uploadWrapper, i) => {\n  const uploadResult = uploadWrapper.json;\n  const item = originalItems[i]?.json || {};\n  const ai = item.ai_result || {};\n\n  return {\n    json: {\n      ...item,\n      enqueue_payload: {\n        document_number: String(item.document_number || ''),\n        subject: String(ai.subject || item.subject || ''),\n        original_subject: String(item.subject || ''),\n        category: ai.suggested_category || 'Correspondence',\n        type_code: ai.type_code || 'LETTER',\n        type_id: ai.type_id || null,\n        body: String(ai.body || ai.summary || ''),\n        ai_summary: ai.summary || ai.body || '',\n        project_id: Number(ai.project_id || config.PROJECT_ID),\n        sender_org_id: ai.sender_id || null,\n        receiver_org_id: ai.receiver_id || null,\n        issued_date: ai.issued_date || item.issued_date || '',\n        received_date: ai.received_date || item.received_date || '',\n        remarks: item.remarks ? item.remarks + (item.staging_remarks ? ' [System: ' + item.staging_remarks + ']' : '') : (item.staging_remarks || ''),\n        extracted_tags: ai.tags || [],\n        details: { tags: ai.tags || [] },\n        temp_attachment_id: uploadResult.id || uploadResult.tempId || null,\n        is_valid: ai.is_valid !== false,\n        confidence: ai.confidence || 0.0,\n        ai_issues: ai.key_points || [],\n        ai_empty: ai.ai_empty || false\n      }\n    }\n  };\n});"
      },
      "id": "51613de7-db28-41bd-bdb3-f7ba12b9186e",
      "name": "Build Enqueue Payload",
      "typeVersion": 2,
      "type": "n8n-nodes-base.code",
      "position": [5888, -26336],
      "notes": "สร้าง payload สำหรับ Enqueue Migration"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{$('Set Configuration').first().json.config.BACKEND_URL}}/api/migration/queue",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "={{$('Set Configuration').first().json.config.MIGRATION_TOKEN}}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.enqueue_payload }}",
        "options": {
          "timeout": 30000
        }
      },
      "id": "aecb004d-846b-4aea-8174-7b9c7aa5c39f",
      "name": "Enqueue to Review Queue",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [5600, -26144],
      "notes": "ส่งข้อมูลเข้า Staging Queue"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO migration_progress (batch_id, last_processed_index, status) VALUES ('{{$('Set Configuration').first().json.config.BATCH_ID}}', {{$json.original_index || 0}}, 'RUNNING') ON DUPLICATE KEY UPDATE last_processed_index = {{$json.original_index || 0}}, updated_at = NOW()",
        "options": {}
      },
      "id": "748b1ee9-b3d8-4900-92a1-4444ded15c61",
      "name": "Save Checkpoint",
      "type": "n8n-nodes-base.mySql",
      "typeVersion": 2.4,
      "position": [5792, -26144],
      "credentials": {
        "mySql": {
          "id": "CHHfbKhMacNo03V4",
          "name": "MySQL account"
        }
      },
      "notes": "บันทึกความคืบหน้าลง Database"
    },
    {
      "parameters": {
        "content": "## Initialization & Preflight",
        "height": 368,
        "width": 544,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [3936, -26352],
      "typeVersion": 1,
      "id": "9eb3cfbd-2fe4-4237-a7ee-9387aa909efb",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "url": "={{$('Set Configuration').first().json.config.BACKEND_URL}}/health",
        "options": {
          "timeout": 5000
        }
      },
      "id": "6d29f005-ae65-42e8-8d3d-55992927a13a",
      "name": "Check Backend Health",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [4288, -26304],
      "onError": "continueErrorOutput",
      "notes": "ตรวจสอบ Backend พร้อมใช้งาน"
    },
    {
      "parameters": {
        "content": "## Data Ingestion & Batching",
        "height": 256,
        "width": 928,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [3936, -25968],
      "typeVersion": 1,
      "id": "f2daf117-9cf2-477e-9c69-56a92503c783",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "content": "## Text Extraction & AI Analysis",
        "height": 368,
        "width": 752,
        "color": 6
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [4496, -26352],
      "typeVersion": 1,
      "id": "0b628ba8-de1a-40c6-8722-fc0e2411d666",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "## Error Logging",
        "height": 224,
        "width": 800,
        "color": 3
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [5264, -25936],
      "typeVersion": 1,
      "id": "fee4de9d-be2f-4e92-aea6-2a11ee89af8c",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "content": "## Routing & Ingestion",
        "height": 416,
        "width": 784,
        "color": 2
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [5264, -26352],
      "typeVersion": 1,
      "id": "23619681-d936-4608-92ba-bfb10c062789",
      "name": "Sticky Note4"
    }
  ],
  "pinData": {},
  "connections": {
    "Form Trigger": {
      "main": [
        [
          {
            "node": "Set Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Configuration": {
      "main": [
        [
          {
            "node": "Check Backend Health",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Categories": {
      "main": [
        [
          {
            "node": "Fetch Tags",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Tags": {
      "main": [
        [
          {
            "node": "File Mount Check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "File Mount Check": {
      "main": [
        [
          {
            "node": "Read Excel Binary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Excel Binary": {
      "main": [
        [
          {
            "node": "Read Excel",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Excel": {
      "main": [
        [
          {
            "node": "Read Checkpoint",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Checkpoint": {
      "main": [
        [
          {
            "node": "Process Batch + Encoding",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Check Backend Health",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process Batch + Encoding": {
      "main": [
        [
          {
            "node": "File Validator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "File Validator": {
      "main": [
        [
          {
            "node": "Read PDF File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read PDF File": {
      "main": [
        [
          {
            "node": "Extract PDF Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload to Backend": {
      "main": [
        [
          {
            "node": "Build Enqueue Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Restore Binary": {
      "main": [
        [
          {
            "node": "Upload to Backend",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract PDF Text": {
      "main": [
        [
          {
            "node": "Check Fallback State",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Fallback State": {
      "main": [
        [
          {
            "node": "Fetch DB Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch DB Context": {
      "main": [
        [
          {
            "node": "Build AI Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build AI Prompt": {
      "main": [
        [
          {
            "node": "Ollama AI Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ollama AI Analysis": {
      "main": [
        [
          {
            "node": "Parse & Validate AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse & Validate AI Response": {
      "main": [
        [
          {
            "node": "Confidence Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Confidence Router": {
      "main": [
        [
          {
            "node": "Route by Confidence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route by Confidence": {
      "main": [
        [
          {
            "node": "Restore Binary",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Restore Binary",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Reject to CSV",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Error to CSV",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Enqueue Payload": {
      "main": [
        [
          {
            "node": "Enqueue to Review Queue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enqueue to Review Queue": {
      "main": [
        [
          {
            "node": "Save Checkpoint",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Checkpoint": {
      "main": [
        [
          {
            "node": "Delay",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Reject to CSV": {
      "main": [
        [
          {
            "node": "Delay",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Error to CSV": {
      "main": [
        [
          {
            "node": "Log Error to DB",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Error to DB": {
      "main": [
        [
          {
            "node": "Delay",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Delay": {
      "main": [
        [
          {
            "node": "Read Checkpoint",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Backend Health": {
      "main": [
        [
          {
            "node": "Fetch Categories",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false
  },
  "versionId": "3fea0965-f77e-4bba-a4be-00ed7c232899",
  "meta": {
    "instanceId": "9e70e47c1eaf3bac72f497ddfbde0983f840f7d0f059537f7e37dd70de18ecb7"
  },
  "id": "8Z6xwWVQ3TUflnSY",
  "tags": []
}
