Files
aiinvoice_pharmacyDashboard/n8n_invoice_automation_workflow.json
T

878 lines
45 KiB
JSON

{
"name": "Invoice Automation-DMH Hospital LOCAL TEST",
"nodes": [
{
"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": {
"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,
"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"
}
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [-4160, 912],
"id": "aaab2e62-0622-4bbd-b3d1-648fcb06b290",
"name": "Label: Add Processing2",
"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"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [-3936, 912],
"id": "584c67c7-ff4d-4b72-8a91-a94fe1c6ad4b",
"name": "Label: Remove New_Invoice1",
"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",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
}
},
{
"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": {
"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,
"retryOnFail": true,
"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": {
"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 const attachment_name = binaries[key].fileName || '';\n\n newItems.push({\n json: {\n ...item.json,\n attachment_name: attachment_name\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: ''\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": {
"jsCode": "// Parse AI classification output — full production-grade parser\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 if (item.json.error) {\n const errStr = typeof item.json.error === 'object' ? (item.json.error.message || JSON.stringify(item.json.error)) : String(item.json.error);\n error_detail = 'AGENT_ERROR: ' + errStr.slice(0, 300);\n classification = 'error';\n return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary };\n }\n\n const FIELD_PATHS = ['output', 'text', 'content', 'message', 'result', 'response'];\n let raw = null;\n let parsed = null;\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 if (item.json.is_invoice !== undefined) { parsed = item.json; raw = null; }\n else { error_detail = 'NO_OUTPUT_FIELD'; classification = 'error'; return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary }; }\n }\n\n if (parsed === null && raw !== null) {\n if (Array.isArray(raw)) raw = raw[0];\n if (raw !== null && typeof raw === 'object') {\n if (raw.kwargs && raw.kwargs.content !== undefined) { raw = raw.kwargs.content; }\n else if (raw.output !== undefined) { raw = raw.output; if (raw !== null && typeof raw === 'object') { parsed = raw; raw = null; } }\n else { parsed = raw; raw = null; }\n }\n }\n\n if (parsed === null && raw !== null) {\n let cleaned = String(raw).replace(/\\uFEFF/g, '').replace(/```json\\s*/gi, '').replace(/```\\s*/g, '').trim();\n try { const r = JSON.parse(cleaned); if (r && typeof r === 'object' && !Array.isArray(r)) parsed = r; } catch(e) {}\n if (!parsed) {\n const m = cleaned.match(/\"is_invoice\"\\s*:\\s*(true|false)/i);\n if (m) parsed = { is_invoice: m[1] === 'true', confidence: 'low', reason: '' };\n }\n if (!parsed) { error_detail = 'PARSE_FAILED: ' + cleaned.slice(0, 200); classification = 'error'; return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary }; }\n }\n\n if (parsed) {\n const rawFlag = parsed.is_invoice !== undefined ? parsed.is_invoice : (parsed.isInvoice !== undefined ? parsed.isInvoice : undefined);\n if (rawFlag === undefined) { error_detail = 'IS_INVOICE_NOT_FOUND'; classification = 'error'; }\n else {\n const flag = String(rawFlag).toLowerCase().trim();\n if (['true','1','yes'].includes(flag)) classification = 'invoice';\n else if (['false','0','no'].includes(flag)) classification = 'not_invoice';\n else { error_detail = 'UNEXPECTED_VALUE: ' + rawFlag; classification = 'error'; }\n }\n const rawConf = String(parsed.confidence || 'low').toLowerCase();\n if (['high','certain','definite'].some(v => rawConf.includes(v))) confidence = 'high';\n else if (['medium','moderate','likely'].some(v => rawConf.includes(v))) confidence = 'medium';\n else confidence = 'low';\n ai_reason = String(parsed.reason || parsed.explanation || '').slice(0, 500);\n }\n\n } catch (e) { error_detail = 'UNCAUGHT: ' + e.message; classification = 'error'; }\n\n return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary };\n});"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [-2464, 320],
"id": "e76f2124-e8b2-4b52-86c5-0ab65b6068cf",
"name": "Parse AI Output2",
"alwaysOutputData": true
},
{
"parameters": {
"rules": {
"values": [
{
"conditions": {
"conditions": [{ "leftValue": "={{ $json.classification }}", "rightValue": "invoice", "operator": { "type": "string", "operation": "equals" } }],
"combinator": "and"
}
},
{
"conditions": {
"conditions": [{ "id": "err", "leftValue": "={{ $json.classification }}", "rightValue": "error", "operator": { "type": "string", "operation": "equals" } }],
"combinator": "and"
}
},
{
"conditions": {
"conditions": [{ "id": "ni", "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": {
"amount": 1
},
"type": "n8n-nodes-base.wait",
"typeVersion": 1.1,
"position": [-1792, 192],
"id": "dab6bfb7-215a-4ccd-8964-333200305739",
"name": "Wait 7s Before OCR2"
},
{
"parameters": {
"method": "POST",
"url": "=http://localhost:{{ $env.LOCAL_APP_PORT || 8080 }}/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"
},
{
"name": "messageId",
"value": "={{ $('Set messageId Field1').item.json.messageId }}"
},
{
"name": "attachment_name",
"value": "={{ $('Split: One Item Per Attachment3').item.json.attachment_name }}"
}
]
},
"options": {}
},
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [-1568, 192],
"id": "bc668542-9d9c-4096-9750-777b7012a29b",
"name": "OCR: Extract Invoice Data2 [LOCAL]",
"alwaysOutputData": false,
"retryOnFail": true,
"waitBetweenTries": 5000,
"maxTries": 3,
"onError": "continueRegularOutput"
},
{
"parameters": {
"conditions": {
"conditions": [
{
"id": "valid-ocr",
"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": {
"jsCode": "function cleanNumber(val) {\n if (val === null || val === undefined) return 0;\n return Number(val.toString().replace(/[^\\d.-]/g, '')) || 0;\n}\n\nreturn items.map(item => {\n const inv = item.json;\n\n return {\n json: {\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 invoice_amount: cleanNumber(inv.invoice_amount),\n currency_code: inv.currency_code ?? 'INR',\n seller_gstin: inv.seller_gstin ?? '',\n customer_name: inv.customer_name ?? '',\n customer_gstin: '27AAATL1944N1ZA',\n dc_date: inv.DC_date ?? '',\n dc_number: inv.DC_number ?? '',\n round_off: cleanNumber(inv.round_off),\n total_gst_rate: cleanNumber(inv.total_gst_rate),\n total_quantity: cleanNumber(inv.total_quantity),\n total_cgst_rate: cleanNumber(inv.total_cgst_rate),\n total_cgst_amount: cleanNumber(inv.total_cgst_amount),\n total_sgst_rate: cleanNumber(inv.total_sgst_rate),\n total_sgst_amount: cleanNumber(inv.total_sgst_amount),\n total_igst_rate: cleanNumber(inv.total_igst_rate),\n total_igst_amount: cleanNumber(inv.total_igst_amount),\n total_gst_amount: cleanNumber(inv.total_gst_amount),\n items: (inv.items ?? []).map(i => ({\n item_code: i.item_code ?? '',\n Batch: i.Batch ?? '',\n quantity: cleanNumber(i.quantity),\n free_item_yn: cleanNumber(i.free_item_yn),\n unit_price: cleanNumber(i.unit_price),\n total_price: cleanNumber(i.total_price),\n Discount: cleanNumber(i.Discount),\n MRP: cleanNumber(i.MRP),\n description: i.description ?? '',\n Pack: i.Pack ?? '',\n hsn_sac: i.hsn_sac ?? '',\n expiry_date: i.expiry_date ?? '',\n cgst_rate: cleanNumber(i.cgst_rate),\n cgst_amount: cleanNumber(i.cgst_amount),\n sgst_rate: cleanNumber(i.sgst_rate),\n sgst_amount: cleanNumber(i.sgst_amount),\n igst_rate: cleanNumber(i.igst_rate),\n igst_amount: cleanNumber(i.igst_amount),\n GST_AMT: cleanNumber(i.GST_AMT),\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});"
},
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [-1120, 96],
"id": "6f82a7b4-9dbf-4e9c-a6c4-6a4a52efc6e3",
"name": "Normalize Invoice Fields2"
},
{
"parameters": {
"method": "POST",
"url": "=http://localhost:{{ $env.LOCAL_APP_PORT || 8080 }}/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 [LOCAL]",
"retryOnFail": false,
"onError": "continueRegularOutput"
},
{
"parameters": {
"jsCode": "// Flatten GRN result + build complete_error identical to production\nfunction safeText(value) {\n if (value === null || value === undefined) return '';\n if (typeof value === 'string') return value.trim();\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return value.map(v => safeText(v)).filter(Boolean).join(' | ');\n if (typeof value === 'object') {\n for (const key of ['message','error','detail','reason','description','statusText']) {\n if (value[key] !== undefined && value[key] !== null) { const r = safeText(value[key]); if (r) return r; }\n }\n try { return JSON.stringify(value); } catch(e) { return ''; }\n }\n return '';\n}\n\nconst output = [];\n\nitems.forEach(item => {\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 let messageId = '';\n try { messageId = $('Set messageId Field1').item.json.messageId || ''; } catch(e) {}\n\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n\n const grn = item.json || {};\n const http_status_code = typeof grn.status === 'number' ? grn.status : parseInt(grn.status, 10) || 0;\n const grnDataRaw = Array.isArray(grn.data) && grn.data.length > 0 ? grn.data[0] : null;\n const grnData = (grnDataRaw && typeof grnDataRaw === 'object' && !Array.isArray(grnDataRaw)) ? grnDataRaw : (grn.data && typeof grn.data === 'object' && !Array.isArray(grn.data) ? grn.data : {});\n\n let grnMsg = safeText(grnDataRaw) || safeText(grn.data) || safeText(grn.message) || safeText(grn.error) || 'Unknown API error';\n\n const httpOk = http_status_code === 200;\n const grnOk = grnData.status === 0 || grnData.status === '0';\n const grn_success = httpOk && grnOk;\n\n let inv = {};\n try { inv = $('Normalize Invoice Fields2').item.json || {}; } catch(e) {}\n\n const invoiceItems = Array.isArray(inv.items) ? inv.items : [];\n const hasFreeGoods = invoiceItems.some(i => String(i && i.free_item_yn) === '1');\n\n let complete_error = '';\n if (grn_success) {\n const parts = [];\n if (grnData.grn_no) parts.push('GRN No: ' + grnData.grn_no);\n if (grnData.grn_master_id) parts.push('GRN Master ID: ' + grnData.grn_master_id);\n if (grnData.items_inserted !== undefined) parts.push('Items Inserted: ' + grnData.items_inserted);\n if (grnData.vendor_id) parts.push('Vendor ID: ' + grnData.vendor_id);\n if (grnData.invoice_no) parts.push('Invoice No (DMH): ' + grnData.invoice_no);\n complete_error = parts.join(' | ');\n } else {\n complete_error = 'Error Type : GRN Creation Failed\\nError From : [LOCAL DMH]\\n─────────────────────────────────\\nRaw API error : ' + (grnMsg || 'Unknown error');\n }\n\n output.push({\n json: {\n date,\n time,\n invoice_id: inv.invoice_id || '',\n invoice_number: inv.invoice_number || '',\n invoice_date: inv.invoice_date || '',\n seller_name: inv.seller_name || '',\n seller_gstin: inv.seller_gstin || '',\n customer_name: inv.customer_name || '',\n invoice_amount: inv.invoice_amount ?? 0,\n attachment_name,\n status: grn_success ? '✅ SUCCESS' : '❌ FAILED',\n grn_success,\n http_status_code,\n grn_message: grnMsg || 'Unknown API error',\n complete_error,\n free_goods: hasFreeGoods ? 'Yes' : 'No',\n messageId,\n grn_no: grnData.grn_no || '',\n grn_master_id: grnData.grn_master_id || '',\n items_inserted: grnData.items_inserted || 0\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": {
"conditions": {
"conditions": [
{
"id": "grn-ok",
"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": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "id"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs"
},
"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.", "type": "string", "canBeUsedToMatch": true },
{ "id": "Date", "displayName": "Date", "type": "string", "canBeUsedToMatch": true },
{ "id": "Time", "displayName": "Time", "type": "string", "canBeUsedToMatch": true },
{ "id": "Attachment Name", "displayName": "Attachment Name", "type": "string", "canBeUsedToMatch": true },
{ "id": "Customer Name", "displayName": "Customer Name", "type": "string", "canBeUsedToMatch": true },
{ "id": "Invoice Amount (₹)", "displayName": "Invoice Amount (₹)", "type": "string", "canBeUsedToMatch": true },
{ "id": "Invoice ID", "displayName": "Invoice ID", "type": "string", "canBeUsedToMatch": true },
{ "id": "Seller Name", "displayName": "Seller Name", "type": "string", "canBeUsedToMatch": true },
{ "id": "Status", "displayName": "Status", "type": "string", "canBeUsedToMatch": true },
{ "id": "GRN Message ", "displayName": "GRN Message ", "type": "string", "canBeUsedToMatch": true },
{ "id": "Seller GSTIN", "displayName": "Seller GSTIN", "type": "string", "canBeUsedToMatch": true },
{ "id": "Free Goods", "displayName": "Free Goods", "type": "string", "canBeUsedToMatch": true },
{ "id": "Complete Error / Null Values", "displayName": "Complete Error / Null Values", "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",
"credentials": {
"googleSheetsOAuth2Api": {
"id": "OGnPiaQp3eu9tWvW",
"name": "Google Sheets account"
}
}
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Sucess"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [0, 0],
"id": "bf5b1548-e75b-40d4-9b2d-a534708db65e",
"name": "Label: Add Invoice_Done2",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==",
"mode": "list",
"cachedResultName": "Invoice_Failed"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [0, 288],
"id": "6ee14313-3f3a-447e-a7d5-cf15a29f972b",
"name": "Failed To add2",
"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"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [-672, 384],
"id": "651c1889-e980-4870-a309-35e23ea51aed",
"name": "Label: Add Invoice_failed2",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"operation": "move",
"messageId": "={{ $json.messageId }}",
"folderId": {
"__rl": true,
"value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA==",
"mode": "list",
"cachedResultName": "Not_invoice"
}
},
"type": "n8n-nodes-base.microsoftOutlook",
"typeVersion": 2,
"position": [-2016, 576],
"id": "0c59ac0e-ca75-45bd-b731-3aae0faed96f",
"name": "Label: Add Not_Invoice2",
"credentials": {
"microsoftOutlookOAuth2Api": {
"id": "neYqnH7A2WPe5lTs",
"name": "Microsoft Outlook account"
}
},
"onError": "continueRegularOutput"
},
{
"parameters": {
"jsCode": "// Flatten OCR error — same format as production\nconst output = [];\nitems.forEach(item => {\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 let messageId = '';\n try { messageId = $('Set messageId Field1').item.json.messageId || ''; } catch(e) {}\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n const data = item.json;\n const rawError = data.error ? (typeof data.error === 'string' ? data.error : (data.error.message || JSON.stringify(data.error))) : '(no error message)';\n output.push({\n json: {\n date, time,\n invoice_id: '', invoice_number: '', invoice_date: '',\n seller_name: '', seller_gstin: '', customer_name: '',\n invoice_amount: 0, attachment_name,\n status: '❌ FAILED',\n grn_message: 'OCR Extraction Failed — Invoice not processed',\n complete_error: 'Error Type : OCR Extraction Failed\\nError From : [AI INDIA]\\n─────────────────────────────────\\nRaw API error : ' + rawError,\n free_goods: 'No',\n messageId\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"
},
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "id"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs"
},
"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": "Date", "displayName": "Date", "type": "string" },
{ "id": "Time", "displayName": "Time", "type": "string" },
{ "id": "Attachment Name", "displayName": "Attachment Name", "type": "string" },
{ "id": "Status", "displayName": "Status", "type": "string" },
{ "id": "Complete Error / Null Values","displayName": "Complete Error / Null Values","type": "string" }
]
},
"options": {}
},
"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": "// Flatten AI classification error\nconst output = [];\nitems.forEach(item => {\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 let messageId = '';\n try { messageId = $('Set messageId Field1').item.json.messageId || ''; } catch(e) {}\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n const errorDetail = item.json.error_detail || item.json.error || 'AI_CLASSIFICATION_FAILED';\n output.push({\n json: {\n date, time,\n invoice_id: '', invoice_number: '', invoice_date: '',\n seller_name: '', seller_gstin: '', customer_name: '',\n invoice_amount: 0, attachment_name,\n status: '❌ FAILED',\n grn_message: 'AI Classification Failed — Invoice not processed',\n complete_error: 'Error Type : AI Classification Error\\nError From : [AI INDIA]\\n─────────────────────────────────\\nRaw API error : ' + (errorDetail || '(no error detail)'),\n messageId\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": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ",
"mode": "id"
},
"sheetName": {
"__rl": true,
"value": 1691973413,
"mode": "list",
"cachedResultName": "Daily Logs"
},
"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": "Date", "displayName": "Date", "type": "string" },
{ "id": "Time", "displayName": "Time", "type": "string" },
{ "id": "Attachment Name", "displayName": "Attachment Name", "type": "string" },
{ "id": "Status", "displayName": "Status", "type": "string" },
{ "id": "GRN Message ", "displayName": "GRN Message ", "type": "string" },
{ "id": "Complete Error / Null Values","displayName": "Complete Error / Null Values","type": "string" }
]
},
"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": {
"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": {
"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"
}
}
}
],
"connections": {
"Watch New_Invoice Label1": {
"main": [[{ "node": "Fetch Emails from New_Invoice (max 3)1", "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 }
]]
},
"Set messageId Field1": {
"main": [[{ "node": "Merge: Email + AI Classification1", "type": "main", "index": 0 }]]
},
"AI: Classify Invoice1": {
"main": [[{ "node": "Merge: Email + AI Classification1", "type": "main", "index": 1 }]]
},
"Merge: Email + AI Classification1": {
"main": [[{ "node": "Split: One Item Per Attachment3", "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 }]
]
},
"Parse AI Output2": {
"main": [[{ "node": "Switch2", "type": "main", "index": 0 }]]
},
"Switch2": {
"main": [
[{ "node": "Wait 7s Before OCR2", "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 }]
]
},
"Wait 7s Before OCR2": {
"main": [[{ "node": "OCR: Extract Invoice Data2 [LOCAL]", "type": "main", "index": 0 }]]
},
"OCR: Extract Invoice Data2 [LOCAL]": {
"main": [[{ "node": "OCR Extraction Valid?2", "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 }]
]
},
"Normalize Invoice Fields2": {
"main": [[{ "node": "GRN: Create Record in Hospital2 [LOCAL]", "type": "main", "index": 0 }]]
},
"GRN: Create Record in Hospital2 [LOCAL]": {
"main": [[{ "node": "Flatten Data for Log2", "type": "main", "index": 0 }]]
},
"Flatten Data for Log2": {
"main": [[{ "node": "Log to Google Sheets (Daily Logs)2", "type": "main", "index": 0 }]]
},
"Log to Google Sheets (Daily Logs)2": {
"main": [[{ "node": "GRN Created Successfully?2", "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 }]
]
},
"Label: Add Invoice_Done2": {
"main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]]
},
"Failed To add2": {
"main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]]
},
"Flatten OCR Error for Log": {
"main": [[{ "node": "Append row in sheet5", "type": "main", "index": 0 }]]
},
"Append row in sheet5": {
"main": [[{ "node": "Label: Add Invoice_failed2", "type": "main", "index": 0 }]]
},
"Label: Add Invoice_failed2": {
"main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]]
},
"Code in JavaScript6": {
"main": [[{ "node": "Append row in sheet1", "type": "main", "index": 0 }]]
},
"Append row in sheet1": {
"main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]]
},
"Label: Add Not_Invoice2": {
"main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]]
},
"Groq Chat Model1": {
"ai_languageModel": [[{ "node": "AI: Classify Invoice1", "type": "ai_languageModel", "index": 1 }]]
},
"Google Gemini Chat Model": {
"ai_languageModel": [[{ "node": "AI: Classify Invoice1", "type": "ai_languageModel", "index": 0 }]]
}
},
"active": false,
"settings": {
"executionOrder": "v1",
"binaryMode": "separate",
"saveExecutionProgress": true,
"callerPolicy": "workflowsFromSameOwner"
},
"meta": {
"templateCredsSetupCompleted": true,
"instanceId": "09595d0d13dc9d2efef972a58e0990aff52b4fcad58caade8fb67afbc50891ba",
"_local_test_note": "LOCAL TEST VERSION — OCR and GRN endpoints point to localhost:8080. Switch to production by replacing localhost URLs with aiinfinite.in and mapp.dmhospital.org."
},
"tags": [
{ "id": "local-test", "name": "local-test" },
{ "id": "production", "name": "production" }
]
}