Files
pharmacy_dashboard/automation.json
T
2026-11-24 12:07:35 +05:30

3997 lines
274 KiB
JSON

{
"updatedAt": "2026-11-18T10:29:49.476Z",
"createdAt": "2026-09-15T07:46:14.929Z",
"id": "EyAw3kSLbeIEnpyf",
"name": "Invoice Automation-DMH Hospital Final Outlook",
"description": null,
"active": true,
"isArchived": false,
"nodes": [
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "=1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "id"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413"
},
"columns": {
"mappingMode": "defineBelow",
"value": {
"Date": "={{ $json.date }}",
"Time": "={{ $json.time }}",
"Attachment Name": "={{ $json.attachment_name }}",
"Status": "={{ $json.status }}",
"GRN Message ": "={{ $json.grn_message }}",
"Complete Error / Null Values": "={{ $json.complete_error }}"
},
"matchingColumns": [],
"schema": [
{
"id": "Sr No.",
"displayName": "Sr No.",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Date",
"displayName": "Date",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Time",
"displayName": "Time",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Attachment Name",
"displayName": "Attachment Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Customer Name",
"displayName": "Customer Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice Amount (₹)",
"displayName": "Invoice Amount (₹)",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice ID",
"displayName": "Invoice ID",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller Name",
"displayName": "Seller Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Status",
"displayName": "Status",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "GRN Message ",
"displayName": "GRN Message ",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller GSTIN",
"displayName": "Seller GSTIN",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Free Goods",
"displayName": "Free Goods",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Complete Error / Null Values",
"displayName": "Complete Error / Null Values",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
}
],
"attemptToConvertTypes": false,
"convertFieldsToString": false
},
"options": {}
},
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 4.7,
"position": [
-1792,
384
],
"id": "1550194a-e54a-4b53-8b77-aa2f3a946d74",
"name": "Append row in sheet1",
"credentials": {
"googleSheetsOAuth2Api": {
"id": "OGnPiaQp3eu9tWvW",
"name": "Google Sheets account"
}
}
},
{
"parameters": {
"pollTimes": {
"item": [
{
"mode": "everyMinute"
}
]
},
"filters": {
"foldersToInclude": [
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==",
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodQAAAA==",
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA=="
]
},
"options": {
"downloadAttachments": true
}
},
"type": "n8n-nodes-base.microsoftOutlookTrigger",
"typeVersion": 1,
"position": [
-4832,
1056
],
"id": "be7ad802-919e-41d8-bd76-d0291e5640dd",
"name": "Watch New_Invoice Label1",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
}
},
{
"parameters": {
"promptType": "define",
"text": "=Email Subject:\n{{$json.subject}}\n\nEmail Body:\n{{$json.bodyPreview || $json.body.content}}\n\nSender Email:\n{{ $json.from }}\n\nAttachment File Name:\n{{$binary.attachment_0.fileName}}\n\nAttachment MIME Type:\n{{$binary.attachment_0.mimeType}}\n",
"needsFallback": true,
"options": {
"systemMessage": "You are an invoice recognition agent operating inside an automated workflow.\n\nYou will receive:\nEmail subject\nEmail body content (plain text or HTML converted to text)\nSender email address and name\nAttachment file name\nAttachment MIME type\n\nYour task:\nDetermine whether the email and its attachment should be treated as a BUSINESS INVOICE.\n\nClassification rules:\nClassify the email as an invoice if ANY billing, payment, receipt, tax, or business transaction context is present.\nThe word \"invoice\" may or may not appear explicitly.\nAttachment file names containing company or brand names (for example: BISLERI.pdf, TATA.pdf, AMAZON.pdf, A+V+TRADING.pdf) may represent invoices.\nIf the attachment MIME type is \"application/pdf\" and the email context is business-related, classify it as an invoice.\nIf there is reasonable doubt, classify the email as an invoice.\n\nHard constraints:\nDo NOT read or analyze PDF binary content.\nDo NOT perform OCR.\nDo NOT extract invoice numbers, dates, or amounts.\nNEVER return null or undefined.\nALWAYS return all fields.\nNEVER include markdown formatting.\nNEVER wrap the output in ```json or ``` blocks.\nNEVER include explanations, headings, or extra text.\n\nOutput requirements:\nReturn ONLY a single valid JSON object.\nThe response must start with { and end with }.\nThe output must be directly parseable using JSON.parse().\n\nReturn the response in this EXACT format:\n\n{\n \"is_invoice\": true or false,\n \"confidence\": \"high\" or \"medium\" or \"low\",\n \"reason\": \"\"\n}"
}
},
"type": "@n8n/n8n-nodes-langchain.agent",
"typeVersion": 2.2,
"position": [
-3488,
960
],
"id": "f43530ad-adfa-41ba-b3e2-59c500b8931e",
"name": "AI: Classify Invoice1",
"alwaysOutputData": false,
"notesInFlow": false,
"retryOnFail": true,
"onError": "continueRegularOutput"
},
{
"parameters": {
"method": "POST",
"url": "https://aiinfinite.in/process-invoice",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523"
}
]
},
"sendBody": true,
"contentType": "multipart-form-data",
"bodyParameters": {
"parameters": [
{
"parameterType": "formBinaryData",
"name": "file",
"inputDataFieldName": "=file"
}
]
},
"options": {}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-1568,
192
],
"id": "bc668542-9d9c-4096-9750-777b7012a29b",
"name": "OCR: Extract Invoice Data2",
"alwaysOutputData": false,
"retryOnFail": true,
"waitBetweenTries": 5000,
"maxTries": 3,
"onError": "continueRegularOutput"
},
{
"parameters": {
"mode": "combine",
"combineBy": "combineByPosition",
"options": {}
},
"type": "n8n-nodes-base.merge",
"typeVersion": 3.2,
"position": [
-3136,
912
],
"id": "c3974a60-9c2b-476b-9283-7eb744b4501e",
"name": "Merge: Email + AI Classification1"
},
{
"parameters": {
"operation": "getAll",
"limit": 3,
"filtersUI": {
"values": {
"filters": {
"foldersToInclude": [
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==",
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA=="
]
}
}
},
"options": {
"downloadAttachments": true
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-4608,
1056
],
"id": "939a1916-4d96-4550-9482-fd51209d060a",
"name": "Fetch Emails from New_Invoice (max 3)1",
"executeOnce": true,
"webhookId": "977ad40e-7150-4f6a-a351-e29c08eb4f97",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
}
},
{
"parameters": {
"options": {}
},
"type": "n8n-nodes-base.splitInBatches",
"typeVersion": 3,
"position": [
-4384,
1056
],
"id": "d71ef907-462d-4c40-bb01-2476d9cb7bf3",
"name": "Loop: Each Email2"
},
{
"parameters": {},
"type": "n8n-nodes-base.noOp",
"name": "End: No More Emails1",
"typeVersion": 1,
"position": [
-4160,
1104
],
"id": "90ad177b-23a6-41d0-86fe-fd3f3725e6d8"
},
{
"parameters": {
"operation": "update",
"messageId": {
"__rl": true,
"value": "={{ $json.id }}",
"mode": "id"
},
"updateFields": {
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==",
"mode": "list",
"cachedResultName": "Processing",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D"
}
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-4160,
912
],
"id": "aaab2e62-0622-4bbd-b3d1-648fcb06b290",
"name": "Label: Add Processing2",
"webhookId": "5d0319e0-f28f-4f7a-a562-038cd721cf91",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": {
"__rl": true,
"value": "={{ $('Fetch Emails from New_Invoice (max 3)1').item.json.id }}",
"mode": "id"
},
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==",
"mode": "list",
"cachedResultName": "Processing",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-3936,
912
],
"id": "584c67c7-ff4d-4b72-8a91-a94fe1c6ad4b",
"name": "Label: Remove New_Invoice1",
"webhookId": "e16ef4d9-e84c-4127-aafa-6f61cbdb9ba0",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"disabled": true
},
{
"parameters": {
"operation": "get",
"messageId": {
"__rl": true,
"mode": "id",
"value": "={{ $json.id }}"
},
"options": {
"downloadAttachments": true
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-3712,
912
],
"id": "8f05ea79-5bef-42c3-aef3-fc99f97397e8",
"name": "Fetch Full Email + Attachments2",
"webhookId": "74750b5a-de62-4326-888d-2d36ef832e5f",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
}
},
{
"parameters": {
"jsCode": "// ═══════════════════════════════════════════════════════════════════\n// MASTER PARSE AI OUTPUT — Production Grade — Never-Fail Strategy\n//\n// Handles ALL known Gemini / Groq / LangChain output formats:\n// 1. Standard string in output field\n// 2. output field is already a parsed Object\n// 3. output field is an Array (unwraps first element)\n// 4. Double-nested output.output\n// 5. JSON wrapped in ```json ... ``` markdown fences\n// 6. JSON buried inside explanatory text (extracts all {} blocks)\n// 7. Malformed / unclosed JSON (regex fallback)\n// 8. is_invoice as boolean true/false\n// 9. is_invoice as string \"true\"/\"false\"/\"True\"/\"yes\"/\"1\"\n// 10. is_invoice as number 1/0\n// 11. Alternative field names: isInvoice, invoice, type, classification\n// 12. Confidence values: \"HIGH\", \"high\", \"Medium\", \"certain\", \"low\"\n// 13. text / content / message / result field instead of output\n// 14. LangChain wrapped format (lc/kwargs/content)\n// 15. Agent-level errors (quota, API down, 429, etc.)\n// 16. BOM characters and non-printable chars in output\n// 17. Partial / truncated JSON (regex field extraction)\n//\n// CLASSIFICATION OUTPUT (Switch node reads this):\n// \"invoice\" → process as invoice\n// \"not_invoice\" → skip, label as not-invoice\n// \"error\" → log error, do not process\n// ═══════════════════════════════════════════════════════════════════\n\nreturn items.map(item => {\n\n let classification = 'error';\n let confidence = 'low';\n let ai_reason = '';\n let error_detail = '';\n\n try {\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 1 — Agent-level error check\n // Catches: Gemini quota, API key invalid, network timeout, 429\n // ══════════════════════════════════════════════════════════════\n if (item.json.error) {\n const errVal = item.json.error;\n const errStr = typeof errVal === 'object'\n ? (errVal.message || JSON.stringify(errVal))\n : String(errVal);\n error_detail = 'AGENT_ERROR: ' + errStr.slice(0, 300);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 2 — Find raw content from all possible field paths\n // Try: output → text → content → message → result → response\n // ══════════════════════════════════════════════════════════════\n const FIELD_PATHS = ['output', 'text', 'content', 'message', 'result', 'response'];\n let raw = null;\n let parsed = null; // set if we already have a parsed object\n\n for (const path of FIELD_PATHS) {\n const val = item.json[path];\n if (val === null || val === undefined || val === '') continue;\n raw = val;\n break;\n }\n\n if (raw === null) {\n // Last resort: check if item.json itself IS the parsed object\n if (item.json.is_invoice !== undefined) {\n parsed = item.json;\n raw = null;\n } else {\n error_detail = 'NO_OUTPUT_FIELD: checked output/text/content/message/result';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 3 — Unwrap arrays and nested objects\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n // Unwrap Array → take first element\n if (Array.isArray(raw)) {\n raw = raw[0];\n }\n\n // If raw is an Object (n8n pre-parsed the JSON)\n if (raw !== null && typeof raw === 'object') {\n // Check for LangChain format: {lc: 1, kwargs: {content: \"...\"}}\n if (raw.kwargs && raw.kwargs.content !== undefined) {\n raw = raw.kwargs.content;\n\n // Check for double-nested output field\n } else if (raw.output !== undefined) {\n raw = raw.output;\n // raw might still be an object — check again\n if (raw !== null && typeof raw === 'object') {\n if (Array.isArray(raw)) raw = raw[0];\n if (raw !== null && typeof raw === 'object') {\n parsed = raw;\n raw = null;\n }\n }\n\n } else {\n // Object IS the parsed result\n parsed = raw;\n raw = null;\n }\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 4 — Parse JSON from string (multi-attempt strategy)\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n const rawStr = String(raw);\n\n if (rawStr.trim() === '') {\n error_detail = 'EMPTY_AI_RESPONSE';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ── Clean the string ──────────────────────────────────────\n let cleaned = rawStr\n .replace(/\\uFEFF/g, '') // BOM character\n .replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/g, '') // control chars (keep \\n \\r \\t)\n .replace(/```json\\s*/gi, '') // opening ```json fence\n .replace(/```\\s*/g, '') // closing ``` fence\n .trim();\n\n // ── Attempt 1: Direct JSON.parse of entire cleaned string ──\n parsed = tryParse(cleaned);\n\n // ── Attempt 2: Extract first complete { ... } block ───────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'first');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 3: Extract the JSON block CONTAINING is_invoice ─\n if (!parsed) {\n const block = extractJsonBlockWithKey(cleaned, 'is_invoice');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 4: Extract LAST { ... } block ─────────────────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'last');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 5: Try ALL { ... } blocks ─────────────────────\n if (!parsed) {\n const blocks = extractAllJsonBlocks(cleaned);\n for (const block of blocks) {\n const p = tryParse(block);\n if (p && (p.is_invoice !== undefined || p.isInvoice !== undefined)) {\n parsed = p;\n break;\n }\n }\n if (!parsed && blocks.length > 0) {\n parsed = tryParse(blocks[0]); // take first even if no is_invoice key\n }\n }\n\n // ── Attempt 6: Regex field extraction (malformed JSON) ────\n if (!parsed) {\n parsed = regexExtract(cleaned);\n }\n\n if (!parsed) {\n error_detail = 'ALL_PARSE_ATTEMPTS_FAILED: ' + cleaned.slice(0, 200);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 5 — Extract is_invoice from parsed object\n // Try all known field name variants\n // ══════════════════════════════════════════════════════════════\n const IS_INVOICE_FIELDS = [\n 'is_invoice', 'isInvoice', 'is_Invoice', 'IS_INVOICE',\n 'invoice', 'is_invoice_document', 'invoiceDetected'\n ];\n\n let rawFlag = undefined;\n let usedField = '';\n\n for (const field of IS_INVOICE_FIELDS) {\n if (parsed[field] !== undefined) {\n rawFlag = parsed[field];\n usedField = field;\n break;\n }\n }\n\n // ── Try classification/type fields (value-based check) ──────\n if (rawFlag === undefined) {\n const typeVal = String(parsed.classification || parsed.type || parsed.category || '').toLowerCase();\n if (typeVal.includes('invoice')) { rawFlag = true; }\n else if (typeVal.includes('not') ||\n typeVal.includes('skip') ||\n typeVal.includes('other')) { rawFlag = false; }\n }\n\n // ── If still not found, scan the raw text for patterns ──────\n if (rawFlag === undefined && raw) {\n const rawLower = String(raw).toLowerCase();\n const m = rawLower.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|1|0)/);\n if (m) {\n rawFlag = (m[1] === 'true' || m[1] === '\"true\"' || m[1] === '1');\n }\n }\n\n if (rawFlag === undefined) {\n error_detail = 'IS_INVOICE_FIELD_NOT_FOUND. Parsed object: ' + JSON.stringify(parsed).slice(0, 200);\n classification = 'error';\n\n } else {\n // ══════════════════════════════════════════════════════════\n // STAGE 6 — Normalize is_invoice to definitive boolean\n // ══════════════════════════════════════════════════════════\n const flag = String(rawFlag).toLowerCase().trim();\n\n if (['true', '1', 'yes', 'y', 'correct', 'affirmative', 'confirmed'].includes(flag)) {\n classification = 'invoice';\n\n } else if (['false', '0', 'no', 'n', 'incorrect', 'negative', 'not'].includes(flag)) {\n classification = 'not_invoice';\n\n } else {\n error_detail = 'UNEXPECTED_IS_INVOICE_VALUE: \"' + String(rawFlag) + '\"';\n classification = 'error';\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 7 — Extract confidence and reason\n // ══════════════════════════════════════════════════════════════\n if (parsed) {\n // Confidence: normalize to \"high\" | \"medium\" | \"low\"\n const rawConf = String(parsed.confidence || parsed.certainty || parsed.score || 'low').toLowerCase().trim();\n if (['high', 'very_high', 'certain', 'definite', 'strong'].some(v => rawConf.includes(v))) {\n confidence = 'high';\n } else if (['medium', 'moderate', 'mid', 'possible', 'likely'].some(v => rawConf.includes(v))) {\n confidence = 'medium';\n } else {\n confidence = 'low';\n }\n\n // Reason: try multiple field names\n ai_reason = String(\n parsed.reason || parsed.explanation || parsed.rationale ||\n parsed.description || parsed.detail || ''\n ).slice(0, 500);\n }\n\n } catch (e) {\n error_detail = error_detail || ('UNCAUGHT_EXCEPTION: ' + e.message);\n classification = 'error';\n }\n\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n\n});\n\n// ══════════════════════════════════════════════════════════════════\n// HELPER FUNCTIONS\n// ══════════════════════════════════════════════════════════════════\n\nfunction buildOutput(item, classification, confidence, ai_reason, error_detail) {\n return {\n json: {\n ...item.json,\n classification,\n confidence,\n ai_reason,\n error_detail\n },\n binary: item.binary\n };\n}\n\nfunction tryParse(str) {\n try {\n if (!str || str.trim() === '') return null;\n const result = JSON.parse(str.trim());\n // Must be an object, not array/primitive\n if (result && typeof result === 'object' && !Array.isArray(result)) return result;\n if (Array.isArray(result) && result.length > 0 && typeof result[0] === 'object') return result[0];\n return null;\n } catch(e) {\n return null;\n }\n}\n\nfunction extractJsonBlock(str, which) {\n // Find matching { } block accounting for nesting\n const results = extractAllJsonBlocks(str);\n if (results.length === 0) return null;\n return which === 'last' ? results[results.length - 1] : results[0];\n}\n\nfunction extractAllJsonBlocks(str) {\n const blocks = [];\n let depth = 0, start = -1;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '{') {\n if (depth === 0) start = i;\n depth++;\n } else if (str[i] === '}') {\n depth--;\n if (depth === 0 && start !== -1) {\n blocks.push(str.slice(start, i + 1));\n start = -1;\n }\n }\n }\n return blocks;\n}\n\nfunction extractJsonBlockWithKey(str, key) {\n const blocks = extractAllJsonBlocks(str);\n for (const block of blocks) {\n if (block.includes('\"' + key + '\"') || block.includes(\"'\" + key + \"'\")) {\n return block;\n }\n }\n return null;\n}\n\nfunction regexExtract(str) {\n // Last resort: use regex to pull specific fields directly from string\n // even if the JSON is malformed or truncated\n try {\n const result = {};\n let found = false;\n\n // Extract is_invoice\n const mInv = str.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|\"yes\"|\"no\"|1|0)/i);\n if (mInv) {\n const v = mInv[1].replace(/\"/g, '').toLowerCase();\n result.is_invoice = ['true', 'yes', '1'].includes(v);\n found = true;\n }\n\n // Extract confidence\n const mConf = str.match(/\"confidence\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mConf) result.confidence = mConf[1];\n\n // Extract reason\n const mReason = str.match(/\"reason\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mReason) result.reason = mReason[1];\n\n return found ? result : null;\n } catch(e) {\n return null;\n }\n}\n"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2464,
320
],
"id": "e76f2124-e8b2-4b52-86c5-0ab65b6068cf",
"name": "Parse AI Output2",
"retryOnFail": true,
"executeOnce": false,
"alwaysOutputData": true,
"notesInFlow": true
},
{
"parameters": {
"assignments": {
"assignments": [
{
"id": "00093515-229c-432c-9c8d-a2ef09acf369",
"name": "messageId",
"value": "={{$json.id}}",
"type": "string"
}
]
},
"includeOtherFields": true,
"options": {}
},
"type": "n8n-nodes-base.set",
"typeVersion": 3.4,
"position": [
-3424,
672
],
"id": "a5f2223b-6f10-4437-81dc-9a34d57996d0",
"name": "Set messageId Field1"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA==",
"mode": "list",
"cachedResultName": "Not_invoice",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-2016,
576
],
"id": "0c59ac0e-ca75-45bd-b731-3aae0faed96f",
"name": "Label: Add Not_Invoice2",
"webhookId": "d4398f49-ea88-4a89-8f2d-cffbda551562",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": {
"__rl": true,
"value": "={{ $('Flatten Data for Log2').item.json.messageId }}",
"mode": ""
},
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Sucess",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
0,
0
],
"id": "bf5b1548-e75b-40d4-9b2d-a534708db65e",
"name": "Label: Add Invoice_Done2",
"webhookId": "e3a226f8-3b0f-4e68-a8d9-b881d60341ac",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $('Set messageId Field1').item.json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Failed",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-672,
384
],
"id": "651c1889-e980-4870-a309-35e23ea51aed",
"name": "Label: Add Invoice_failed2",
"webhookId": "8f38dce4-4702-49e4-8a0f-7882a573aacf",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 2
},
"conditions": [
{
"id": "78e67355-b3ff-448c-b597-35b7e0709267",
"leftValue": "={{\n !($json.error && $json.error.includes(\"429\")) &&\n !$json.error &&\n ($json.invoice_number ?? \"\") !== \"\"\n}}",
"rightValue": "",
"operator": {
"type": "boolean",
"operation": "true",
"singleValue": true
}
}
],
"combinator": "and"
},
"options": {}
},
"type": "n8n-nodes-base.if",
"typeVersion": 2.2,
"position": [
-1344,
192
],
"id": "c7004bf2-bb80-4eea-8384-54cbd6baae84",
"name": "OCR Extraction Valid?2"
},
{
"parameters": {
"method": "POST",
"url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "nirajAi26@DMH"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{$json}}",
"options": {}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-400,
96
],
"id": "4372d6a1-b4d9-4a1f-b522-c3399044ce33",
"name": "GRN: Create Record in Hospital2",
"retryOnFail": false,
"onError": "continueRegularOutput"
},
{
"parameters": {
"jsCode": "function cleanNumber(val) {\n if (val === null || val === undefined) return 0;\n\n return Number(\n val\n .toString()\n .replace(/[^\\d.-]/g, \"\") // remove commas, brackets, symbols\n ) || 0;\n}\n\nreturn items.map(item => {\n\n const inv = item.json;\n\n return {\n json: {\n\n // ── HEADER ────────────────────────────────────────────────────────────\n invoice_id: inv.invoice_id ?? \"\",\n invoice_number: inv.invoice_number ?? \"\",\n invoice_date: inv.invoice_date ?? \"\",\n due_date: inv.due_date ?? \"\",\n seller_name: inv.seller_name ?? \"\",\n PO_number: inv.PO_number ?? \"\",\n\n invoice_amount: cleanNumber(inv.invoice_amount),\n currency_code: inv.currency_code ?? \"INR\",\n\n seller_gstin: inv.seller_gstin ?? \"\",\n customer_name: inv.customer_name ?? \"\",\n\n // ⚠️ HARDCODED — OCR frequently misreads or omits the hospital GSTIN.\n // This is always DEENANATH MEDICAL STORES (DMH Hospital Pharmacy).\n // Never trust the OCR value for this field.\n customer_gstin: \"27AAATL1944N1ZA\",\n\n dc_date: inv.DC_date ?? \"\",\n dc_number: inv.DC_number ?? \"\",\n\n round_off: cleanNumber(inv.round_off),\n\n total_gst_rate: cleanNumber(inv.total_gst_rate),\n total_quantity: cleanNumber(inv.total_quantity),\n\n total_cgst_rate: cleanNumber(inv.total_cgst_rate),\n total_cgst_amount: cleanNumber(inv.total_cgst_amount),\n\n total_sgst_rate: cleanNumber(inv.total_sgst_rate),\n total_sgst_amount: cleanNumber(inv.total_sgst_amount),\n\n total_igst_rate: cleanNumber(inv.total_igst_rate),\n total_igst_amount: cleanNumber(inv.total_igst_amount),\n\n total_gst_amount: cleanNumber(inv.total_gst_amount),\n\n // ── ITEMS ─────────────────────────────────────────────────────────────\n items: (inv.items ?? []).map(i => ({\n\n item_code: i.item_code ?? \"\",\n Batch: i.Batch ?? \"\",\n\n quantity: cleanNumber(i.quantity),\n free_item_yn: cleanNumber(i.free_item_yn),\n\n unit_price: cleanNumber(i.unit_price),\n total_price: cleanNumber(i.total_price),\n\n Discount: cleanNumber(i.Discount),\n MRP: cleanNumber(i.MRP),\n\n description: i.description ?? \"\",\n Pack: i.Pack ?? \"\",\n hsn_sac: i.hsn_sac ?? \"\",\n expiry_date: i.expiry_date ?? \"\",\n\n cgst_rate: cleanNumber(i.cgst_rate),\n cgst_amount: cleanNumber(i.cgst_amount),\n\n sgst_rate: cleanNumber(i.sgst_rate),\n sgst_amount: cleanNumber(i.sgst_amount),\n\n igst_rate: cleanNumber(i.igst_rate),\n igst_amount: cleanNumber(i.igst_amount),\n\n GST_AMT: cleanNumber(i.GST_AMT),\n\n // Added missing fields\n taxable_value: cleanNumber(i.taxable_value),\n \"Gst%\": cleanNumber(i[\"Gst%\"]),\n Value: cleanNumber(i.Value),\n reference_number: i.reference_number ?? \"\"\n\n }))\n\n }\n };\n});"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-1480,
96
],
"id": "6f82a7b4-9dbf-4e9c-a6c4-6a4a52efc6e3",
"name": "Normalize Invoice Fields2"
},
{
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 2
},
"conditions": [
{
"id": "b97ce590-39e2-4792-b38e-972bfd18e0fd",
"leftValue": "={{ $('Flatten Data for Log2').item.json.grn_success }}",
"rightValue": "",
"operator": {
"type": "boolean",
"operation": "true",
"singleValue": true
}
}
],
"combinator": "and"
},
"options": {}
},
"type": "n8n-nodes-base.if",
"typeVersion": 2.2,
"position": [
-224,
96
],
"id": "477bad63-5dad-4f11-bfdb-8f21c9cb801e",
"name": "GRN Created Successfully?2"
},
{
"parameters": {
"jsCode": "const newItems = [];\n\nfor (const item of items) {\n\n const binaries = item.binary || {};\n const keys = Object.keys(binaries);\n\n if (keys.length > 0) {\n\n for (const key of keys) {\n\n // ── GET filename before binary is consumed ──────────────\n const attachment_name = binaries[key].fileName || '';\n\n newItems.push({\n json: {\n ...item.json,\n attachment_name: attachment_name // ← ONLY NEW LINE\n },\n binary: {\n file: binaries[key]\n }\n });\n }\n\n } else {\n\n let parsedOutput = {};\n try {\n parsedOutput = JSON.parse(item.json.output || '{}');\n } catch (e) {\n parsedOutput = {};\n }\n\n newItems.push({\n json: {\n ...item.json,\n ...parsedOutput,\n attachment_name: '' // ← ONLY NEW LINE\n }\n });\n }\n}\n\nreturn newItems;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2912,
912
],
"id": "b019335c-9a06-417b-95bb-862fcfa1a8fc",
"name": "Split: One Item Per Attachment3",
"alwaysOutputData": true,
"retryOnFail": true
},
{
"parameters": {
"options": {}
},
"type": "n8n-nodes-base.splitInBatches",
"typeVersion": 3,
"position": [
-2688,
912
],
"id": "7cb557ad-cb6d-45d4-99e9-8966e310b493",
"name": "Loop: Each Attachment2"
},
{
"parameters": {
"amount": 1
},
"type": "n8n-nodes-base.wait",
"typeVersion": 1.1,
"position": [
-1792,
192
],
"id": "dab6bfb7-215a-4ccd-8964-333200305739",
"name": "Wait 7s Before OCR2",
"webhookId": "66577e6f-2f40-4a0b-a701-b0b535c018e2"
},
{
"parameters": {
"jsCode": "// =======================================================================\n// Flatten Data for Log2 — v5.0\n// Node: Flatten Data for Log2\n//\n// PURPOSE:\n// Parse GRN API responses safely, including unexpected/new error formats.\n//\n// SUPPORTED ERROR MESSAGE LOCATIONS:\n// message\n// error\n// detail\n// reason\n// description\n// statusText\n// error.message\n// error.detail\n// error.description\n// data.message\n// data.error\n// data.detail\n// data[0].message\n// data[0].error\n// data[0].detail\n// data[0] as string\n// JSON-stringified error objects\n//\n// IMPORTANT:\n// Never returns null / undefined / [object Object] as grn_message.\n// =======================================================================\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safe word-boundary HTTP status code check\n// ───────────────────────────────────────────────────────────────────────\n\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(\n String(text || '')\n );\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safely convert any value to useful text\n// ───────────────────────────────────────────────────────────────────────\n\nfunction safeText(value) {\n if (value === null || value === undefined) return '';\n\n if (typeof value === 'string') {\n return value.trim();\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n if (Array.isArray(value)) {\n const parts = value\n .map(v => safeText(v))\n .filter(Boolean);\n\n return parts.join(' | ').trim();\n }\n\n if (typeof value === 'object') {\n // Try common message fields first\n const keys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage'\n ];\n\n for (const key of keys) {\n if (value[key] !== undefined && value[key] !== null) {\n const result = safeText(value[key]);\n if (result) return result;\n }\n }\n\n // Last resort: JSON\n try {\n return JSON.stringify(value);\n } catch (e) {\n return '';\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: recursively extract a meaningful error message\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractErrorMessage(source, depth = 0) {\n\n if (source === null || source === undefined) {\n return '';\n }\n\n // Prevent infinite recursion\n if (depth > 6) {\n return '';\n }\n\n // Direct string\n if (typeof source === 'string') {\n\n const str = source.trim();\n\n if (!str) return '';\n\n // If string itself contains JSON, try parsing it\n if (\n (str.startsWith('{') && str.endsWith('}')) ||\n (str.startsWith('[') && str.endsWith(']'))\n ) {\n try {\n const parsed = JSON.parse(str);\n const nested = extractErrorMessage(parsed, depth + 1);\n\n if (nested) return nested;\n } catch (e) {\n // Not valid JSON — use original string\n }\n }\n\n return str;\n }\n\n // Number / boolean\n if (\n typeof source === 'number' ||\n typeof source === 'boolean'\n ) {\n return String(source);\n }\n\n // Array\n if (Array.isArray(source)) {\n\n // Prefer meaningful string values\n for (const item of source) {\n const result = extractErrorMessage(item, depth + 1);\n\n if (result) {\n return result;\n }\n }\n\n return '';\n }\n\n // Object\n if (typeof source === 'object') {\n\n // Most useful keys first\n const priorityKeys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage',\n 'response',\n 'body',\n 'data'\n ];\n\n for (const key of priorityKeys) {\n\n if (\n Object.prototype.hasOwnProperty.call(source, key) &&\n source[key] !== null &&\n source[key] !== undefined\n ) {\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n // Search any remaining keys\n for (const key of Object.keys(source)) {\n\n if (priorityKeys.includes(key)) {\n continue;\n }\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: extract which specific header/item fields are missing\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractMissingFields(cb) {\n\n const fields = [];\n\n if (cb.includes('po_number'))\n fields.push('PO_number');\n\n if (cb.includes('invoice_amount'))\n fields.push('invoice_amount');\n\n if (cb.includes('invoice_id'))\n fields.push('invoice_id');\n\n if (cb.includes('item_code'))\n fields.push('item_code');\n\n if (cb.includes('item_id'))\n fields.push('item_id');\n\n if (cb.includes('batch'))\n fields.push('Batch');\n\n if (cb.includes('quantity'))\n fields.push('quantity');\n\n return fields;\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: get item-code arrays from any supported structure\n// ───────────────────────────────────────────────────────────────────────\n\nfunction getArrayFromSources(sources, fieldNames) {\n\n for (const source of sources) {\n\n if (!source || typeof source !== 'object') {\n continue;\n }\n\n for (const field of fieldNames) {\n\n if (Array.isArray(source[field])) {\n return source[field];\n }\n }\n }\n\n return [];\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Error classifier\n// ───────────────────────────────────────────────────────────────────────\n\nfunction classifyError(\n grnMsg,\n fullErrorRaw,\n missingCodes,\n invalidCodes\n) {\n\n const text = String(\n (grnMsg || '') +\n ' ' +\n (fullErrorRaw || '')\n );\n\n const cb = text.toLowerCase();\n\n const raw =\n String(grnMsg || '').trim() ||\n String(fullErrorRaw || '').trim() ||\n 'Unknown API error';\n\n if (!cb.trim()) {\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: 'Unknown API error'\n };\n }\n\n const hasMissing =\n Array.isArray(missingCodes) &&\n missingCodes.length > 0;\n\n const hasInvalid =\n Array.isArray(invalidCodes) &&\n invalidCodes.length > 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: MySQL Pool Exhausted\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pool exhausted') ||\n cb.includes('mysql.connector.errors.poolerror') ||\n cb.includes('too many connections') ||\n (\n cb.includes('connection refused') &&\n cb.includes('mysql')\n )\n ) {\n return {\n owner: 'DMH',\n category: 'MySQL Pool Exhausted',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Timeout / Gateway\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') ||\n cb.includes('gateway timeout') ||\n cb.includes('etimedout') ||\n cb.includes('econnrefused') ||\n cb.includes('socket hang up') ||\n cb.includes('300000ms') ||\n cb.includes('deadline expired') ||\n cb.includes('connect timeout') ||\n cb.includes('read timeout') ||\n cb.includes('request timed out') ||\n cb.includes('timeout')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'API Timeout / Gateway Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid File Type\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n hasHttpCode(text, 400) &&\n cb.includes('invalid file type')\n ) ||\n cb.includes('unsupported file type') ||\n cb.includes('file type not supported')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid File Type (400)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: File Too Large\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 413) ||\n cb.includes('request entity too large') ||\n cb.includes('payload too large') ||\n cb.includes('file size exceeds') ||\n cb.includes('file too large')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'File Too Large (413)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Gemini / API Key / Quota\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 401) ||\n hasHttpCode(text, 403) ||\n hasHttpCode(text, 429) ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('api error: forbidden') ||\n cb.includes('api error: service unavailable') ||\n cb.includes('fetch failed') ||\n cb.includes('unauthorized: api key') ||\n cb.includes('invalid api key') ||\n cb.includes('quota') ||\n cb.includes('rate limit') ||\n cb.includes('resource has been exhausted')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Gemini API Error (Quota / Auth)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Server Crash\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 500) &&\n (\n cb.includes('internal server error') ||\n cb.includes('nginx') ||\n cb.includes('werkzeug') ||\n cb.includes('traceback') ||\n cb.includes('application error') ||\n cb.includes('server error')\n )\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Server Internal Crash (500)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid Image Format\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pil') ||\n cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') ||\n cb.includes('image file is truncated') ||\n cb.includes('invalid image') ||\n cb.includes('unsupported image')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid Image Format (PIL Error)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: No Binary File Attached\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n cb.includes('binary file') &&\n cb.includes('none was found')\n ) ||\n cb.includes('no file was uploaded') ||\n cb.includes('missing file attachment') ||\n cb.includes('file not found') ||\n cb.includes('no binary data')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'No Binary File Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: CSV File\n // ─────────────────────────────────────────────────────────────────────\n\n if (cb.includes('csv')) {\n return {\n owner: 'DMH',\n category: 'Invalid File Format — CSV Not Supported',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Extraction Failed\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('ocr extraction failed') ||\n cb.includes('ocr extraction') ||\n cb.includes('unknown processing error') ||\n cb.includes('extraction failed') ||\n cb.includes('could not extract') ||\n cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') ||\n cb.includes('pdf parse') ||\n cb.includes('failed to parse') ||\n cb.includes('parsing failed') ||\n cb.includes('unable to extract')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Extraction Failed',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Duplicate Invoice\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('record already exist') ||\n cb.includes('already exist') ||\n cb.includes('duplicate invoice') ||\n cb.includes('duplicate entry') ||\n cb.includes('already exists') ||\n cb.includes('invoice already')\n ) {\n return {\n owner: 'DMH',\n category: 'Duplicate Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: No Valid Items\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes(\n 'the invoice must contain at least one valid item'\n ) ||\n cb.includes('no valid items') ||\n cb.includes('zero valid item') ||\n cb.includes('all items are invalid') ||\n cb.includes('valid item not found') ||\n cb.includes('no valid item found')\n ) {\n\n if (hasMissing && hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') + Invalid Item Codes (' +\n invalidCodes.length +\n ') — Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasMissing) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Invalid Item Codes (' +\n invalidCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n return {\n owner: 'DMH',\n category: 'No Valid Items in Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Vendor Not Found\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('vendor details not found') &&\n !cb.includes('po details not found') &&\n !cb.includes('po number does not contain') &&\n !cb.includes('phrmcy') &&\n !cb.includes('dmhmss') &&\n !cb.includes('not valid!!!') &&\n !cb.includes('po_number')\n ) {\n\n return {\n owner: 'DMH',\n category: 'Vendor Not Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: PO Not Found / Invalid PO\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('po details not found') ||\n cb.includes('not valid!!!') ||\n cb.includes('phrmcy') ||\n cb.includes('dmhmss') ||\n cb.includes('does not contain either') ||\n cb.includes('invalid purchase order') ||\n cb.includes('po not found') ||\n cb.includes('invalid po') ||\n cb.includes('purchase order not found')\n ) {\n\n return {\n owner: 'DMH',\n category: 'PO Not Found / Invalid PO Number',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Item Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing from item list') ||\n cb.includes('item_code') ||\n cb.includes('item_id') ||\n (\n cb.includes('batch') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n ) ||\n (\n cb.includes('quantity') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified item fields';\n\n return {\n owner: 'DMH',\n category:\n 'Item Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Header Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing') ||\n cb.includes('po_number') ||\n (\n cb.includes('invoice_amount') &&\n cb.includes('missing')\n ) ||\n (\n cb.includes('invoice_id') &&\n cb.includes('missing')\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified header fields';\n\n return {\n owner: 'DMH',\n category:\n 'Header Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: GSTIN / GST Mismatch\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('gstin mismatch') ||\n cb.includes('gst mismatch') ||\n cb.includes('gstin validation') ||\n cb.includes('invalid gstin')\n ) {\n\n return {\n owner: 'DMH',\n category: 'GSTIN Mismatch / Validation Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Fallback\n // ─────────────────────────────────────────────────────────────────────\n\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: raw\n };\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Build complete_error\n// ───────────────────────────────────────────────────────────────────────\n\nfunction buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n fallbackRaw\n) {\n\n const message =\n String(grnMsg || '').trim() ||\n String(fallbackRaw || '').trim() ||\n 'Unknown API error';\n\n const c = classifyError(\n message,\n fallbackRaw || '',\n missingCodes,\n invalidCodes\n );\n\n if (!c) {\n return '';\n }\n\n const divider =\n '─────────────────────────────────';\n\n const lines = [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + message\n ];\n\n return lines.join('\\n');\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Resolve messageId\n// ───────────────────────────────────────────────────────────────────────\n\nfunction resolveMessageId(item) {\n\n // Source 1\n try {\n\n const v =\n $('Set messageId Field1')\n .item\n .json\n .messageId;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 2\n try {\n\n const v =\n $('Switch2')\n .item\n .json\n .id;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 3\n if (\n item.json &&\n item.json.messageId\n ) {\n return String(item.json.messageId);\n }\n\n\n // Source 4\n if (\n item.json &&\n item.json.id\n ) {\n return String(item.json.id);\n }\n\n\n return '';\n}\n\n\n// ═══════════════════════════════════════════════════════════════════════\n// MAIN\n// ═══════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n // ─────────────────────────────────────────────────────────────────────\n // IST Timestamp\n // ─────────────────────────────────────────────────────────────────────\n\n const now = new Date();\n\n const date =\n now.toLocaleDateString(\n 'en-CA',\n {\n timeZone: 'Asia/Kolkata'\n }\n );\n\n const time =\n now.toLocaleTimeString(\n 'en-IN',\n {\n timeZone: 'Asia/Kolkata',\n hour12: true\n }\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // messageId\n // ─────────────────────────────────────────────────────────────────────\n\n const messageId =\n resolveMessageId(item);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN root object\n // ─────────────────────────────────────────────────────────────────────\n\n const grn =\n item.json || {};\n\n const httpStatus =\n grn.status;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Parse data\n // ─────────────────────────────────────────────────────────────────────\n\n const grnDataRaw =\n Array.isArray(grn.data) &&\n grn.data.length > 0\n ? grn.data[0]\n : null;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Build possible sources\n // ─────────────────────────────────────────────────────────────────────\n\n const sources = [];\n\n if (grnDataRaw !== null) {\n sources.push(grnDataRaw);\n }\n\n if (\n grn.data &&\n typeof grn.data === 'object'\n ) {\n sources.push(grn.data);\n }\n\n sources.push(grn);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Extract GRN data object\n // ─────────────────────────────────────────────────────────────────────\n\n let grnData = {};\n\n if (\n grnDataRaw &&\n typeof grnDataRaw === 'object' &&\n !Array.isArray(grnDataRaw)\n ) {\n\n grnData = grnDataRaw;\n\n } else if (\n grn.data &&\n typeof grn.data === 'object' &&\n !Array.isArray(grn.data)\n ) {\n\n grnData = grn.data;\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // NEW ROBUST MESSAGE EXTRACTION\n // ─────────────────────────────────────────────────────────────────────\n\n let grnMsg =\n extractErrorMessage(grnDataRaw);\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.data);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.message);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.error);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.detail);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.reason);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.description);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.statusText);\n }\n\n\n // Absolute fallback\n if (!grnMsg) {\n grnMsg = 'Unknown API error';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Missing / Invalid item codes\n // ─────────────────────────────────────────────────────────────────────\n\n const missingCodes =\n getArrayFromSources(\n sources,\n [\n 'missingItmesCodes',\n 'missingItemsCodes',\n 'missing_item_codes',\n 'missingItemCodes',\n 'missing_items',\n 'missingItems'\n ]\n );\n\n\n const invalidCodes =\n getArrayFromSources(\n sources,\n [\n 'invalidItmes',\n 'invalidItems',\n 'invalid_item_codes',\n 'invalidItemCodes',\n 'invalid_items'\n ]\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // HTTP status\n // ─────────────────────────────────────────────────────────────────────\n\n const http_status_code =\n typeof httpStatus === 'number'\n ? httpStatus\n : parseInt(httpStatus, 10) || 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN success\n // ─────────────────────────────────────────────────────────────────────\n\n const httpOk =\n http_status_code === 200;\n\n const grnOk =\n grnData.status === 0 ||\n grnData.status === '0';\n\n const grn_success =\n httpOk && grnOk;\n\n const status =\n grn_success\n ? '✅ SUCCESS'\n : '❌ FAILED';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Invoice fields\n // ─────────────────────────────────────────────────────────────────────\n\n let inv = {};\n\n try {\n\n inv =\n $('Normalize Invoice Fields2')\n .item\n .json || {};\n\n } catch (e) {\n\n inv = {};\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Attachment name\n // ─────────────────────────────────────────────────────────────────────\n\n let attachment_name = '';\n\n try {\n\n attachment_name =\n $('Split: One Item Per Attachment3')\n .item\n .json\n .attachment_name || '';\n\n } catch (e) {\n\n attachment_name = '';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Free Goods\n // ─────────────────────────────────────────────────────────────────────\n\n const invoiceItems =\n Array.isArray(inv.items)\n ? inv.items\n : [];\n\n const hasFreeGoods =\n invoiceItems.some(\n i =>\n String(\n i &&\n i.free_item_yn\n ) === '1'\n );\n\n const free_goods =\n hasFreeGoods\n ? 'Yes'\n : 'No';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Complete error\n // ─────────────────────────────────────────────────────────────────────\n\n let complete_error = '';\n\n\n if (grn_success) {\n\n const auditParts = [];\n\n if (grnData.grn_no) {\n auditParts.push(\n 'GRN No: ' +\n grnData.grn_no\n );\n }\n\n if (grnData.grn_master_id) {\n auditParts.push(\n 'GRN Master ID: ' +\n grnData.grn_master_id\n );\n }\n\n if (\n grnData.items_inserted !== undefined &&\n grnData.items_inserted !== null\n ) {\n auditParts.push(\n 'Items Inserted: ' +\n grnData.items_inserted\n );\n }\n\n if (grnData.vendor_id) {\n auditParts.push(\n 'Vendor ID: ' +\n grnData.vendor_id\n );\n }\n\n if (grnData.invoice_no) {\n auditParts.push(\n 'Invoice No (DMH): ' +\n grnData.invoice_no\n );\n }\n\n complete_error =\n auditParts.length\n ? auditParts.join(' | ')\n : '';\n\n } else {\n\n complete_error =\n buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n JSON.stringify(grn)\n );\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Output\n // ─────────────────────────────────────────────────────────────────────\n\n output.push({\n\n json: {\n\n // Timestamp\n date,\n time,\n\n\n // Invoice identity\n invoice_id:\n inv.invoice_id || '',\n\n invoice_number:\n inv.invoice_number || '',\n\n invoice_date:\n inv.invoice_date || '',\n\n seller_name:\n inv.seller_name || '',\n\n seller_gstin:\n inv.seller_gstin || '',\n\n customer_name:\n inv.customer_name || '',\n\n invoice_amount:\n inv.invoice_amount ?? 0,\n\n attachment_name,\n\n\n // GRN result\n status,\n\n grn_success,\n\n http_status_code,\n\n grn_message:\n grnMsg || 'Unknown API error',\n\n\n // Error detail\n complete_error,\n\n\n // Traceability\n free_goods,\n\n messageId\n }\n });\n\n});\n\n\nreturn output;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-672,
96
],
"id": "864137a6-b9cb-4e21-bcc2-1f2543d04fda",
"name": "Flatten Data for Log2",
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "list",
"cachedResultName": "Invoice_Tracker_NEW",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413"
},
"columns": {
"mappingMode": "defineBelow",
"value": {
"Date": "={{ $json.date }}",
"Time": "={{ $json.time }}",
"Status": "={{ $json.status }}",
"Complete Error / Null Values": "={{ $json.complete_error }}",
"Attachment Name": "={{ $('Wait 7s Before OCR2').item.json.attachment_name }}"
},
"matchingColumns": [],
"schema": [
{
"id": "Sr No.",
"displayName": "Sr No.",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Date",
"displayName": "Date",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Time",
"displayName": "Time",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Attachment Name",
"displayName": "Attachment Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Customer Name",
"displayName": "Customer Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice Amount (₹)",
"displayName": "Invoice Amount (₹)",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice ID",
"displayName": "Invoice ID",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Seller Name",
"displayName": "Seller Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Status",
"displayName": "Status",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "GRN Message ",
"displayName": "GRN Message ",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Seller GSTIN",
"displayName": "Seller GSTIN",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Free Goods",
"displayName": "Free Goods",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Complete Error / Null Values",
"displayName": "Complete Error / Null Values",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
}
],
"attemptToConvertTypes": false,
"convertFieldsToString": false
},
"options": {
"cellFormat": "USER_ENTERED",
"useAppend": true
}
},
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 4.7,
"position": [
-896,
384
],
"id": "b12ab90f-240b-4845-ac94-dada14ce001f",
"name": "Append row in sheet5",
"credentials": {
"googleSheetsOAuth2Api": {
"id": "OGnPiaQp3eu9tWvW",
"name": "Google Sheets account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"jsCode": "// ═══════════════════════════════════════════════════════════════\n// Flatten AI Classification Error for Log\n// Placed BEFORE: Append row in sheet1\n// Receives: Switch2 → error route (classification = \"error\")\n//\n// This fires when the AI provider completely fails to classify\n// the email — API down, quota hit, empty response, parse failure.\n//\n// Uses IDENTICAL complete_error format as Flatten Data for Log2:\n// Error Type : API Blocked — Project Suspended (403)\n// Error From : [AI INDIA]\n// ─────────────────────────────────\n// Raw API error : AGENT_ERROR: 403 PERMISSION_DENIED...\n//\n// NOTE: Category labels are intentionally generic (\"API Error...\")\n// and do NOT mention the underlying provider name (e.g. Gemini)\n// in the output. The raw error text in \"Raw API error\" is left\n// untouched since that's just the upstream message, not a label.\n// ═══════════════════════════════════════════════════════════════\n\n// ── Error classifier ──────────────────────────────────────────\nfunction classifyAIError(errorDetail) {\n const text = String(errorDetail || '');\n const cb = text.toLowerCase();\n\n function hasCode(code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(text);\n }\n\n // 403 Lightning Dunning (most specific — before generic 403)\n if (hasCode(403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Project Suspended (403)' };\n\n // 403 / 401 / Permission denied\n if (hasCode(403) || hasCode(401) || cb.includes('permission_denied') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Permission Denied (403)' };\n\n // 429 / Quota / Rate limit\n if (hasCode(429) || cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('too many requests') || cb.includes('resource has been exhausted') ||\n cb.includes('generate_requests_per_model_per_day'))\n return { owner: 'AI INDIA', category: 'API Quota / Rate Limit (429)' };\n\n // 504 / Timeout\n if (hasCode(504) || cb.includes('gateway timeout') || cb.includes('etimedout') ||\n cb.includes('socket hang up') || cb.includes('300000ms') || cb.includes('deadline expired'))\n return { owner: 'AI INDIA', category: 'API Timeout (504)' };\n\n // 500 server error\n if (hasCode(500) || cb.includes('internal server error'))\n return { owner: 'AI INDIA', category: 'API Server Error (500)' };\n\n // Empty / no response\n if (cb.includes('empty_ai_response') || cb.includes('empty'))\n return { owner: 'AI INDIA', category: 'API Returned Empty Response' };\n\n // JSON / parse failure\n if (cb.includes('no_json_found') || cb.includes('parse_exception') ||\n cb.includes('json_parse_failed') || cb.includes('all_parse_attempts_failed'))\n return { owner: 'AI INDIA', category: 'API Response — JSON Parse Failed' };\n\n // Missing is_invoice field\n if (cb.includes('missing_is_invoice') || cb.includes('is_invoice_field_not_found'))\n return { owner: 'AI INDIA', category: 'API Response — Missing is_invoice Field' };\n\n // Agent-level error\n if (cb.includes('agent_error'))\n return { owner: 'AI INDIA', category: 'API Agent Error' };\n\n // Fallback\n return { owner: 'AI INDIA', category: 'AI Classification Error — Unclassified' };\n}\n\n// ── Build complete_error block ─────────────────────────────────\nfunction buildCompleteError(errorDetail) {\n const c = classifyAIError(errorDetail);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (errorDetail || '(no error detail)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ─────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ══════════════════════════════════════════════════════════════\n// MAIN\n// ══════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // IST Timestamp\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n const messageId = resolveMessageId(item);\n\n // Attachment name\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // Read CORRECT field set by Parse AI Output (not data.error!)\n const errorDetail = data.error_detail || data.error || 'AI_CLASSIFICATION_FAILED';\n const complete_error = buildCompleteError(errorDetail);\n\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (AI never got to OCR)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'AI Classification Failed — Invoice not processed',\n\n // Error block — same format as all other rows\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2016,
384
],
"id": "88f8d70f-f8b0-4462-bf46-478f26a507df",
"name": "Code in JavaScript6",
"onError": "continueRegularOutput"
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 3
},
"conditions": [
{
"leftValue": "={{ $json.classification }}",
"rightValue": "invoice",
"operator": {
"type": "string",
"operation": "equals"
},
"id": "a4a14d24-2846-4497-85b2-d76b08ee5f3f"
}
],
"combinator": "and"
}
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 3
},
"conditions": [
{
"id": "6e8cef57-3eb1-458e-a82c-82f914ff3ffb",
"leftValue": "={{ $json.classification }}",
"rightValue": "error",
"operator": {
"type": "string",
"operation": "equals"
}
}
],
"combinator": "and"
}
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 3
},
"conditions": [
{
"id": "d6db0eb2-e8fa-4b20-b475-6b78e2bbb39e",
"leftValue": "={{ $json.classification }}",
"rightValue": "not_invoice",
"operator": {
"type": "string",
"operation": "equals"
}
}
],
"combinator": "and"
}
}
]
},
"options": {
"fallbackOutput": "extra"
}
},
"type": "n8n-nodes-base.switch",
"typeVersion": 3.4,
"position": [
-2240,
288
],
"id": "334b80a6-4e59-44b6-a627-536fc65ea1cd",
"name": "Switch2"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Failed",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
0,
288
],
"id": "6ee14313-3f3a-447e-a7d5-cf15a29f972b",
"name": "Failed To add2",
"webhookId": "0d4c72df-2457-4462-aa2f-b53949022df8",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"model": "openai/gpt-oss-120b",
"options": {}
},
"type": "@n8n/n8n-nodes-langchain.lmChatGroq",
"typeVersion": 1,
"position": [
-3360,
1184
],
"id": "69adb603-b839-49a8-a652-79c28fc2dcdb",
"name": "Groq Chat Model1",
"credentials": {
"groqApi": {
"id": "5STjMY6aZDMipq2f",
"name": "Groq account"
}
}
},
{
"parameters": {
"jsCode": "// ─── Filter: Skip Non-OCR-able Files ─────────────────────────────\n// Allows ONLY PDF, image, and CSV attachments to reach the next node.\n// Other files (DOCX, TXT, EML etc.) are dropped silently.\n// An empty output from this node = no call generated = safe no-op.\n// ──────────────────────────────────────────────────────────────────────\nconst ALLOWED_MIME_TYPES = [\n 'application/pdf',\n 'image/jpeg',\n 'image/jpg',\n 'image/png',\n 'image/tiff',\n 'image/webp',\n 'image/bmp',\n 'image/gif',\n 'text/csv', // ← added\n 'application/csv' // ← added (some systems send this for .csv)\n];\nconst ALLOWED_EXTENSIONS = [\n '.pdf', '.jpg', '.jpeg', '.png',\n '.tiff', '.tif', '.webp', '.bmp', '.gif',\n '.csv' // ← added\n];\nconst filtered = items.filter(item => {\n const binary = item.binary?.file;\n // ── No binary at all → skip (text-only email path) ──────────────\n if (!binary) {\n return false;\n }\n const mimeType = (binary.mimeType || '').toLowerCase();\n const fileName = (binary.fileName || item.json.attachment_name || '').toLowerCase();\n const lastDot = fileName.lastIndexOf('.');\n const ext = lastDot !== -1 ? fileName.slice(lastDot) : '';\n const isAllowedMime = ALLOWED_MIME_TYPES.some(m => mimeType.includes(m));\n const isAllowedExt = ALLOWED_EXTENSIONS.includes(ext);\n if (!isAllowedMime && !isAllowedExt) {\n console.log('[OCR-FILTER] BLOCKED | file: ' + (binary.fileName || 'unknown') + ' | mime: ' + (mimeType || 'none') + ' | ext: ' + (ext || 'none') + ' | Reason: not PDF, image, or CSV format');\n return false;\n }\n return true;\n});\n// Return empty array cleanly if nothing passes the filter\nreturn filtered;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2016,
192
],
"id": "90bed578-8c62-4c6b-a1d3-e10639a0f051",
"name": "Filter: Skip Non-OCR-able Files",
"disabled": true,
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "list",
"cachedResultName": "Invoice_Tracker_NEW",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413"
},
"columns": {
"mappingMode": "defineBelow",
"value": {
"Date": "={{ $json.date }}",
"Time": "={{ $json.time }}",
"Attachment Name": "={{ $json.attachment_name }}",
"Invoice ID": "={{ $json.invoice_id }}",
"Customer Name": "={{ $json.customer_name }}",
"Invoice Amount (₹)": "={{ $json.invoice_amount }}",
"Seller Name": "={{ $json.seller_name }}",
"Status": "={{ $json.status }}",
"GRN Message ": "={{ $json.grn_message }}",
"Seller GSTIN": "={{ $json.seller_gstin }}",
"Free Goods": "={{ $json.free_goods }}",
"Complete Error / Null Values": "={{ $json.complete_error }}"
},
"matchingColumns": [],
"schema": [
{
"id": "Sr No.",
"displayName": "Sr No.",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Date",
"displayName": "Date",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Time",
"displayName": "Time",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Attachment Name",
"displayName": "Attachment Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Customer Name",
"displayName": "Customer Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice Amount (₹)",
"displayName": "Invoice Amount (₹)",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice ID",
"displayName": "Invoice ID",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller Name",
"displayName": "Seller Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Status",
"displayName": "Status",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "GRN Message ",
"displayName": "GRN Message ",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller GSTIN",
"displayName": "Seller GSTIN",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Free Goods",
"displayName": "Free Goods",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Complete Error / Null Values",
"displayName": "Complete Error / Null Values",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
}
],
"attemptToConvertTypes": false,
"convertFieldsToString": false
},
"options": {}
},
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 4.7,
"position": [
-448,
96
],
"id": "54fc0189-5a1a-402b-93a0-9f575f730f32",
"name": "Log to Google Sheets (Daily Logs)2",
"retryOnFail": false,
"maxTries": 3,
"credentials": {
"googleSheetsOAuth2Api": {
"id": "OGnPiaQp3eu9tWvW",
"name": "Google Sheets account"
}
}
},
{
"parameters": {
"options": {
"temperature": 0.4
}
},
"type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
"typeVersion": 1,
"position": [
-3488,
1184
],
"id": "5b645a7b-acc2-46f6-88e5-82d8d79a8986",
"name": "Google Gemini Chat Model",
"credentials": {
"googlePalmApi": {
"id": "8wBnH32SbKmjkfYp",
"name": "Google Gemini(PaLM) Api account"
}
}
},
{
"parameters": {
"jsCode": "// ═══════════════════════════════════════════════════════════════════\n// Flatten OCR Error for Log\n// Placed BEFORE: Append row in sheet5\n// Receives: OCR Extraction Valid?2 → FALSE branch\n//\n// Produces the SAME complete_error format as Flatten Data for Log2:\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\n// Correctly classifies all OCR errors including:\n// 403 PERMISSION_DENIED → AI INDIA (Server Issue)\n// 400 Invalid file type → DMH\n// 504 Gateway Timeout → AI INDIA\n// 500 Server Crash → AI INDIA\n// PIL image error → AI INDIA\n// PO number missing → DMH\n// Duplicate Invoice → DMH\n// ═══════════════════════════════════════════════════════════════════\n\n// ── Helper: safe word-boundary HTTP status code check ────────────\n// Prevents \"400\" matching \"14005\" or UNKNOWN_ERROR400 from the prefix\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(String(text || ''));\n}\n\n// ── Error classifier ───────────────────────────────────────────────\n// Returns: { owner: \"AI INDIA\"|\"DMH\", category: string, detail: string }\nfunction classifyError(rawError) {\n const text = String(rawError || '');\n const cb = text.toLowerCase();\n const raw = text.trim();\n\n if (!cb.trim()) return { owner: 'AI INDIA', category: 'Unknown OCR Error', detail: '(no error message)' };\n\n // ── DMH: Invalid File Type (400) ───────────────────────────────\n // File format not accepted — DMH responsibility\n if (hasHttpCode(text, 400) && cb.includes('invalid file type'))\n return { owner: 'DMH', category: 'Invalid File Type (400)', detail: raw };\n\n // ── DMH: PO Number Missing ──────────────────────────────────────\n // Invoice rejected due to missing PO — DMH responsibility\n if (cb.includes('po number') || cb.includes('po number is missing') ||\n cb.includes('invoice rejected') || cb.includes('valid po number'))\n return { owner: 'DMH', category: 'Invoice Rejected — PO Number Missing', detail: raw };\n\n // ── DMH: Duplicate Invoice ──────────────────────────────────────\n if (cb.includes('duplicate invoice') || cb.includes('already processed') ||\n cb.includes('already exists'))\n return { owner: 'DMH', category: 'Duplicate Invoice', detail: raw };\n\n // ── AI INDIA: Server Issue (Lightning Dunning) ──────────────────\n // Most specific 403 check — must come BEFORE generic 403\n if (hasHttpCode(text, 403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Server Issue (403)', detail: raw };\n\n // ── AI INDIA: Server Issue Permission Denied / Quota / Auth ────\n if (hasHttpCode(text, 403) || hasHttpCode(text, 401) || hasHttpCode(text, 429) ||\n cb.includes('permission_denied') ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('resource has been exhausted') ||\n cb.includes('unauthorized') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Error — Server Issue', detail: raw };\n\n // ── AI INDIA: Generic 400 Bad Request ──────────────────────────\n if (hasHttpCode(text, 400))\n return { owner: 'AI INDIA', category: 'Bad Request to OCR API (400)', detail: raw };\n\n // ── AI INDIA: Timeout / Gateway ────────────────────────────────\n if (hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') || cb.includes('gateway timeout') ||\n cb.includes('etimedout') || cb.includes('econnrefused') ||\n cb.includes('socket hang up') || cb.includes('300000ms') ||\n cb.includes('deadline expired') || cb.includes('connect timeout') ||\n cb.includes('read timeout'))\n return { owner: 'AI INDIA', category: 'OCR API Timeout / Gateway Error (504)', detail: raw };\n\n // ── AI INDIA: File Too Large (413) ─────────────────────────────\n if (hasHttpCode(text, 413) || cb.includes('request entity too large') ||\n cb.includes('payload too large') || cb.includes('file size exceeds'))\n return { owner: 'AI INDIA', category: 'File Too Large (413)', detail: raw };\n\n // ── AI INDIA: Server Crash (500) ───────────────────────────────\n if (hasHttpCode(text, 500) &&\n (cb.includes('internal server error') || cb.includes('nginx') ||\n cb.includes('werkzeug') || cb.includes('traceback')))\n return { owner: 'AI INDIA', category: 'OCR Server Internal Crash (500)', detail: raw };\n\n // ── AI INDIA: Invalid Image Format (PIL) ───────────────────────\n if (cb.includes('pil') || cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') || cb.includes('image file is truncated'))\n return { owner: 'AI INDIA', category: 'Invalid Image Format (PIL Error)', detail: raw };\n\n // ── AI INDIA: No Binary File ────────────────────────────────────\n if ((cb.includes('binary file') && cb.includes('none was found')) ||\n cb.includes('no file was uploaded') || cb.includes('missing file attachment'))\n return { owner: 'AI INDIA', category: 'No Binary File Found', detail: raw };\n\n // ── AI INDIA: OCR Extraction Failed ────────────────────────────\n if (cb.includes('ocr extraction failed') || cb.includes('extraction failed') ||\n cb.includes('could not extract') || cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') || cb.includes('pdf parse') ||\n cb.includes('unknown processing error'))\n return { owner: 'AI INDIA', category: 'OCR Extraction Failed', detail: raw };\n\n // ── AI INDIA: OCR — Missing invoice_number (validation fail) ───\n if (cb.includes('invoice_number') || cb.includes('invoice number'))\n return { owner: 'AI INDIA', category: 'OCR — invoice_number Missing or Empty', detail: raw };\n\n // ── Fallback ────────────────────────────────────────────────────\n return { owner: 'AI INDIA', category: 'OCR Error — Unclassified', detail: raw };\n}\n\n// ── Build complete_error block ──────────────────────────────────────\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\nfunction buildCompleteError(rawError) {\n const c = classifyError(rawError);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (c.detail || '(no raw message)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ──────────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ── Normalize raw error from item.json.error ───────────────────────\nfunction extractRawError(data) {\n if (!data.error) return '(no error message)';\n if (typeof data.error === 'string') return data.error;\n if (typeof data.error === 'object') {\n return data.error.message || data.error.description || JSON.stringify(data.error);\n }\n return String(data.error);\n}\n\n// ════════════════════════════════════════════════════════════════════\n// MAIN\n// ════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // ── IST Timestamp ──────────────────────────────────────────────\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n // ── messageId ──────────────────────────────────────────────────\n const messageId = resolveMessageId(item);\n\n // ── Attachment name ────────────────────────────────────────────\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // ── Build error string ─────────────────────────────────────────\n const rawError = extractRawError(data);\n const complete_error = buildCompleteError(rawError);\n\n // ── Output — SAME columns as main sheet ───────────────────────\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (OCR failed, nothing extracted)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'OCR Extraction Failed — Server Issue — Invoice not processed',\n\n // Error block\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-1120,
384
],
"id": "6402173a-44c3-4233-b394-0581d4f47f89",
"name": "Flatten OCR Error for Log",
"onError": "continueRegularOutput"
},
{
"id": "3b533f17-2607-4b4d-80d2-f37ff47d30c0",
"name": "Router: Classify Invoice Condition",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-1120,
96
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "function isPOValid(po) {\n if (!po) return false;\n const s = po.toString().trim().toLowerCase();\n return s.length > 0 && !['n/a','na','-','0','null','nil','none','undefined','not found',''].includes(s);\n}\n\nreturn items.map(item => {\n const inv = item.json;\n const po_present = isPOValid(inv.PO_number);\n const itemList = Array.isArray(inv.items) ? inv.items : [];\n const item_code_present = itemList.length > 0 && itemList.every(i => (i.item_code || '').toString().trim() !== '');\n\n let route = 1;\n if (po_present && item_code_present) {\n route = 1; // Condition 1: Direct GRN\n } else if (po_present && !item_code_present) {\n route = 2; // Condition 2 or 3: Fetch PO Details API first\n } else if (!po_present && item_code_present) {\n route = 4; // Condition 4: Manual PO Approval Queue\n } else {\n route = 5; // Condition 5: Manual PO Approval Queue\n }\n\n return {\n json: {\n ...inv,\n _route: route,\n _po_present: po_present,\n _item_code_present: item_code_present\n }\n };\n});"
}
},
{
"id": "ba1e5bd5-01a7-4266-82bb-4576c57199e6",
"name": "Switch: 4-Way Condition Router",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [
-800,
96
],
"parameters": {
"mode": "rules",
"rules": {
"rules": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "b017fe4a-1f29-41e6-a01d-1c400e5e2211",
"leftValue": "={{ $json._route }}",
"rightValue": 1,
"operator": {
"type": "number",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 1 — Direct GRN"
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "cd47adf8-aea5-4a6e-9b1e-92225ebab209",
"leftValue": "={{ $json._route }}",
"rightValue": 2,
"operator": {
"type": "number",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 2/3 — Fetch PO Details"
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "73178f10-c3c2-4df2-b1d1-eecd2aeb4bf1",
"leftValue": "={{ $json._route }}",
"rightValue": 4,
"operator": {
"type": "number",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 4 — Manual PO Approval"
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "49a06089-1d42-436d-923d-ddbf0318e889",
"leftValue": "={{ $json._route }}",
"rightValue": 5,
"operator": {
"type": "number",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 5 — Manual PO & Item Approval"
}
]
},
"options": {}
}
},
{
"id": "5376696e-1a21-41d3-96fa-30766c45e72b",
"name": "HTTP: Fetch DMH PO Details",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-800,
-200
],
"parameters": {
"method": "GET",
"url": "={{ $env.DMH_PO_DETAILS_API_URL || 'https://mapp.dmhospital.org/dmhApiRef/po/getPoDetails.php' }}",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "={{ $env.DMH_PO_DETAILS_API_KEY || 'nirajAi26@DMH' }}"
}
]
},
"sendQuery": true,
"queryParameters": {
"parameters": [
{
"name": "po_number",
"value": "={{ $json.PO_number }}"
}
]
},
"options": {
"response": {
"response": {
"responseFormat": "json"
}
},
"timeout": 15000
}
}
},
{
"id": "3a164cf6-4572-458f-b6aa-f0a5e4797536",
"name": "Code: Merge PO Item Codes",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-400,
-200
],
"parameters": {
"mode": "runOnceForEachItem",
"jsCode": "// Merges item codes from DMH PO Details API\n// If item codes are found -> _condition = 2 (Proceed to GRN)\n// If item codes NOT found -> _condition = 3 (Route to Manual Item Code Approval)\nreturn items.map(item => {\n const inv = item.json;\n const poResponse = inv.data || inv;\n const poItems = poResponse.items || poResponse.data?.items || [];\n const originalItems = inv.items || [];\n\n const codeMap = {};\n poItems.forEach(pi => {\n const key = (pi.description || pi.item_name || pi.name || '').toLowerCase().trim();\n if (key && pi.item_code) codeMap[key] = pi.item_code;\n });\n\n let anyFound = false;\n const mergedItems = originalItems.map(oi => {\n const key = (oi.description || '').toLowerCase().trim();\n const foundCode = codeMap[key] || oi.item_code || '';\n if (foundCode) anyFound = true;\n return {\n ...oi,\n item_code: foundCode\n };\n });\n\n const condition = anyFound ? 2 : 3;\n return {\n json: {\n ...inv,\n items: mergedItems,\n _condition: condition,\n _item_codes_found: anyFound\n }\n };\n});"
}
},
{
"id": "0bd30100-a417-44eb-bbec-b087bab1b6fd",
"name": "HTTP: Post to Pharmacy Dashboard (C3)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-800,
300
],
"parameters": {
"method": "POST",
"url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Content-Type",
"value": "application/json"
},
{
"name": "X-API-Key",
"value": "={{ $env.N8N_WEBHOOK_SECRET }}"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ JSON.stringify({ extraction_id: null, invoice_number: $json.invoice_number, vendor_name: $json.seller_name, invoice_date: $json.invoice_date, invoice_filename: $json.invoice_id || '', po_number_original: $json.PO_number, condition_type: 'condition_3', items: $json.items, full_invoice: $json }) }}",
"options": {
"timeout": 15000
}
}
},
{
"id": "eeb4a3d1-6fce-4f87-87c9-45546945ae89",
"name": "HTTP: Post to Pharmacy Dashboard (C4)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-800,
500
],
"parameters": {
"method": "POST",
"url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Content-Type",
"value": "application/json"
},
{
"name": "X-API-Key",
"value": "={{ $env.N8N_WEBHOOK_SECRET }}"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ JSON.stringify({ extraction_id: null, invoice_number: $json.invoice_number, vendor_name: $json.seller_name, invoice_date: $json.invoice_date, invoice_filename: $json.invoice_id || '', po_number_original: $json.PO_number, condition_type: 'condition_4', items: $json.items, full_invoice: $json }) }}",
"options": {
"timeout": 15000
}
}
},
{
"id": "11137476-ca21-4bd6-9d7e-d4f6af3097b1",
"name": "Switch: Condition 2 vs 3",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [
-100,
-200
],
"parameters": {
"mode": "rules",
"rules": {
"rules": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "fb7b7103-90f0-4e73-9706-2e8ac1d549e0",
"leftValue": "={{ $json._condition }}",
"rightValue": 2,
"operator": {
"type": "number",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 2 (Codes Found -> GRN)"
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "52755876-80b6-496a-bc22-278a76bfc4af",
"leftValue": "={{ $json._condition }}",
"rightValue": 3,
"operator": {
"type": "number",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 3 (Codes Not Found -> Pharmacy Dashboard)"
}
]
},
"options": {}
}
},
{
"id": "7b477b4b-d4b5-4fb7-8e23-8023cc84714e",
"name": "HTTP: Post to Pharmacy Dashboard (C5)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-800,
700
],
"parameters": {
"method": "POST",
"url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Content-Type",
"value": "application/json"
},
{
"name": "X-API-Key",
"value": "={{ $env.N8N_WEBHOOK_SECRET }}"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ JSON.stringify({ extraction_id: null, invoice_number: $json.invoice_number, vendor_name: $json.seller_name, invoice_date: $json.invoice_date, invoice_filename: $json.invoice_id || '', po_number_original: $json.PO_number, condition_type: 'condition_5', items: $json.items, full_invoice: $json }) }}",
"options": {
"timeout": 15000
}
}
}
],
"connections": {
"Append row in sheet1": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Watch New_Invoice Label1": {
"main": [
[
{
"node": "Fetch Emails from New_Invoice (max 3)1",
"type": "main",
"index": 0
}
]
]
},
"AI: Classify Invoice1": {
"main": [
[
{
"node": "Merge: Email + AI Classification1",
"type": "main",
"index": 1
}
]
]
},
"OCR: Extract Invoice Data2": {
"main": [
[
{
"node": "OCR Extraction Valid?2",
"type": "main",
"index": 0
}
]
]
},
"Merge: Email + AI Classification1": {
"main": [
[
{
"node": "Split: One Item Per Attachment3",
"type": "main",
"index": 0
}
]
]
},
"Fetch Emails from New_Invoice (max 3)1": {
"main": [
[
{
"node": "Loop: Each Email2",
"type": "main",
"index": 0
}
]
]
},
"Loop: Each Email2": {
"main": [
[
{
"node": "Label: Add Processing2",
"type": "main",
"index": 0
}
],
[
{
"node": "End: No More Emails1",
"type": "main",
"index": 0
}
]
]
},
"End: No More Emails1": {
"main": [
[
{
"node": "Loop: Each Email2",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Processing2": {
"main": [
[
{
"node": "Label: Remove New_Invoice1",
"type": "main",
"index": 0
}
]
]
},
"Label: Remove New_Invoice1": {
"main": [
[
{
"node": "Fetch Full Email + Attachments2",
"type": "main",
"index": 0
}
]
]
},
"Fetch Full Email + Attachments2": {
"main": [
[
{
"node": "Set messageId Field1",
"type": "main",
"index": 0
},
{
"node": "AI: Classify Invoice1",
"type": "main",
"index": 0
}
]
]
},
"Parse AI Output2": {
"main": [
[
{
"node": "Switch2",
"type": "main",
"index": 0
}
]
]
},
"Set messageId Field1": {
"main": [
[
{
"node": "Merge: Email + AI Classification1",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Not_Invoice2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Invoice_Done2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Invoice_failed2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"OCR Extraction Valid?2": {
"main": [
[
{
"node": "Normalize Invoice Fields2",
"type": "main",
"index": 0
}
],
[
{
"node": "Flatten OCR Error for Log",
"type": "main",
"index": 0
}
]
]
},
"GRN: Create Record in Hospital2": {
"main": [
[
{
"node": "Flatten Data for Log2",
"type": "main",
"index": 0
}
]
]
},
"Normalize Invoice Fields2": {
"main": [
[
{
"node": "Router: Classify Invoice Condition",
"type": "main",
"index": 0
}
]
]
},
"GRN Created Successfully?2": {
"main": [
[
{
"node": "Label: Add Invoice_Done2",
"type": "main",
"index": 0
}
],
[
{
"node": "Failed To add2",
"type": "main",
"index": 0
}
]
]
},
"Split: One Item Per Attachment3": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Loop: Each Attachment2": {
"main": [
[],
[
{
"node": "Parse AI Output2",
"type": "main",
"index": 0
}
]
]
},
"Wait 7s Before OCR2": {
"main": [
[
{
"node": "OCR: Extract Invoice Data2",
"type": "main",
"index": 0
}
]
]
},
"Flatten Data for Log2": {
"main": [
[
{
"node": "Log to Google Sheets (Daily Logs)2",
"type": "main",
"index": 0
}
]
]
},
"Append row in sheet5": {
"main": [
[
{
"node": "Label: Add Invoice_failed2",
"type": "main",
"index": 0
}
]
]
},
"Code in JavaScript6": {
"main": [
[
{
"node": "Append row in sheet1",
"type": "main",
"index": 0
}
]
]
},
"Switch2": {
"main": [
[
{
"node": "Filter: Skip Non-OCR-able Files",
"type": "main",
"index": 0
}
],
[
{
"node": "Code in JavaScript6",
"type": "main",
"index": 0
}
],
[
{
"node": "Label: Add Not_Invoice2",
"type": "main",
"index": 0
}
],
[
{
"node": "Code in JavaScript6",
"type": "main",
"index": 0
}
]
]
},
"Filter: Skip Non-OCR-able Files": {
"main": [
[
{
"node": "Wait 7s Before OCR2",
"type": "main",
"index": 0
}
]
]
},
"Failed To add2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Groq Chat Model1": {
"ai_languageModel": [
[
{
"node": "AI: Classify Invoice1",
"type": "ai_languageModel",
"index": 1
}
]
]
},
"Log to Google Sheets (Daily Logs)2": {
"main": [
[
{
"node": "GRN Created Successfully?2",
"type": "main",
"index": 0
}
]
]
},
"Google Gemini Chat Model": {
"ai_languageModel": [
[
{
"node": "AI: Classify Invoice1",
"type": "ai_languageModel",
"index": 0
}
]
]
},
"Flatten OCR Error for Log": {
"main": [
[
{
"node": "Append row in sheet5",
"type": "main",
"index": 0
}
]
]
},
"Router: Classify Invoice Condition": {
"main": [
[
{
"node": "Switch: 4-Way Condition Router",
"type": "main",
"index": 0
}
]
]
},
"Switch: 4-Way Condition Router": {
"main": [
[
{
"node": "GRN: Create Record in Hospital2",
"type": "main",
"index": 0
}
],
[
{
"node": "HTTP: Fetch DMH PO Details",
"type": "main",
"index": 0
}
],
[
{
"node": "HTTP: Post to Pharmacy Dashboard (C4)",
"type": "main",
"index": 0
}
],
[
{
"node": "HTTP: Post to Pharmacy Dashboard (C5)",
"type": "main",
"index": 0
}
]
]
},
"HTTP: Fetch DMH PO Details": {
"main": [
[
{
"node": "Code: Merge PO Item Codes",
"type": "main",
"index": 0
}
]
]
},
"Code: Merge PO Item Codes": {
"main": [
[
{
"node": "Switch: Condition 2 vs 3",
"type": "main",
"index": 0
}
]
]
},
"HTTP: Post to Pharmacy Dashboard (C3)": {
"main": [
[]
]
},
"HTTP: Post to Pharmacy Dashboard (C4)": {
"main": [
[]
]
},
"Switch: Condition 2 vs 3": {
"main": [
[
{
"node": "GRN: Create Record in Hospital2",
"type": "main",
"index": 0
}
],
[
{
"node": "HTTP: Post to Pharmacy Dashboard (C3)",
"type": "main",
"index": 0
}
]
]
},
"HTTP: Post to Pharmacy Dashboard (C5)": {
"main": [
[]
]
}
},
"settings": {
"executionOrder": "v1",
"binaryMode": "separate",
"timeSavedMode": "fixed",
"saveExecutionProgress": true,
"callerPolicy": "workflowsFromSameOwner",
"availableInMCP": false
},
"staticData": {
"node:Watch New_Invoice Label1": {
"lastTimeChecked": "2026-11-18T15:51:37.013+05:30"
}
},
"meta": {
"templateCredsSetupCompleted": true
},
"nodeGroups": [],
"pinData": {
"Watch New_Invoice Label1": [
{
"json": {
"id": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoARgAAA3R9Z7-WZCBHqvG_09flPEoHAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAJRkAPlTP4RNsddkpsHybkoAAAA5XQWtAAAA",
"conversationId": "AQQkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoAEADgrABTb8JpRr-DRXapa6y6",
"subject": "Fw: Invoice",
"bodyPreview": "________________________________\r\nFrom: Kalpak Marketing Pvt. Ltd. <kalpakmarketingpune@gmail.com>\r\nSent: Friday, October 9, 2026 12:10 PM\r\nTo: MSS Purchase <msspurchase@dmhospital.org>\r\nSubject: Invoice\r\n\r\nCAUTION: This email originated from outside of",
"from": "msspurchase@dmhospital.org",
"to": [
"mss.receipt@dmhospital.org"
],
"categories": [],
"hasAttachments": true
},
"binary": {
"attachment_0": {
"mimeType": "application/pdf",
"fileType": "pdf",
"fileExtension": "pdf",
"data": "database",
"fileName": "New Doc 10-09-2026 12.10.pdf",
"id": "database:bca5fe77-cc9d-4e80-932f-62a367cd86a8",
"fileSize": "617 kB",
"bytes": 617324
}
},
"pairedItem": {
"item": 0
}
}
]
},
"versionId": "76305287-8e74-4038-9a85-a6f909fc5b2d",
"activeVersionId": "e33393f4-a186-4ea6-8ab3-61c482ec228f",
"versionCounter": 93,
"triggerCount": 1,
"sourceWorkflowId": null,
"shared": [
{
"updatedAt": "2026-09-15T07:46:14.929Z",
"createdAt": "2026-09-15T07:46:14.929Z",
"role": "workflow:owner",
"workflowId": "EyAw3kSLbeIEnpyf",
"projectId": "U9SnIeRl7eF0hSQX",
"project": {
"updatedAt": "2026-09-15T07:47:28.147Z",
"createdAt": "2026-09-15T07:43:05.605Z",
"id": "U9SnIeRl7eF0hSQX",
"name": "Invoice Aiindia <aiindia.invoice@gmail.com>",
"type": "personal",
"icon": null,
"description": null,
"customTelemetryTags": [],
"creatorId": "9f578e99-f4de-457a-8344-b8c82fadc25d"
}
}
],
"tags": [
{
"updatedAt": "2026-09-15T07:46:09.800Z",
"createdAt": "2026-09-15T07:46:09.800Z",
"id": "Nca3jDpPX9nLSq7y",
"name": "production"
},
{
"updatedAt": "2026-09-15T07:46:09.831Z",
"createdAt": "2026-09-15T07:46:09.831Z",
"id": "otaGZ3WSkv1hyy2B",
"name": "lead-intelligence"
},
{
"updatedAt": "2026-09-15T07:46:09.831Z",
"createdAt": "2026-09-15T07:46:09.831Z",
"id": "q9n74oMLardp0TCD",
"name": "outlook"
},
{
"updatedAt": "2026-09-15T07:46:09.838Z",
"createdAt": "2026-09-15T07:46:09.838Z",
"id": "TK1XnjFEsfCQ77ir",
"name": "SEO"
},
{
"updatedAt": "2026-09-15T07:46:09.840Z",
"createdAt": "2026-09-15T07:46:09.840Z",
"id": "f3VP6ad1R0CDm31u",
"name": "v9-final"
},
{
"updatedAt": "2026-09-15T07:46:09.844Z",
"createdAt": "2026-09-15T07:46:09.844Z",
"id": "841y4IviYcHFNWIM",
"name": "v25"
}
],
"parentFolder": null,
"activeVersion": {
"updatedAt": "2026-10-10T10:33:00.659Z",
"createdAt": "2026-10-10T10:01:16.335Z",
"versionId": "e33393f4-a186-4ea6-8ab3-61c482ec228f",
"workflowId": "EyAw3kSLbeIEnpyf",
"nodes": [
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "=1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "id"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413"
},
"columns": {
"mappingMode": "defineBelow",
"value": {
"Date": "={{ $json.date }}",
"Time": "={{ $json.time }}",
"Attachment Name": "={{ $json.attachment_name }}",
"Status": "={{ $json.status }}",
"GRN Message ": "={{ $json.grn_message }}",
"Complete Error / Null Values": "={{ $json.complete_error }}"
},
"matchingColumns": [],
"schema": [
{
"id": "Sr No.",
"displayName": "Sr No.",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Date",
"displayName": "Date",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Time",
"displayName": "Time",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Attachment Name",
"displayName": "Attachment Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Customer Name",
"displayName": "Customer Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice Amount (₹)",
"displayName": "Invoice Amount (₹)",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice ID",
"displayName": "Invoice ID",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller Name",
"displayName": "Seller Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Status",
"displayName": "Status",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "GRN Message ",
"displayName": "GRN Message ",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller GSTIN",
"displayName": "Seller GSTIN",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Free Goods",
"displayName": "Free Goods",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Complete Error / Null Values",
"displayName": "Complete Error / Null Values",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
}
],
"attemptToConvertTypes": false,
"convertFieldsToString": false
},
"options": {}
},
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 4.7,
"position": [
-1792,
384
],
"id": "1550194a-e54a-4b53-8b77-aa2f3a946d74",
"name": "Append row in sheet1",
"credentials": {
"googleSheetsOAuth2Api": {
"id": "OGnPiaQp3eu9tWvW",
"name": "Google Sheets account"
}
}
},
{
"parameters": {
"pollTimes": {
"item": [
{
"mode": "everyMinute"
}
]
},
"filters": {
"foldersToInclude": [
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==",
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodQAAAA==",
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA=="
]
},
"options": {
"downloadAttachments": true
}
},
"type": "n8n-nodes-base.microsoftOutlookTrigger",
"typeVersion": 1,
"position": [
-4832,
1056
],
"id": "be7ad802-919e-41d8-bd76-d0291e5640dd",
"name": "Watch New_Invoice Label1",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
}
},
{
"parameters": {
"promptType": "define",
"text": "=Email Subject:\n{{$json.subject}}\n\nEmail Body:\n{{$json.bodyPreview || $json.body.content}}\n\nSender Email:\n{{ $json.from }}\n\nAttachment File Name:\n{{$binary.attachment_0.fileName}}\n\nAttachment MIME Type:\n{{$binary.attachment_0.mimeType}}\n",
"needsFallback": true,
"options": {
"systemMessage": "You are an invoice recognition agent operating inside an automated workflow.\n\nYou will receive:\nEmail subject\nEmail body content (plain text or HTML converted to text)\nSender email address and name\nAttachment file name\nAttachment MIME type\n\nYour task:\nDetermine whether the email and its attachment should be treated as a BUSINESS INVOICE.\n\nClassification rules:\nClassify the email as an invoice if ANY billing, payment, receipt, tax, or business transaction context is present.\nThe word \"invoice\" may or may not appear explicitly.\nAttachment file names containing company or brand names (for example: BISLERI.pdf, TATA.pdf, AMAZON.pdf, A+V+TRADING.pdf) may represent invoices.\nIf the attachment MIME type is \"application/pdf\" and the email context is business-related, classify it as an invoice.\nIf there is reasonable doubt, classify the email as an invoice.\n\nHard constraints:\nDo NOT read or analyze PDF binary content.\nDo NOT perform OCR.\nDo NOT extract invoice numbers, dates, or amounts.\nNEVER return null or undefined.\nALWAYS return all fields.\nNEVER include markdown formatting.\nNEVER wrap the output in ```json or ``` blocks.\nNEVER include explanations, headings, or extra text.\n\nOutput requirements:\nReturn ONLY a single valid JSON object.\nThe response must start with { and end with }.\nThe output must be directly parseable using JSON.parse().\n\nReturn the response in this EXACT format:\n\n{\n \"is_invoice\": true or false,\n \"confidence\": \"high\" or \"medium\" or \"low\",\n \"reason\": \"\"\n}"
}
},
"type": "@n8n/n8n-nodes-langchain.agent",
"typeVersion": 2.2,
"position": [
-3488,
960
],
"id": "f43530ad-adfa-41ba-b3e2-59c500b8931e",
"name": "AI: Classify Invoice1",
"alwaysOutputData": false,
"notesInFlow": false,
"retryOnFail": true,
"onError": "continueRegularOutput"
},
{
"parameters": {
"method": "POST",
"url": "https://aiinfinite.in/process-invoice",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523"
}
]
},
"sendBody": true,
"contentType": "multipart-form-data",
"bodyParameters": {
"parameters": [
{
"parameterType": "formBinaryData",
"name": "file",
"inputDataFieldName": "=file"
}
]
},
"options": {}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-1568,
192
],
"id": "bc668542-9d9c-4096-9750-777b7012a29b",
"name": "OCR: Extract Invoice Data2",
"alwaysOutputData": false,
"retryOnFail": true,
"waitBetweenTries": 5000,
"maxTries": 3,
"onError": "continueRegularOutput"
},
{
"parameters": {
"mode": "combine",
"combineBy": "combineByPosition",
"options": {}
},
"type": "n8n-nodes-base.merge",
"typeVersion": 3.2,
"position": [
-3136,
912
],
"id": "c3974a60-9c2b-476b-9283-7eb744b4501e",
"name": "Merge: Email + AI Classification1"
},
{
"parameters": {
"operation": "getAll",
"limit": 3,
"filtersUI": {
"values": {
"filters": {
"foldersToInclude": [
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==",
"AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA=="
]
}
}
},
"options": {
"downloadAttachments": true
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-4608,
1056
],
"id": "939a1916-4d96-4550-9482-fd51209d060a",
"name": "Fetch Emails from New_Invoice (max 3)1",
"executeOnce": true,
"webhookId": "977ad40e-7150-4f6a-a351-e29c08eb4f97",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
}
},
{
"parameters": {
"options": {}
},
"type": "n8n-nodes-base.splitInBatches",
"typeVersion": 3,
"position": [
-4384,
1056
],
"id": "d71ef907-462d-4c40-bb01-2476d9cb7bf3",
"name": "Loop: Each Email2"
},
{
"parameters": {},
"type": "n8n-nodes-base.noOp",
"name": "End: No More Emails1",
"typeVersion": 1,
"position": [
-4160,
1104
],
"id": "90ad177b-23a6-41d0-86fe-fd3f3725e6d8"
},
{
"parameters": {
"operation": "update",
"messageId": {
"__rl": true,
"value": "={{ $json.id }}",
"mode": "id"
},
"updateFields": {
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==",
"mode": "list",
"cachedResultName": "Processing",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D"
}
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-4160,
912
],
"id": "aaab2e62-0622-4bbd-b3d1-648fcb06b290",
"name": "Label: Add Processing2",
"webhookId": "5d0319e0-f28f-4f7a-a562-038cd721cf91",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": {
"__rl": true,
"value": "={{ $('Fetch Emails from New_Invoice (max 3)1').item.json.id }}",
"mode": "id"
},
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==",
"mode": "list",
"cachedResultName": "Processing",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-3936,
912
],
"id": "584c67c7-ff4d-4b72-8a91-a94fe1c6ad4b",
"name": "Label: Remove New_Invoice1",
"webhookId": "e16ef4d9-e84c-4127-aafa-6f61cbdb9ba0",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"disabled": true
},
{
"parameters": {
"operation": "get",
"messageId": {
"__rl": true,
"mode": "id",
"value": "={{ $json.id }}"
},
"options": {
"downloadAttachments": true
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-3712,
912
],
"id": "8f05ea79-5bef-42c3-aef3-fc99f97397e8",
"name": "Fetch Full Email + Attachments2",
"webhookId": "74750b5a-de62-4326-888d-2d36ef832e5f",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
}
},
{
"parameters": {
"jsCode": "// ═══════════════════════════════════════════════════════════════════\n// MASTER PARSE AI OUTPUT — Production Grade — Never-Fail Strategy\n//\n// Handles ALL known Gemini / Groq / LangChain output formats:\n// 1. Standard string in output field\n// 2. output field is already a parsed Object\n// 3. output field is an Array (unwraps first element)\n// 4. Double-nested output.output\n// 5. JSON wrapped in ```json ... ``` markdown fences\n// 6. JSON buried inside explanatory text (extracts all {} blocks)\n// 7. Malformed / unclosed JSON (regex fallback)\n// 8. is_invoice as boolean true/false\n// 9. is_invoice as string \"true\"/\"false\"/\"True\"/\"yes\"/\"1\"\n// 10. is_invoice as number 1/0\n// 11. Alternative field names: isInvoice, invoice, type, classification\n// 12. Confidence values: \"HIGH\", \"high\", \"Medium\", \"certain\", \"low\"\n// 13. text / content / message / result field instead of output\n// 14. LangChain wrapped format (lc/kwargs/content)\n// 15. Agent-level errors (quota, API down, 429, etc.)\n// 16. BOM characters and non-printable chars in output\n// 17. Partial / truncated JSON (regex field extraction)\n//\n// CLASSIFICATION OUTPUT (Switch node reads this):\n// \"invoice\" → process as invoice\n// \"not_invoice\" → skip, label as not-invoice\n// \"error\" → log error, do not process\n// ═══════════════════════════════════════════════════════════════════\n\nreturn items.map(item => {\n\n let classification = 'error';\n let confidence = 'low';\n let ai_reason = '';\n let error_detail = '';\n\n try {\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 1 — Agent-level error check\n // Catches: Gemini quota, API key invalid, network timeout, 429\n // ══════════════════════════════════════════════════════════════\n if (item.json.error) {\n const errVal = item.json.error;\n const errStr = typeof errVal === 'object'\n ? (errVal.message || JSON.stringify(errVal))\n : String(errVal);\n error_detail = 'AGENT_ERROR: ' + errStr.slice(0, 300);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 2 — Find raw content from all possible field paths\n // Try: output → text → content → message → result → response\n // ══════════════════════════════════════════════════════════════\n const FIELD_PATHS = ['output', 'text', 'content', 'message', 'result', 'response'];\n let raw = null;\n let parsed = null; // set if we already have a parsed object\n\n for (const path of FIELD_PATHS) {\n const val = item.json[path];\n if (val === null || val === undefined || val === '') continue;\n raw = val;\n break;\n }\n\n if (raw === null) {\n // Last resort: check if item.json itself IS the parsed object\n if (item.json.is_invoice !== undefined) {\n parsed = item.json;\n raw = null;\n } else {\n error_detail = 'NO_OUTPUT_FIELD: checked output/text/content/message/result';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 3 — Unwrap arrays and nested objects\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n // Unwrap Array → take first element\n if (Array.isArray(raw)) {\n raw = raw[0];\n }\n\n // If raw is an Object (n8n pre-parsed the JSON)\n if (raw !== null && typeof raw === 'object') {\n // Check for LangChain format: {lc: 1, kwargs: {content: \"...\"}}\n if (raw.kwargs && raw.kwargs.content !== undefined) {\n raw = raw.kwargs.content;\n\n // Check for double-nested output field\n } else if (raw.output !== undefined) {\n raw = raw.output;\n // raw might still be an object — check again\n if (raw !== null && typeof raw === 'object') {\n if (Array.isArray(raw)) raw = raw[0];\n if (raw !== null && typeof raw === 'object') {\n parsed = raw;\n raw = null;\n }\n }\n\n } else {\n // Object IS the parsed result\n parsed = raw;\n raw = null;\n }\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 4 — Parse JSON from string (multi-attempt strategy)\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n const rawStr = String(raw);\n\n if (rawStr.trim() === '') {\n error_detail = 'EMPTY_AI_RESPONSE';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ── Clean the string ──────────────────────────────────────\n let cleaned = rawStr\n .replace(/\\uFEFF/g, '') // BOM character\n .replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/g, '') // control chars (keep \\n \\r \\t)\n .replace(/```json\\s*/gi, '') // opening ```json fence\n .replace(/```\\s*/g, '') // closing ``` fence\n .trim();\n\n // ── Attempt 1: Direct JSON.parse of entire cleaned string ──\n parsed = tryParse(cleaned);\n\n // ── Attempt 2: Extract first complete { ... } block ───────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'first');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 3: Extract the JSON block CONTAINING is_invoice ─\n if (!parsed) {\n const block = extractJsonBlockWithKey(cleaned, 'is_invoice');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 4: Extract LAST { ... } block ─────────────────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'last');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 5: Try ALL { ... } blocks ─────────────────────\n if (!parsed) {\n const blocks = extractAllJsonBlocks(cleaned);\n for (const block of blocks) {\n const p = tryParse(block);\n if (p && (p.is_invoice !== undefined || p.isInvoice !== undefined)) {\n parsed = p;\n break;\n }\n }\n if (!parsed && blocks.length > 0) {\n parsed = tryParse(blocks[0]); // take first even if no is_invoice key\n }\n }\n\n // ── Attempt 6: Regex field extraction (malformed JSON) ────\n if (!parsed) {\n parsed = regexExtract(cleaned);\n }\n\n if (!parsed) {\n error_detail = 'ALL_PARSE_ATTEMPTS_FAILED: ' + cleaned.slice(0, 200);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 5 — Extract is_invoice from parsed object\n // Try all known field name variants\n // ══════════════════════════════════════════════════════════════\n const IS_INVOICE_FIELDS = [\n 'is_invoice', 'isInvoice', 'is_Invoice', 'IS_INVOICE',\n 'invoice', 'is_invoice_document', 'invoiceDetected'\n ];\n\n let rawFlag = undefined;\n let usedField = '';\n\n for (const field of IS_INVOICE_FIELDS) {\n if (parsed[field] !== undefined) {\n rawFlag = parsed[field];\n usedField = field;\n break;\n }\n }\n\n // ── Try classification/type fields (value-based check) ──────\n if (rawFlag === undefined) {\n const typeVal = String(parsed.classification || parsed.type || parsed.category || '').toLowerCase();\n if (typeVal.includes('invoice')) { rawFlag = true; }\n else if (typeVal.includes('not') ||\n typeVal.includes('skip') ||\n typeVal.includes('other')) { rawFlag = false; }\n }\n\n // ── If still not found, scan the raw text for patterns ──────\n if (rawFlag === undefined && raw) {\n const rawLower = String(raw).toLowerCase();\n const m = rawLower.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|1|0)/);\n if (m) {\n rawFlag = (m[1] === 'true' || m[1] === '\"true\"' || m[1] === '1');\n }\n }\n\n if (rawFlag === undefined) {\n error_detail = 'IS_INVOICE_FIELD_NOT_FOUND. Parsed object: ' + JSON.stringify(parsed).slice(0, 200);\n classification = 'error';\n\n } else {\n // ══════════════════════════════════════════════════════════\n // STAGE 6 — Normalize is_invoice to definitive boolean\n // ══════════════════════════════════════════════════════════\n const flag = String(rawFlag).toLowerCase().trim();\n\n if (['true', '1', 'yes', 'y', 'correct', 'affirmative', 'confirmed'].includes(flag)) {\n classification = 'invoice';\n\n } else if (['false', '0', 'no', 'n', 'incorrect', 'negative', 'not'].includes(flag)) {\n classification = 'not_invoice';\n\n } else {\n error_detail = 'UNEXPECTED_IS_INVOICE_VALUE: \"' + String(rawFlag) + '\"';\n classification = 'error';\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 7 — Extract confidence and reason\n // ══════════════════════════════════════════════════════════════\n if (parsed) {\n // Confidence: normalize to \"high\" | \"medium\" | \"low\"\n const rawConf = String(parsed.confidence || parsed.certainty || parsed.score || 'low').toLowerCase().trim();\n if (['high', 'very_high', 'certain', 'definite', 'strong'].some(v => rawConf.includes(v))) {\n confidence = 'high';\n } else if (['medium', 'moderate', 'mid', 'possible', 'likely'].some(v => rawConf.includes(v))) {\n confidence = 'medium';\n } else {\n confidence = 'low';\n }\n\n // Reason: try multiple field names\n ai_reason = String(\n parsed.reason || parsed.explanation || parsed.rationale ||\n parsed.description || parsed.detail || ''\n ).slice(0, 500);\n }\n\n } catch (e) {\n error_detail = error_detail || ('UNCAUGHT_EXCEPTION: ' + e.message);\n classification = 'error';\n }\n\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n\n});\n\n// ══════════════════════════════════════════════════════════════════\n// HELPER FUNCTIONS\n// ══════════════════════════════════════════════════════════════════\n\nfunction buildOutput(item, classification, confidence, ai_reason, error_detail) {\n return {\n json: {\n ...item.json,\n classification,\n confidence,\n ai_reason,\n error_detail\n },\n binary: item.binary\n };\n}\n\nfunction tryParse(str) {\n try {\n if (!str || str.trim() === '') return null;\n const result = JSON.parse(str.trim());\n // Must be an object, not array/primitive\n if (result && typeof result === 'object' && !Array.isArray(result)) return result;\n if (Array.isArray(result) && result.length > 0 && typeof result[0] === 'object') return result[0];\n return null;\n } catch(e) {\n return null;\n }\n}\n\nfunction extractJsonBlock(str, which) {\n // Find matching { } block accounting for nesting\n const results = extractAllJsonBlocks(str);\n if (results.length === 0) return null;\n return which === 'last' ? results[results.length - 1] : results[0];\n}\n\nfunction extractAllJsonBlocks(str) {\n const blocks = [];\n let depth = 0, start = -1;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '{') {\n if (depth === 0) start = i;\n depth++;\n } else if (str[i] === '}') {\n depth--;\n if (depth === 0 && start !== -1) {\n blocks.push(str.slice(start, i + 1));\n start = -1;\n }\n }\n }\n return blocks;\n}\n\nfunction extractJsonBlockWithKey(str, key) {\n const blocks = extractAllJsonBlocks(str);\n for (const block of blocks) {\n if (block.includes('\"' + key + '\"') || block.includes(\"'\" + key + \"'\")) {\n return block;\n }\n }\n return null;\n}\n\nfunction regexExtract(str) {\n // Last resort: use regex to pull specific fields directly from string\n // even if the JSON is malformed or truncated\n try {\n const result = {};\n let found = false;\n\n // Extract is_invoice\n const mInv = str.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|\"yes\"|\"no\"|1|0)/i);\n if (mInv) {\n const v = mInv[1].replace(/\"/g, '').toLowerCase();\n result.is_invoice = ['true', 'yes', '1'].includes(v);\n found = true;\n }\n\n // Extract confidence\n const mConf = str.match(/\"confidence\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mConf) result.confidence = mConf[1];\n\n // Extract reason\n const mReason = str.match(/\"reason\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mReason) result.reason = mReason[1];\n\n return found ? result : null;\n } catch(e) {\n return null;\n }\n}\n"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2464,
320
],
"id": "e76f2124-e8b2-4b52-86c5-0ab65b6068cf",
"name": "Parse AI Output2",
"retryOnFail": true,
"executeOnce": false,
"alwaysOutputData": true,
"notesInFlow": true
},
{
"parameters": {
"assignments": {
"assignments": [
{
"id": "00093515-229c-432c-9c8d-a2ef09acf369",
"name": "messageId",
"value": "={{$json.id}}",
"type": "string"
}
]
},
"includeOtherFields": true,
"options": {}
},
"type": "n8n-nodes-base.set",
"typeVersion": 3.4,
"position": [
-3424,
672
],
"id": "a5f2223b-6f10-4437-81dc-9a34d57996d0",
"name": "Set messageId Field1"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA==",
"mode": "list",
"cachedResultName": "Not_invoice",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-2016,
576
],
"id": "0c59ac0e-ca75-45bd-b731-3aae0faed96f",
"name": "Label: Add Not_Invoice2",
"webhookId": "d4398f49-ea88-4a89-8f2d-cffbda551562",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": {
"__rl": true,
"value": "={{ $('Flatten Data for Log2').item.json.messageId }}",
"mode": ""
},
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Sucess",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
0,
0
],
"id": "bf5b1548-e75b-40d4-9b2d-a534708db65e",
"name": "Label: Add Invoice_Done2",
"webhookId": "e3a226f8-3b0f-4e68-a8d9-b881d60341ac",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $('Set messageId Field1').item.json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Failed",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
-672,
384
],
"id": "651c1889-e980-4870-a309-35e23ea51aed",
"name": "Label: Add Invoice_failed2",
"webhookId": "8f38dce4-4702-49e4-8a0f-7882a573aacf",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 2
},
"conditions": [
{
"id": "78e67355-b3ff-448c-b597-35b7e0709267",
"leftValue": "={{\n !($json.error && $json.error.includes(\"429\")) &&\n !$json.error &&\n ($json.invoice_number ?? \"\") !== \"\"\n}}",
"rightValue": "",
"operator": {
"type": "boolean",
"operation": "true",
"singleValue": true
}
}
],
"combinator": "and"
},
"options": {}
},
"type": "n8n-nodes-base.if",
"typeVersion": 2.2,
"position": [
-1344,
192
],
"id": "c7004bf2-bb80-4eea-8384-54cbd6baae84",
"name": "OCR Extraction Valid?2"
},
{
"parameters": {
"method": "POST",
"url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "nirajAi26@DMH"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{$json}}",
"options": {}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
-896,
96
],
"id": "4372d6a1-b4d9-4a1f-b522-c3399044ce33",
"name": "GRN: Create Record in Hospital2",
"retryOnFail": false,
"onError": "continueRegularOutput"
},
{
"parameters": {
"jsCode": "function cleanNumber(val) {\n if (val === null || val === undefined) return 0;\n\n return Number(\n val\n .toString()\n .replace(/[^\\d.-]/g, \"\") // remove commas, brackets, symbols\n ) || 0;\n}\n\nreturn items.map(item => {\n\n const inv = item.json;\n\n return {\n json: {\n\n // ── HEADER ────────────────────────────────────────────────────────────\n invoice_id: inv.invoice_id ?? \"\",\n invoice_number: inv.invoice_number ?? \"\",\n invoice_date: inv.invoice_date ?? \"\",\n due_date: inv.due_date ?? \"\",\n seller_name: inv.seller_name ?? \"\",\n PO_number: inv.PO_number ?? \"\",\n\n invoice_amount: cleanNumber(inv.invoice_amount),\n currency_code: inv.currency_code ?? \"INR\",\n\n seller_gstin: inv.seller_gstin ?? \"\",\n customer_name: inv.customer_name ?? \"\",\n\n // ⚠️ HARDCODED — OCR frequently misreads or omits the hospital GSTIN.\n // This is always DEENANATH MEDICAL STORES (DMH Hospital Pharmacy).\n // Never trust the OCR value for this field.\n customer_gstin: \"27AAATL1944N1ZA\",\n\n dc_date: inv.DC_date ?? \"\",\n dc_number: inv.DC_number ?? \"\",\n\n round_off: cleanNumber(inv.round_off),\n\n total_gst_rate: cleanNumber(inv.total_gst_rate),\n total_quantity: cleanNumber(inv.total_quantity),\n\n total_cgst_rate: cleanNumber(inv.total_cgst_rate),\n total_cgst_amount: cleanNumber(inv.total_cgst_amount),\n\n total_sgst_rate: cleanNumber(inv.total_sgst_rate),\n total_sgst_amount: cleanNumber(inv.total_sgst_amount),\n\n total_igst_rate: cleanNumber(inv.total_igst_rate),\n total_igst_amount: cleanNumber(inv.total_igst_amount),\n\n total_gst_amount: cleanNumber(inv.total_gst_amount),\n\n // ── ITEMS ─────────────────────────────────────────────────────────────\n items: (inv.items ?? []).map(i => ({\n\n item_code: i.item_code ?? \"\",\n Batch: i.Batch ?? \"\",\n\n quantity: cleanNumber(i.quantity),\n free_item_yn: cleanNumber(i.free_item_yn),\n\n unit_price: cleanNumber(i.unit_price),\n total_price: cleanNumber(i.total_price),\n\n Discount: cleanNumber(i.Discount),\n MRP: cleanNumber(i.MRP),\n\n description: i.description ?? \"\",\n Pack: i.Pack ?? \"\",\n hsn_sac: i.hsn_sac ?? \"\",\n expiry_date: i.expiry_date ?? \"\",\n\n cgst_rate: cleanNumber(i.cgst_rate),\n cgst_amount: cleanNumber(i.cgst_amount),\n\n sgst_rate: cleanNumber(i.sgst_rate),\n sgst_amount: cleanNumber(i.sgst_amount),\n\n igst_rate: cleanNumber(i.igst_rate),\n igst_amount: cleanNumber(i.igst_amount),\n\n GST_AMT: cleanNumber(i.GST_AMT),\n\n // Added missing fields\n taxable_value: cleanNumber(i.taxable_value),\n \"Gst%\": cleanNumber(i[\"Gst%\"]),\n Value: cleanNumber(i.Value),\n reference_number: i.reference_number ?? \"\"\n\n }))\n\n }\n };\n});"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-1120,
96
],
"id": "6f82a7b4-9dbf-4e9c-a6c4-6a4a52efc6e3",
"name": "Normalize Invoice Fields2"
},
{
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 2
},
"conditions": [
{
"id": "b97ce590-39e2-4792-b38e-972bfd18e0fd",
"leftValue": "={{ $('Flatten Data for Log2').item.json.grn_success }}",
"rightValue": "",
"operator": {
"type": "boolean",
"operation": "true",
"singleValue": true
}
}
],
"combinator": "and"
},
"options": {}
},
"type": "n8n-nodes-base.if",
"typeVersion": 2.2,
"position": [
-224,
96
],
"id": "477bad63-5dad-4f11-bfdb-8f21c9cb801e",
"name": "GRN Created Successfully?2"
},
{
"parameters": {
"jsCode": "const newItems = [];\n\nfor (const item of items) {\n\n const binaries = item.binary || {};\n const keys = Object.keys(binaries);\n\n if (keys.length > 0) {\n\n for (const key of keys) {\n\n // ── GET filename before binary is consumed ──────────────\n const attachment_name = binaries[key].fileName || '';\n\n newItems.push({\n json: {\n ...item.json,\n attachment_name: attachment_name // ← ONLY NEW LINE\n },\n binary: {\n file: binaries[key]\n }\n });\n }\n\n } else {\n\n let parsedOutput = {};\n try {\n parsedOutput = JSON.parse(item.json.output || '{}');\n } catch (e) {\n parsedOutput = {};\n }\n\n newItems.push({\n json: {\n ...item.json,\n ...parsedOutput,\n attachment_name: '' // ← ONLY NEW LINE\n }\n });\n }\n}\n\nreturn newItems;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2912,
912
],
"id": "b019335c-9a06-417b-95bb-862fcfa1a8fc",
"name": "Split: One Item Per Attachment3",
"alwaysOutputData": true,
"retryOnFail": true
},
{
"parameters": {
"options": {}
},
"type": "n8n-nodes-base.splitInBatches",
"typeVersion": 3,
"position": [
-2688,
912
],
"id": "7cb557ad-cb6d-45d4-99e9-8966e310b493",
"name": "Loop: Each Attachment2"
},
{
"parameters": {
"amount": 1
},
"type": "n8n-nodes-base.wait",
"typeVersion": 1.1,
"position": [
-1792,
192
],
"id": "dab6bfb7-215a-4ccd-8964-333200305739",
"name": "Wait 7s Before OCR2",
"webhookId": "66577e6f-2f40-4a0b-a701-b0b535c018e2"
},
{
"parameters": {
"jsCode": "// =======================================================================\n// Flatten Data for Log2 — v5.0\n// Node: Flatten Data for Log2\n//\n// PURPOSE:\n// Parse GRN API responses safely, including unexpected/new error formats.\n//\n// SUPPORTED ERROR MESSAGE LOCATIONS:\n// message\n// error\n// detail\n// reason\n// description\n// statusText\n// error.message\n// error.detail\n// error.description\n// data.message\n// data.error\n// data.detail\n// data[0].message\n// data[0].error\n// data[0].detail\n// data[0] as string\n// JSON-stringified error objects\n//\n// IMPORTANT:\n// Never returns null / undefined / [object Object] as grn_message.\n// =======================================================================\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safe word-boundary HTTP status code check\n// ───────────────────────────────────────────────────────────────────────\n\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(\n String(text || '')\n );\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safely convert any value to useful text\n// ───────────────────────────────────────────────────────────────────────\n\nfunction safeText(value) {\n if (value === null || value === undefined) return '';\n\n if (typeof value === 'string') {\n return value.trim();\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n if (Array.isArray(value)) {\n const parts = value\n .map(v => safeText(v))\n .filter(Boolean);\n\n return parts.join(' | ').trim();\n }\n\n if (typeof value === 'object') {\n // Try common message fields first\n const keys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage'\n ];\n\n for (const key of keys) {\n if (value[key] !== undefined && value[key] !== null) {\n const result = safeText(value[key]);\n if (result) return result;\n }\n }\n\n // Last resort: JSON\n try {\n return JSON.stringify(value);\n } catch (e) {\n return '';\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: recursively extract a meaningful error message\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractErrorMessage(source, depth = 0) {\n\n if (source === null || source === undefined) {\n return '';\n }\n\n // Prevent infinite recursion\n if (depth > 6) {\n return '';\n }\n\n // Direct string\n if (typeof source === 'string') {\n\n const str = source.trim();\n\n if (!str) return '';\n\n // If string itself contains JSON, try parsing it\n if (\n (str.startsWith('{') && str.endsWith('}')) ||\n (str.startsWith('[') && str.endsWith(']'))\n ) {\n try {\n const parsed = JSON.parse(str);\n const nested = extractErrorMessage(parsed, depth + 1);\n\n if (nested) return nested;\n } catch (e) {\n // Not valid JSON — use original string\n }\n }\n\n return str;\n }\n\n // Number / boolean\n if (\n typeof source === 'number' ||\n typeof source === 'boolean'\n ) {\n return String(source);\n }\n\n // Array\n if (Array.isArray(source)) {\n\n // Prefer meaningful string values\n for (const item of source) {\n const result = extractErrorMessage(item, depth + 1);\n\n if (result) {\n return result;\n }\n }\n\n return '';\n }\n\n // Object\n if (typeof source === 'object') {\n\n // Most useful keys first\n const priorityKeys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage',\n 'response',\n 'body',\n 'data'\n ];\n\n for (const key of priorityKeys) {\n\n if (\n Object.prototype.hasOwnProperty.call(source, key) &&\n source[key] !== null &&\n source[key] !== undefined\n ) {\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n // Search any remaining keys\n for (const key of Object.keys(source)) {\n\n if (priorityKeys.includes(key)) {\n continue;\n }\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: extract which specific header/item fields are missing\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractMissingFields(cb) {\n\n const fields = [];\n\n if (cb.includes('po_number'))\n fields.push('PO_number');\n\n if (cb.includes('invoice_amount'))\n fields.push('invoice_amount');\n\n if (cb.includes('invoice_id'))\n fields.push('invoice_id');\n\n if (cb.includes('item_code'))\n fields.push('item_code');\n\n if (cb.includes('item_id'))\n fields.push('item_id');\n\n if (cb.includes('batch'))\n fields.push('Batch');\n\n if (cb.includes('quantity'))\n fields.push('quantity');\n\n return fields;\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: get item-code arrays from any supported structure\n// ───────────────────────────────────────────────────────────────────────\n\nfunction getArrayFromSources(sources, fieldNames) {\n\n for (const source of sources) {\n\n if (!source || typeof source !== 'object') {\n continue;\n }\n\n for (const field of fieldNames) {\n\n if (Array.isArray(source[field])) {\n return source[field];\n }\n }\n }\n\n return [];\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Error classifier\n// ───────────────────────────────────────────────────────────────────────\n\nfunction classifyError(\n grnMsg,\n fullErrorRaw,\n missingCodes,\n invalidCodes\n) {\n\n const text = String(\n (grnMsg || '') +\n ' ' +\n (fullErrorRaw || '')\n );\n\n const cb = text.toLowerCase();\n\n const raw =\n String(grnMsg || '').trim() ||\n String(fullErrorRaw || '').trim() ||\n 'Unknown API error';\n\n if (!cb.trim()) {\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: 'Unknown API error'\n };\n }\n\n const hasMissing =\n Array.isArray(missingCodes) &&\n missingCodes.length > 0;\n\n const hasInvalid =\n Array.isArray(invalidCodes) &&\n invalidCodes.length > 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: MySQL Pool Exhausted\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pool exhausted') ||\n cb.includes('mysql.connector.errors.poolerror') ||\n cb.includes('too many connections') ||\n (\n cb.includes('connection refused') &&\n cb.includes('mysql')\n )\n ) {\n return {\n owner: 'DMH',\n category: 'MySQL Pool Exhausted',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Timeout / Gateway\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') ||\n cb.includes('gateway timeout') ||\n cb.includes('etimedout') ||\n cb.includes('econnrefused') ||\n cb.includes('socket hang up') ||\n cb.includes('300000ms') ||\n cb.includes('deadline expired') ||\n cb.includes('connect timeout') ||\n cb.includes('read timeout') ||\n cb.includes('request timed out') ||\n cb.includes('timeout')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'API Timeout / Gateway Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid File Type\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n hasHttpCode(text, 400) &&\n cb.includes('invalid file type')\n ) ||\n cb.includes('unsupported file type') ||\n cb.includes('file type not supported')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid File Type (400)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: File Too Large\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 413) ||\n cb.includes('request entity too large') ||\n cb.includes('payload too large') ||\n cb.includes('file size exceeds') ||\n cb.includes('file too large')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'File Too Large (413)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Gemini / API Key / Quota\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 401) ||\n hasHttpCode(text, 403) ||\n hasHttpCode(text, 429) ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('api error: forbidden') ||\n cb.includes('api error: service unavailable') ||\n cb.includes('fetch failed') ||\n cb.includes('unauthorized: api key') ||\n cb.includes('invalid api key') ||\n cb.includes('quota') ||\n cb.includes('rate limit') ||\n cb.includes('resource has been exhausted')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Gemini API Error (Quota / Auth)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Server Crash\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 500) &&\n (\n cb.includes('internal server error') ||\n cb.includes('nginx') ||\n cb.includes('werkzeug') ||\n cb.includes('traceback') ||\n cb.includes('application error') ||\n cb.includes('server error')\n )\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Server Internal Crash (500)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid Image Format\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pil') ||\n cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') ||\n cb.includes('image file is truncated') ||\n cb.includes('invalid image') ||\n cb.includes('unsupported image')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid Image Format (PIL Error)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: No Binary File Attached\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n cb.includes('binary file') &&\n cb.includes('none was found')\n ) ||\n cb.includes('no file was uploaded') ||\n cb.includes('missing file attachment') ||\n cb.includes('file not found') ||\n cb.includes('no binary data')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'No Binary File Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: CSV File\n // ─────────────────────────────────────────────────────────────────────\n\n if (cb.includes('csv')) {\n return {\n owner: 'DMH',\n category: 'Invalid File Format — CSV Not Supported',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Extraction Failed\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('ocr extraction failed') ||\n cb.includes('ocr extraction') ||\n cb.includes('unknown processing error') ||\n cb.includes('extraction failed') ||\n cb.includes('could not extract') ||\n cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') ||\n cb.includes('pdf parse') ||\n cb.includes('failed to parse') ||\n cb.includes('parsing failed') ||\n cb.includes('unable to extract')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Extraction Failed',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Duplicate Invoice\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('record already exist') ||\n cb.includes('already exist') ||\n cb.includes('duplicate invoice') ||\n cb.includes('duplicate entry') ||\n cb.includes('already exists') ||\n cb.includes('invoice already')\n ) {\n return {\n owner: 'DMH',\n category: 'Duplicate Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: No Valid Items\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes(\n 'the invoice must contain at least one valid item'\n ) ||\n cb.includes('no valid items') ||\n cb.includes('zero valid item') ||\n cb.includes('all items are invalid') ||\n cb.includes('valid item not found') ||\n cb.includes('no valid item found')\n ) {\n\n if (hasMissing && hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') + Invalid Item Codes (' +\n invalidCodes.length +\n ') — Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasMissing) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Invalid Item Codes (' +\n invalidCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n return {\n owner: 'DMH',\n category: 'No Valid Items in Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Vendor Not Found\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('vendor details not found') &&\n !cb.includes('po details not found') &&\n !cb.includes('po number does not contain') &&\n !cb.includes('phrmcy') &&\n !cb.includes('dmhmss') &&\n !cb.includes('not valid!!!') &&\n !cb.includes('po_number')\n ) {\n\n return {\n owner: 'DMH',\n category: 'Vendor Not Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: PO Not Found / Invalid PO\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('po details not found') ||\n cb.includes('not valid!!!') ||\n cb.includes('phrmcy') ||\n cb.includes('dmhmss') ||\n cb.includes('does not contain either') ||\n cb.includes('invalid purchase order') ||\n cb.includes('po not found') ||\n cb.includes('invalid po') ||\n cb.includes('purchase order not found')\n ) {\n\n return {\n owner: 'DMH',\n category: 'PO Not Found / Invalid PO Number',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Item Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing from item list') ||\n cb.includes('item_code') ||\n cb.includes('item_id') ||\n (\n cb.includes('batch') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n ) ||\n (\n cb.includes('quantity') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified item fields';\n\n return {\n owner: 'DMH',\n category:\n 'Item Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Header Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing') ||\n cb.includes('po_number') ||\n (\n cb.includes('invoice_amount') &&\n cb.includes('missing')\n ) ||\n (\n cb.includes('invoice_id') &&\n cb.includes('missing')\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified header fields';\n\n return {\n owner: 'DMH',\n category:\n 'Header Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: GSTIN / GST Mismatch\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('gstin mismatch') ||\n cb.includes('gst mismatch') ||\n cb.includes('gstin validation') ||\n cb.includes('invalid gstin')\n ) {\n\n return {\n owner: 'DMH',\n category: 'GSTIN Mismatch / Validation Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Fallback\n // ─────────────────────────────────────────────────────────────────────\n\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: raw\n };\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Build complete_error\n// ───────────────────────────────────────────────────────────────────────\n\nfunction buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n fallbackRaw\n) {\n\n const message =\n String(grnMsg || '').trim() ||\n String(fallbackRaw || '').trim() ||\n 'Unknown API error';\n\n const c = classifyError(\n message,\n fallbackRaw || '',\n missingCodes,\n invalidCodes\n );\n\n if (!c) {\n return '';\n }\n\n const divider =\n '─────────────────────────────────';\n\n const lines = [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + message\n ];\n\n return lines.join('\\n');\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Resolve messageId\n// ───────────────────────────────────────────────────────────────────────\n\nfunction resolveMessageId(item) {\n\n // Source 1\n try {\n\n const v =\n $('Set messageId Field1')\n .item\n .json\n .messageId;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 2\n try {\n\n const v =\n $('Switch2')\n .item\n .json\n .id;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 3\n if (\n item.json &&\n item.json.messageId\n ) {\n return String(item.json.messageId);\n }\n\n\n // Source 4\n if (\n item.json &&\n item.json.id\n ) {\n return String(item.json.id);\n }\n\n\n return '';\n}\n\n\n// ═══════════════════════════════════════════════════════════════════════\n// MAIN\n// ═══════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n // ─────────────────────────────────────────────────────────────────────\n // IST Timestamp\n // ─────────────────────────────────────────────────────────────────────\n\n const now = new Date();\n\n const date =\n now.toLocaleDateString(\n 'en-CA',\n {\n timeZone: 'Asia/Kolkata'\n }\n );\n\n const time =\n now.toLocaleTimeString(\n 'en-IN',\n {\n timeZone: 'Asia/Kolkata',\n hour12: true\n }\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // messageId\n // ─────────────────────────────────────────────────────────────────────\n\n const messageId =\n resolveMessageId(item);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN root object\n // ─────────────────────────────────────────────────────────────────────\n\n const grn =\n item.json || {};\n\n const httpStatus =\n grn.status;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Parse data\n // ─────────────────────────────────────────────────────────────────────\n\n const grnDataRaw =\n Array.isArray(grn.data) &&\n grn.data.length > 0\n ? grn.data[0]\n : null;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Build possible sources\n // ─────────────────────────────────────────────────────────────────────\n\n const sources = [];\n\n if (grnDataRaw !== null) {\n sources.push(grnDataRaw);\n }\n\n if (\n grn.data &&\n typeof grn.data === 'object'\n ) {\n sources.push(grn.data);\n }\n\n sources.push(grn);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Extract GRN data object\n // ─────────────────────────────────────────────────────────────────────\n\n let grnData = {};\n\n if (\n grnDataRaw &&\n typeof grnDataRaw === 'object' &&\n !Array.isArray(grnDataRaw)\n ) {\n\n grnData = grnDataRaw;\n\n } else if (\n grn.data &&\n typeof grn.data === 'object' &&\n !Array.isArray(grn.data)\n ) {\n\n grnData = grn.data;\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // NEW ROBUST MESSAGE EXTRACTION\n // ─────────────────────────────────────────────────────────────────────\n\n let grnMsg =\n extractErrorMessage(grnDataRaw);\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.data);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.message);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.error);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.detail);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.reason);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.description);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.statusText);\n }\n\n\n // Absolute fallback\n if (!grnMsg) {\n grnMsg = 'Unknown API error';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Missing / Invalid item codes\n // ─────────────────────────────────────────────────────────────────────\n\n const missingCodes =\n getArrayFromSources(\n sources,\n [\n 'missingItmesCodes',\n 'missingItemsCodes',\n 'missing_item_codes',\n 'missingItemCodes',\n 'missing_items',\n 'missingItems'\n ]\n );\n\n\n const invalidCodes =\n getArrayFromSources(\n sources,\n [\n 'invalidItmes',\n 'invalidItems',\n 'invalid_item_codes',\n 'invalidItemCodes',\n 'invalid_items'\n ]\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // HTTP status\n // ─────────────────────────────────────────────────────────────────────\n\n const http_status_code =\n typeof httpStatus === 'number'\n ? httpStatus\n : parseInt(httpStatus, 10) || 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN success\n // ─────────────────────────────────────────────────────────────────────\n\n const httpOk =\n http_status_code === 200;\n\n const grnOk =\n grnData.status === 0 ||\n grnData.status === '0';\n\n const grn_success =\n httpOk && grnOk;\n\n const status =\n grn_success\n ? '✅ SUCCESS'\n : '❌ FAILED';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Invoice fields\n // ─────────────────────────────────────────────────────────────────────\n\n let inv = {};\n\n try {\n\n inv =\n $('Normalize Invoice Fields2')\n .item\n .json || {};\n\n } catch (e) {\n\n inv = {};\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Attachment name\n // ─────────────────────────────────────────────────────────────────────\n\n let attachment_name = '';\n\n try {\n\n attachment_name =\n $('Split: One Item Per Attachment3')\n .item\n .json\n .attachment_name || '';\n\n } catch (e) {\n\n attachment_name = '';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Free Goods\n // ─────────────────────────────────────────────────────────────────────\n\n const invoiceItems =\n Array.isArray(inv.items)\n ? inv.items\n : [];\n\n const hasFreeGoods =\n invoiceItems.some(\n i =>\n String(\n i &&\n i.free_item_yn\n ) === '1'\n );\n\n const free_goods =\n hasFreeGoods\n ? 'Yes'\n : 'No';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Complete error\n // ─────────────────────────────────────────────────────────────────────\n\n let complete_error = '';\n\n\n if (grn_success) {\n\n const auditParts = [];\n\n if (grnData.grn_no) {\n auditParts.push(\n 'GRN No: ' +\n grnData.grn_no\n );\n }\n\n if (grnData.grn_master_id) {\n auditParts.push(\n 'GRN Master ID: ' +\n grnData.grn_master_id\n );\n }\n\n if (\n grnData.items_inserted !== undefined &&\n grnData.items_inserted !== null\n ) {\n auditParts.push(\n 'Items Inserted: ' +\n grnData.items_inserted\n );\n }\n\n if (grnData.vendor_id) {\n auditParts.push(\n 'Vendor ID: ' +\n grnData.vendor_id\n );\n }\n\n if (grnData.invoice_no) {\n auditParts.push(\n 'Invoice No (DMH): ' +\n grnData.invoice_no\n );\n }\n\n complete_error =\n auditParts.length\n ? auditParts.join(' | ')\n : '';\n\n } else {\n\n complete_error =\n buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n JSON.stringify(grn)\n );\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Output\n // ─────────────────────────────────────────────────────────────────────\n\n output.push({\n\n json: {\n\n // Timestamp\n date,\n time,\n\n\n // Invoice identity\n invoice_id:\n inv.invoice_id || '',\n\n invoice_number:\n inv.invoice_number || '',\n\n invoice_date:\n inv.invoice_date || '',\n\n seller_name:\n inv.seller_name || '',\n\n seller_gstin:\n inv.seller_gstin || '',\n\n customer_name:\n inv.customer_name || '',\n\n invoice_amount:\n inv.invoice_amount ?? 0,\n\n attachment_name,\n\n\n // GRN result\n status,\n\n grn_success,\n\n http_status_code,\n\n grn_message:\n grnMsg || 'Unknown API error',\n\n\n // Error detail\n complete_error,\n\n\n // Traceability\n free_goods,\n\n messageId\n }\n });\n\n});\n\n\nreturn output;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-672,
96
],
"id": "864137a6-b9cb-4e21-bcc2-1f2543d04fda",
"name": "Flatten Data for Log2",
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "list",
"cachedResultName": "Invoice_Tracker_NEW",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413"
},
"columns": {
"mappingMode": "defineBelow",
"value": {
"Date": "={{ $json.date }}",
"Time": "={{ $json.time }}",
"Status": "={{ $json.status }}",
"Complete Error / Null Values": "={{ $json.complete_error }}",
"Attachment Name": "={{ $('Wait 7s Before OCR2').item.json.attachment_name }}"
},
"matchingColumns": [],
"schema": [
{
"id": "Sr No.",
"displayName": "Sr No.",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Date",
"displayName": "Date",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Time",
"displayName": "Time",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Attachment Name",
"displayName": "Attachment Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Customer Name",
"displayName": "Customer Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice Amount (₹)",
"displayName": "Invoice Amount (₹)",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice ID",
"displayName": "Invoice ID",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Seller Name",
"displayName": "Seller Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Status",
"displayName": "Status",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "GRN Message ",
"displayName": "GRN Message ",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Seller GSTIN",
"displayName": "Seller GSTIN",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Free Goods",
"displayName": "Free Goods",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Complete Error / Null Values",
"displayName": "Complete Error / Null Values",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
}
],
"attemptToConvertTypes": false,
"convertFieldsToString": false
},
"options": {
"cellFormat": "USER_ENTERED",
"useAppend": true
}
},
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 4.7,
"position": [
-896,
384
],
"id": "b12ab90f-240b-4845-ac94-dada14ce001f",
"name": "Append row in sheet5",
"credentials": {
"googleSheetsOAuth2Api": {
"id": "OGnPiaQp3eu9tWvW",
"name": "Google Sheets account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"jsCode": "// ═══════════════════════════════════════════════════════════════\n// Flatten AI Classification Error for Log\n// Placed BEFORE: Append row in sheet1\n// Receives: Switch2 → error route (classification = \"error\")\n//\n// This fires when the AI provider completely fails to classify\n// the email — API down, quota hit, empty response, parse failure.\n//\n// Uses IDENTICAL complete_error format as Flatten Data for Log2:\n// Error Type : API Blocked — Project Suspended (403)\n// Error From : [AI INDIA]\n// ─────────────────────────────────\n// Raw API error : AGENT_ERROR: 403 PERMISSION_DENIED...\n//\n// NOTE: Category labels are intentionally generic (\"API Error...\")\n// and do NOT mention the underlying provider name (e.g. Gemini)\n// in the output. The raw error text in \"Raw API error\" is left\n// untouched since that's just the upstream message, not a label.\n// ═══════════════════════════════════════════════════════════════\n\n// ── Error classifier ──────────────────────────────────────────\nfunction classifyAIError(errorDetail) {\n const text = String(errorDetail || '');\n const cb = text.toLowerCase();\n\n function hasCode(code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(text);\n }\n\n // 403 Lightning Dunning (most specific — before generic 403)\n if (hasCode(403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Project Suspended (403)' };\n\n // 403 / 401 / Permission denied\n if (hasCode(403) || hasCode(401) || cb.includes('permission_denied') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Permission Denied (403)' };\n\n // 429 / Quota / Rate limit\n if (hasCode(429) || cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('too many requests') || cb.includes('resource has been exhausted') ||\n cb.includes('generate_requests_per_model_per_day'))\n return { owner: 'AI INDIA', category: 'API Quota / Rate Limit (429)' };\n\n // 504 / Timeout\n if (hasCode(504) || cb.includes('gateway timeout') || cb.includes('etimedout') ||\n cb.includes('socket hang up') || cb.includes('300000ms') || cb.includes('deadline expired'))\n return { owner: 'AI INDIA', category: 'API Timeout (504)' };\n\n // 500 server error\n if (hasCode(500) || cb.includes('internal server error'))\n return { owner: 'AI INDIA', category: 'API Server Error (500)' };\n\n // Empty / no response\n if (cb.includes('empty_ai_response') || cb.includes('empty'))\n return { owner: 'AI INDIA', category: 'API Returned Empty Response' };\n\n // JSON / parse failure\n if (cb.includes('no_json_found') || cb.includes('parse_exception') ||\n cb.includes('json_parse_failed') || cb.includes('all_parse_attempts_failed'))\n return { owner: 'AI INDIA', category: 'API Response — JSON Parse Failed' };\n\n // Missing is_invoice field\n if (cb.includes('missing_is_invoice') || cb.includes('is_invoice_field_not_found'))\n return { owner: 'AI INDIA', category: 'API Response — Missing is_invoice Field' };\n\n // Agent-level error\n if (cb.includes('agent_error'))\n return { owner: 'AI INDIA', category: 'API Agent Error' };\n\n // Fallback\n return { owner: 'AI INDIA', category: 'AI Classification Error — Unclassified' };\n}\n\n// ── Build complete_error block ─────────────────────────────────\nfunction buildCompleteError(errorDetail) {\n const c = classifyAIError(errorDetail);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (errorDetail || '(no error detail)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ─────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ══════════════════════════════════════════════════════════════\n// MAIN\n// ══════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // IST Timestamp\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n const messageId = resolveMessageId(item);\n\n // Attachment name\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // Read CORRECT field set by Parse AI Output (not data.error!)\n const errorDetail = data.error_detail || data.error || 'AI_CLASSIFICATION_FAILED';\n const complete_error = buildCompleteError(errorDetail);\n\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (AI never got to OCR)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'AI Classification Failed — Invoice not processed',\n\n // Error block — same format as all other rows\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2016,
384
],
"id": "88f8d70f-f8b0-4462-bf46-478f26a507df",
"name": "Code in JavaScript6",
"onError": "continueRegularOutput"
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 3
},
"conditions": [
{
"leftValue": "={{ $json.classification }}",
"rightValue": "invoice",
"operator": {
"type": "string",
"operation": "equals"
},
"id": "a4a14d24-2846-4497-85b2-d76b08ee5f3f"
}
],
"combinator": "and"
}
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 3
},
"conditions": [
{
"id": "6e8cef57-3eb1-458e-a82c-82f914ff3ffb",
"leftValue": "={{ $json.classification }}",
"rightValue": "error",
"operator": {
"type": "string",
"operation": "equals"
}
}
],
"combinator": "and"
}
},
{
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 3
},
"conditions": [
{
"id": "d6db0eb2-e8fa-4b20-b475-6b78e2bbb39e",
"leftValue": "={{ $json.classification }}",
"rightValue": "not_invoice",
"operator": {
"type": "string",
"operation": "equals"
}
}
],
"combinator": "and"
}
}
]
},
"options": {
"fallbackOutput": "extra"
}
},
"type": "n8n-nodes-base.switch",
"typeVersion": 3.4,
"position": [
-2240,
288
],
"id": "334b80a6-4e59-44b6-a627-536fc65ea1cd",
"name": "Switch2"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Failed",
"cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [
0,
288
],
"id": "6ee14313-3f3a-447e-a7d5-cf15a29f972b",
"name": "Failed To add2",
"webhookId": "0d4c72df-2457-4462-aa2f-b53949022df8",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"model": "openai/gpt-oss-120b",
"options": {}
},
"type": "@n8n/n8n-nodes-langchain.lmChatGroq",
"typeVersion": 1,
"position": [
-3360,
1184
],
"id": "69adb603-b839-49a8-a652-79c28fc2dcdb",
"name": "Groq Chat Model1",
"credentials": {
"groqApi": {
"id": "5STjMY6aZDMipq2f",
"name": "Groq account"
}
}
},
{
"parameters": {
"jsCode": "// ─── Filter: Skip Non-OCR-able Files ─────────────────────────────\n// Allows ONLY PDF, image, and CSV attachments to reach the next node.\n// Other files (DOCX, TXT, EML etc.) are dropped silently.\n// An empty output from this node = no call generated = safe no-op.\n// ──────────────────────────────────────────────────────────────────────\nconst ALLOWED_MIME_TYPES = [\n 'application/pdf',\n 'image/jpeg',\n 'image/jpg',\n 'image/png',\n 'image/tiff',\n 'image/webp',\n 'image/bmp',\n 'image/gif',\n 'text/csv', // ← added\n 'application/csv' // ← added (some systems send this for .csv)\n];\nconst ALLOWED_EXTENSIONS = [\n '.pdf', '.jpg', '.jpeg', '.png',\n '.tiff', '.tif', '.webp', '.bmp', '.gif',\n '.csv' // ← added\n];\nconst filtered = items.filter(item => {\n const binary = item.binary?.file;\n // ── No binary at all → skip (text-only email path) ──────────────\n if (!binary) {\n return false;\n }\n const mimeType = (binary.mimeType || '').toLowerCase();\n const fileName = (binary.fileName || item.json.attachment_name || '').toLowerCase();\n const lastDot = fileName.lastIndexOf('.');\n const ext = lastDot !== -1 ? fileName.slice(lastDot) : '';\n const isAllowedMime = ALLOWED_MIME_TYPES.some(m => mimeType.includes(m));\n const isAllowedExt = ALLOWED_EXTENSIONS.includes(ext);\n if (!isAllowedMime && !isAllowedExt) {\n console.log('[OCR-FILTER] BLOCKED | file: ' + (binary.fileName || 'unknown') + ' | mime: ' + (mimeType || 'none') + ' | ext: ' + (ext || 'none') + ' | Reason: not PDF, image, or CSV format');\n return false;\n }\n return true;\n});\n// Return empty array cleanly if nothing passes the filter\nreturn filtered;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-2016,
192
],
"id": "90bed578-8c62-4c6b-a1d3-e10639a0f051",
"name": "Filter: Skip Non-OCR-able Files",
"disabled": true,
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "list",
"cachedResultName": "Invoice_Tracker_NEW",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs",
"cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413"
},
"columns": {
"mappingMode": "defineBelow",
"value": {
"Date": "={{ $json.date }}",
"Time": "={{ $json.time }}",
"Attachment Name": "={{ $json.attachment_name }}",
"Invoice ID": "={{ $json.invoice_id }}",
"Customer Name": "={{ $json.customer_name }}",
"Invoice Amount (₹)": "={{ $json.invoice_amount }}",
"Seller Name": "={{ $json.seller_name }}",
"Status": "={{ $json.status }}",
"GRN Message ": "={{ $json.grn_message }}",
"Seller GSTIN": "={{ $json.seller_gstin }}",
"Free Goods": "={{ $json.free_goods }}",
"Complete Error / Null Values": "={{ $json.complete_error }}"
},
"matchingColumns": [],
"schema": [
{
"id": "Sr No.",
"displayName": "Sr No.",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true,
"removed": false
},
{
"id": "Date",
"displayName": "Date",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Time",
"displayName": "Time",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Attachment Name",
"displayName": "Attachment Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Customer Name",
"displayName": "Customer Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice Amount (₹)",
"displayName": "Invoice Amount (₹)",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Invoice ID",
"displayName": "Invoice ID",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller Name",
"displayName": "Seller Name",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Status",
"displayName": "Status",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "GRN Message ",
"displayName": "GRN Message ",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Seller GSTIN",
"displayName": "Seller GSTIN",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Free Goods",
"displayName": "Free Goods",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
},
{
"id": "Complete Error / Null Values",
"displayName": "Complete Error / Null Values",
"required": false,
"defaultMatch": false,
"display": true,
"type": "string",
"canBeUsedToMatch": true
}
],
"attemptToConvertTypes": false,
"convertFieldsToString": false
},
"options": {}
},
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 4.7,
"position": [
-448,
96
],
"id": "54fc0189-5a1a-402b-93a0-9f575f730f32",
"name": "Log to Google Sheets (Daily Logs)2",
"retryOnFail": false,
"maxTries": 3,
"credentials": {
"googleSheetsOAuth2Api": {
"id": "OGnPiaQp3eu9tWvW",
"name": "Google Sheets account"
}
}
},
{
"parameters": {
"options": {
"temperature": 0.4
}
},
"type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
"typeVersion": 1,
"position": [
-3488,
1184
],
"id": "5b645a7b-acc2-46f6-88e5-82d8d79a8986",
"name": "Google Gemini Chat Model",
"credentials": {
"googlePalmApi": {
"id": "8wBnH32SbKmjkfYp",
"name": "Google Gemini(PaLM) Api account"
}
}
},
{
"parameters": {
"jsCode": "// ═══════════════════════════════════════════════════════════════════\n// Flatten OCR Error for Log\n// Placed BEFORE: Append row in sheet5\n// Receives: OCR Extraction Valid?2 → FALSE branch\n//\n// Produces the SAME complete_error format as Flatten Data for Log2:\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\n// Correctly classifies all OCR errors including:\n// 403 PERMISSION_DENIED → AI INDIA (Server Issue)\n// 400 Invalid file type → DMH\n// 504 Gateway Timeout → AI INDIA\n// 500 Server Crash → AI INDIA\n// PIL image error → AI INDIA\n// PO number missing → DMH\n// Duplicate Invoice → DMH\n// ═══════════════════════════════════════════════════════════════════\n\n// ── Helper: safe word-boundary HTTP status code check ────────────\n// Prevents \"400\" matching \"14005\" or UNKNOWN_ERROR400 from the prefix\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(String(text || ''));\n}\n\n// ── Error classifier ───────────────────────────────────────────────\n// Returns: { owner: \"AI INDIA\"|\"DMH\", category: string, detail: string }\nfunction classifyError(rawError) {\n const text = String(rawError || '');\n const cb = text.toLowerCase();\n const raw = text.trim();\n\n if (!cb.trim()) return { owner: 'AI INDIA', category: 'Unknown OCR Error', detail: '(no error message)' };\n\n // ── DMH: Invalid File Type (400) ───────────────────────────────\n // File format not accepted — DMH responsibility\n if (hasHttpCode(text, 400) && cb.includes('invalid file type'))\n return { owner: 'DMH', category: 'Invalid File Type (400)', detail: raw };\n\n // ── DMH: PO Number Missing ──────────────────────────────────────\n // Invoice rejected due to missing PO — DMH responsibility\n if (cb.includes('po number') || cb.includes('po number is missing') ||\n cb.includes('invoice rejected') || cb.includes('valid po number'))\n return { owner: 'DMH', category: 'Invoice Rejected — PO Number Missing', detail: raw };\n\n // ── DMH: Duplicate Invoice ──────────────────────────────────────\n if (cb.includes('duplicate invoice') || cb.includes('already processed') ||\n cb.includes('already exists'))\n return { owner: 'DMH', category: 'Duplicate Invoice', detail: raw };\n\n // ── AI INDIA: Server Issue (Lightning Dunning) ──────────────────\n // Most specific 403 check — must come BEFORE generic 403\n if (hasHttpCode(text, 403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Server Issue (403)', detail: raw };\n\n // ── AI INDIA: Server Issue Permission Denied / Quota / Auth ────\n if (hasHttpCode(text, 403) || hasHttpCode(text, 401) || hasHttpCode(text, 429) ||\n cb.includes('permission_denied') ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('resource has been exhausted') ||\n cb.includes('unauthorized') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Error — Server Issue', detail: raw };\n\n // ── AI INDIA: Generic 400 Bad Request ──────────────────────────\n if (hasHttpCode(text, 400))\n return { owner: 'AI INDIA', category: 'Bad Request to OCR API (400)', detail: raw };\n\n // ── AI INDIA: Timeout / Gateway ────────────────────────────────\n if (hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') || cb.includes('gateway timeout') ||\n cb.includes('etimedout') || cb.includes('econnrefused') ||\n cb.includes('socket hang up') || cb.includes('300000ms') ||\n cb.includes('deadline expired') || cb.includes('connect timeout') ||\n cb.includes('read timeout'))\n return { owner: 'AI INDIA', category: 'OCR API Timeout / Gateway Error (504)', detail: raw };\n\n // ── AI INDIA: File Too Large (413) ─────────────────────────────\n if (hasHttpCode(text, 413) || cb.includes('request entity too large') ||\n cb.includes('payload too large') || cb.includes('file size exceeds'))\n return { owner: 'AI INDIA', category: 'File Too Large (413)', detail: raw };\n\n // ── AI INDIA: Server Crash (500) ───────────────────────────────\n if (hasHttpCode(text, 500) &&\n (cb.includes('internal server error') || cb.includes('nginx') ||\n cb.includes('werkzeug') || cb.includes('traceback')))\n return { owner: 'AI INDIA', category: 'OCR Server Internal Crash (500)', detail: raw };\n\n // ── AI INDIA: Invalid Image Format (PIL) ───────────────────────\n if (cb.includes('pil') || cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') || cb.includes('image file is truncated'))\n return { owner: 'AI INDIA', category: 'Invalid Image Format (PIL Error)', detail: raw };\n\n // ── AI INDIA: No Binary File ────────────────────────────────────\n if ((cb.includes('binary file') && cb.includes('none was found')) ||\n cb.includes('no file was uploaded') || cb.includes('missing file attachment'))\n return { owner: 'AI INDIA', category: 'No Binary File Found', detail: raw };\n\n // ── AI INDIA: OCR Extraction Failed ────────────────────────────\n if (cb.includes('ocr extraction failed') || cb.includes('extraction failed') ||\n cb.includes('could not extract') || cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') || cb.includes('pdf parse') ||\n cb.includes('unknown processing error'))\n return { owner: 'AI INDIA', category: 'OCR Extraction Failed', detail: raw };\n\n // ── AI INDIA: OCR — Missing invoice_number (validation fail) ───\n if (cb.includes('invoice_number') || cb.includes('invoice number'))\n return { owner: 'AI INDIA', category: 'OCR — invoice_number Missing or Empty', detail: raw };\n\n // ── Fallback ────────────────────────────────────────────────────\n return { owner: 'AI INDIA', category: 'OCR Error — Unclassified', detail: raw };\n}\n\n// ── Build complete_error block ──────────────────────────────────────\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\nfunction buildCompleteError(rawError) {\n const c = classifyError(rawError);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (c.detail || '(no raw message)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ──────────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ── Normalize raw error from item.json.error ───────────────────────\nfunction extractRawError(data) {\n if (!data.error) return '(no error message)';\n if (typeof data.error === 'string') return data.error;\n if (typeof data.error === 'object') {\n return data.error.message || data.error.description || JSON.stringify(data.error);\n }\n return String(data.error);\n}\n\n// ════════════════════════════════════════════════════════════════════\n// MAIN\n// ════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // ── IST Timestamp ──────────────────────────────────────────────\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n // ── messageId ──────────────────────────────────────────────────\n const messageId = resolveMessageId(item);\n\n // ── Attachment name ────────────────────────────────────────────\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // ── Build error string ─────────────────────────────────────────\n const rawError = extractRawError(data);\n const complete_error = buildCompleteError(rawError);\n\n // ── Output — SAME columns as main sheet ───────────────────────\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (OCR failed, nothing extracted)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'OCR Extraction Failed — Server Issue — Invoice not processed',\n\n // Error block\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
-1120,
384
],
"id": "6402173a-44c3-4233-b394-0581d4f47f89",
"name": "Flatten OCR Error for Log",
"onError": "continueRegularOutput"
}
],
"connections": {
"Append row in sheet1": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Watch New_Invoice Label1": {
"main": [
[
{
"node": "Fetch Emails from New_Invoice (max 3)1",
"type": "main",
"index": 0
}
]
]
},
"AI: Classify Invoice1": {
"main": [
[
{
"node": "Merge: Email + AI Classification1",
"type": "main",
"index": 1
}
]
]
},
"OCR: Extract Invoice Data2": {
"main": [
[
{
"node": "OCR Extraction Valid?2",
"type": "main",
"index": 0
}
]
]
},
"Merge: Email + AI Classification1": {
"main": [
[
{
"node": "Split: One Item Per Attachment3",
"type": "main",
"index": 0
}
]
]
},
"Fetch Emails from New_Invoice (max 3)1": {
"main": [
[
{
"node": "Loop: Each Email2",
"type": "main",
"index": 0
}
]
]
},
"Loop: Each Email2": {
"main": [
[
{
"node": "Label: Add Processing2",
"type": "main",
"index": 0
}
],
[
{
"node": "End: No More Emails1",
"type": "main",
"index": 0
}
]
]
},
"End: No More Emails1": {
"main": [
[
{
"node": "Loop: Each Email2",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Processing2": {
"main": [
[
{
"node": "Label: Remove New_Invoice1",
"type": "main",
"index": 0
}
]
]
},
"Label: Remove New_Invoice1": {
"main": [
[
{
"node": "Fetch Full Email + Attachments2",
"type": "main",
"index": 0
}
]
]
},
"Fetch Full Email + Attachments2": {
"main": [
[
{
"node": "Set messageId Field1",
"type": "main",
"index": 0
},
{
"node": "AI: Classify Invoice1",
"type": "main",
"index": 0
}
]
]
},
"Parse AI Output2": {
"main": [
[
{
"node": "Switch2",
"type": "main",
"index": 0
}
]
]
},
"Set messageId Field1": {
"main": [
[
{
"node": "Merge: Email + AI Classification1",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Not_Invoice2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Invoice_Done2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Label: Add Invoice_failed2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"OCR Extraction Valid?2": {
"main": [
[
{
"node": "Normalize Invoice Fields2",
"type": "main",
"index": 0
}
],
[
{
"node": "Flatten OCR Error for Log",
"type": "main",
"index": 0
}
]
]
},
"GRN: Create Record in Hospital2": {
"main": [
[
{
"node": "Flatten Data for Log2",
"type": "main",
"index": 0
}
]
]
},
"Normalize Invoice Fields2": {
"main": [
[
{
"node": "GRN: Create Record in Hospital2",
"type": "main",
"index": 0
}
]
]
},
"GRN Created Successfully?2": {
"main": [
[
{
"node": "Label: Add Invoice_Done2",
"type": "main",
"index": 0
}
],
[
{
"node": "Failed To add2",
"type": "main",
"index": 0
}
]
]
},
"Split: One Item Per Attachment3": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Loop: Each Attachment2": {
"main": [
[],
[
{
"node": "Parse AI Output2",
"type": "main",
"index": 0
}
]
]
},
"Wait 7s Before OCR2": {
"main": [
[
{
"node": "OCR: Extract Invoice Data2",
"type": "main",
"index": 0
}
]
]
},
"Flatten Data for Log2": {
"main": [
[
{
"node": "Log to Google Sheets (Daily Logs)2",
"type": "main",
"index": 0
}
]
]
},
"Append row in sheet5": {
"main": [
[
{
"node": "Label: Add Invoice_failed2",
"type": "main",
"index": 0
}
]
]
},
"Code in JavaScript6": {
"main": [
[
{
"node": "Append row in sheet1",
"type": "main",
"index": 0
}
]
]
},
"Switch2": {
"main": [
[
{
"node": "Filter: Skip Non-OCR-able Files",
"type": "main",
"index": 0
}
],
[
{
"node": "Code in JavaScript6",
"type": "main",
"index": 0
}
],
[
{
"node": "Label: Add Not_Invoice2",
"type": "main",
"index": 0
}
],
[
{
"node": "Code in JavaScript6",
"type": "main",
"index": 0
}
]
]
},
"Filter: Skip Non-OCR-able Files": {
"main": [
[
{
"node": "Wait 7s Before OCR2",
"type": "main",
"index": 0
}
]
]
},
"Failed To add2": {
"main": [
[
{
"node": "Loop: Each Attachment2",
"type": "main",
"index": 0
}
]
]
},
"Groq Chat Model1": {
"ai_languageModel": [
[
{
"node": "AI: Classify Invoice1",
"type": "ai_languageModel",
"index": 1
}
]
]
},
"Log to Google Sheets (Daily Logs)2": {
"main": [
[
{
"node": "GRN Created Successfully?2",
"type": "main",
"index": 0
}
]
]
},
"Google Gemini Chat Model": {
"ai_languageModel": [
[
{
"node": "AI: Classify Invoice1",
"type": "ai_languageModel",
"index": 0
}
]
]
},
"Flatten OCR Error for Log": {
"main": [
[
{
"node": "Append row in sheet5",
"type": "main",
"index": 0
}
]
]
}
},
"nodeGroups": [],
"authors": "Invoice Aiindia",
"name": "Version e33393f4",
"description": "",
"autosaved": true,
"workflowPublishHistory": [
{
"createdAt": "2026-10-10T10:33:00.631Z",
"id": 35,
"workflowId": "EyAw3kSLbeIEnpyf",
"versionId": "e33393f4-a186-4ea6-8ab3-61c482ec228f",
"event": "activated",
"userId": "9f578e99-f4de-457a-8344-b8c82fadc25d"
}
]
},
"scopes": [
"execution:reveal",
"workflow:create",
"workflow:delete",
"workflow:disableRedaction",
"workflow:enableRedaction",
"workflow:execute",
"workflow:execute-chat",
"workflow:export",
"workflow:import",
"workflow:list",
"workflow:move",
"workflow:publish",
"workflow:read",
"workflow:share",
"workflow:unpublish",
"workflow:unshare",
"workflow:update"
],
"checksum": "7c94d68081bd1bfd43b80829df06849c5f0e7c71004c5ba0492cdbd91f5c1b59"
}