{
  "id": "0xFAcPdJ4Umoxfl9",
  "name": "Intelligent Tax Deduction Processing and Filing",
  "tags": [],
  "nodes": [
    {
      "id": "91c07b4f-ff0e-4439-963a-fb72cc546d74",
      "name": "Monthly Tax Processing Schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -1792,
        208
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "months",
              "triggerAtHour": 9
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "39b0b809-214a-48c9-8377-436b9f5a82fe",
      "name": "Workflow Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        -1600,
        208
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "expenseReceiptsApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__API endpoint for expense receipts__>"
            },
            {
              "id": "id-2",
              "name": "revenueDataApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__API endpoint for revenue data__>"
            },
            {
              "id": "id-3",
              "name": "taxAgentEmail",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Tax agent email address__>"
            },
            {
              "id": "id-4",
              "name": "currentTaxYear",
              "type": "number",
              "value": "={{ new Date().getFullYear() }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "92bb8752-587a-4aa4-9468-656de717a593",
      "name": "Fetch Expense Receipts",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -1408,
        96
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.expenseReceiptsApiUrl }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          }
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "b9e0d9ba-c8a2-42e2-90d3-fc1f9e79fd19",
      "name": "Fetch Revenue Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -656,
        400
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.revenueDataApiUrl }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "json"
            }
          }
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "fd98407a-6741-47e3-be4b-2645fde125f4",
      "name": "Check Receipt File Type",
      "type": "n8n-nodes-base.if",
      "position": [
        -1184,
        64
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "object",
                "operation": "exists"
              },
              "leftValue": "={{ $binary }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "07f38646-e544-41af-8c4b-d3784bf335c1",
      "name": "Extract Receipt Data",
      "type": "n8n-nodes-base.extractFromFile",
      "position": [
        -960,
        48
      ],
      "parameters": {
        "options": {},
        "operation": "pdf"
      },
      "typeVersion": 1.1
    },
    {
      "id": "0f2cccdb-b621-47c0-bf72-23e36a27bbb2",
      "name": "Extract Deductible Categories",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -736,
        64
      ],
      "parameters": {
        "text": "=Receipt data: {{ $json.text }}",
        "options": {
          "systemMessage": "You are a tax deduction specialist AI. Your task is to analyze expense receipts and extract deductible categories.\n\nAnalyze the receipt and extract:\n1. Vendor/Supplier name\n2. Date of expense\n3. Total amount\n4. Expense category (e.g., Office Supplies, Travel, Meals, Equipment, Professional Services)\n5. Tax deductibility status (fully deductible, partially deductible, non-deductible)\n6. Deduction percentage (0-100%)\n7. Notes or justification for deductibility\n\nReturn the structured data in the defined JSON format."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "6f5435c3-ee29-4597-bcee-616b178afc38",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        -752,
        288
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "1ba2ff7f-08d0-4540-99f8-6d64872f11cd",
      "name": "Structured Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -592,
        272
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"vendor\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"expenseDate\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"amount\": {\n\t\t\t\"type\": \"number\"\n\t\t},\n\t\t\"category\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"deductibilityStatus\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"deductionPercentage\": {\n\t\t\t\"type\": \"number\"\n\t\t},\n\t\t\"notes\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "3422a3cd-90de-4019-bdf1-4f75203dffe0",
      "name": "Merge Revenue and Deductions",
      "type": "n8n-nodes-base.merge",
      "position": [
        -384,
        208
      ],
      "parameters": {
        "mode": "combine",
        "options": {},
        "combineBy": "combineAll"
      },
      "typeVersion": 3.2
    },
    {
      "id": "96c1294e-e8a0-4e91-a2fb-180252d32575",
      "name": "Match Expenses to Revenue Periods",
      "type": "n8n-nodes-base.code",
      "position": [
        -160,
        208
      ],
      "parameters": {
        "jsCode": "// Match expense dates with revenue periods and combine the data\nconst expenses = $input.first().json.expenses || [];\nconst revenue = $input.last().json.revenue || [];\n\nconst matchedData = [];\n\n// Process each expense and match to revenue period\nfor (const expense of expenses) {\n  const expenseDate = new Date(expense.date);\n  \n  // Find matching revenue period\n  const matchingRevenue = revenue.find(rev => {\n    const periodStart = new Date(rev.periodStart);\n    const periodEnd = new Date(rev.periodEnd);\n    return expenseDate >= periodStart && expenseDate <= periodEnd;\n  });\n  \n  matchedData.push({\n    expense: expense,\n    revenue: matchingRevenue || null,\n    matched: !!matchingRevenue\n  });\n}\n\nreturn matchedData.map(item => ({ json: item }));"
      },
      "typeVersion": 2
    },
    {
      "id": "5028d4bf-de7e-4ebe-ba29-b4621a990ac6",
      "name": "Calculate Tax Deductions",
      "type": "n8n-nodes-base.code",
      "position": [
        64,
        208
      ],
      "parameters": {
        "jsCode": "// Calculate tax deductions by applying percentages to expenses\n// Group by revenue period and compute revenue minus deductions\n\nconst items = $input.all();\nconst results = [];\n\n// Group expenses by revenue period\nconst periodMap = new Map();\n\nfor (const item of items) {\n  const period = item.json.revenuePeriod || 'Unknown';\n  const revenue = item.json.revenue || 0;\n  const expenseAmount = item.json.expenseAmount || 0;\n  const deductionPercentage = item.json.deductionPercentage || 0;\n  \n  // Calculate deduction amount\n  const deductionAmount = expenseAmount * (deductionPercentage / 100);\n  \n  if (!periodMap.has(period)) {\n    periodMap.set(period, {\n      period: period,\n      revenue: revenue,\n      totalDeductions: 0,\n      expenses: []\n    });\n  }\n  \n  const periodData = periodMap.get(period);\n  periodData.totalDeductions += deductionAmount;\n  periodData.expenses.push({\n    amount: expenseAmount,\n    deductionPercentage: deductionPercentage,\n    deductionAmount: deductionAmount,\n    category: item.json.category || 'Uncategorized'\n  });\n}\n\n// Calculate net amounts for each period\nfor (const [period, data] of periodMap) {\n  results.push({\n    json: {\n      period: data.period,\n      revenue: data.revenue,\n      totalDeductions: data.totalDeductions,\n      netAmount: data.revenue - data.totalDeductions,\n      expenses: data.expenses,\n      expenseCount: data.expenses.length\n    }\n  });\n}\n\nreturn results;"
      },
      "typeVersion": 2
    },
    {
      "id": "2f515909-c403-467b-9c2f-4f825eeb0803",
      "name": "Format Tax Report",
      "type": "n8n-nodes-base.set",
      "position": [
        288,
        208
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "reportTitle",
              "type": "string",
              "value": "=Tax Deduction Report - {{ $('Workflow Configuration').first().json.currentTaxYear }}"
            },
            {
              "id": "id-2",
              "name": "generatedDate",
              "type": "string",
              "value": "={{ new Date().toISOString() }}"
            },
            {
              "id": "id-3",
              "name": "totalRevenue",
              "type": "number",
              "value": "={{ $json.totalRevenue }}"
            },
            {
              "id": "id-4",
              "name": "totalDeductions",
              "type": "number",
              "value": "={{ $json.totalDeductions }}"
            },
            {
              "id": "id-5",
              "name": "netIncome",
              "type": "number",
              "value": "={{ $json.netIncome }}"
            },
            {
              "id": "id-6",
              "name": "deductionsByCategory",
              "type": "object",
              "value": "={{ $json.deductionsByCategory }}"
            },
            {
              "id": "id-7",
              "name": "expenseDetails",
              "type": "array",
              "value": "={{ $json.expenseDetails }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "adcb4a3d-23f2-4236-a80c-4b5ef1535f47",
      "name": "Send to Tax Agent",
      "type": "n8n-nodes-base.gmail",
      "position": [
        512,
        208
      ],
      "parameters": {
        "sendTo": "={{ $('Workflow Configuration').first().json.taxAgentEmail }}",
        "message": "=Please find attached the automated tax deduction report for {{ $('Workflow Configuration').first().json.currentTaxYear }}.\n\nSummary:\n- Total Revenue: ${{ $json.totalRevenue }}\n- Total Deductions: ${{ $json.totalDeductions }}\n- Net Income: ${{ $json.netIncome }}\n\nThe detailed breakdown is included in the attached report.\n\nBest regards,\nAutomated Tax Processing System",
        "options": {},
        "subject": "=Tax Deduction Report - {{ $('Workflow Configuration').first().json.currentTaxYear }}",
        "emailType": "text"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "11b6c8ec-f244-4136-8673-d5c0790fd194",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -768,
        -448
      ],
      "parameters": {
        "color": 3,
        "width": 704,
        "height": 336,
        "content": "\n## Prerequisites\nExpense receipt repository; OpenAI API key; Gmail account; revenue data source.\n\n## Use Cases\nAccountants automating receipt processing for multiple clients; \n\n## Customization\nAdjust extraction prompts for industry-specific expenses, modify deduction rules \n\n## Benefits\nEliminates manual receipt review, reduces categorization errors "
      },
      "typeVersion": 1
    },
    {
      "id": "c53e32ac-97c4-46f7-b26f-1e8d9d810eea",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1232,
        -448
      ],
      "parameters": {
        "width": 432,
        "height": 208,
        "content": "## Setup Steps\n1. Configure receipt storage source and OpenAI Chat Model API key.\n2. Connect Gmail for report delivery and set up tax agent email.\n3. Define expense categories, revenue periods, and deduction rules.\n4. Schedule monthly trigger and test extraction "
      },
      "typeVersion": 1
    },
    {
      "id": "935604c6-af8f-47dd-a853-35494cc7be73",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1888,
        -448
      ],
      "parameters": {
        "width": 624,
        "height": 240,
        "content": "## How It Works\nThis workflow automates monthly tax processing by ingesting expense receipts alongside revenue data, extracting structured deduction details using GPT-4, and accurately matching expenses to their corresponding revenue periods. It retrieves receipts with built-in type validation, parses deduction information through OpenAI structured output extraction, and consolidates revenue records into a unified dataset. The system then intelligently aligns expenses with revenue timelines, calculates eligible deductions, and generates well-formatted tax reports that are automatically sent to designated agents via Gmail. Designed for accountants, tax professionals, and finance teams, it enables automated expense categorization and optimized deduction calculations."
      },
      "typeVersion": 1
    },
    {
      "id": "a45e6441-9366-4f81-b630-3bffe068b84b",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        16,
        -96
      ],
      "parameters": {
        "color": 7,
        "width": 672,
        "height": 704,
        "content": "## Calculate & Format\nWhat: Matches expenses to revenue periods, calculates deductions, generates tax reports.\nWhy: Produces audit-ready documentation and maximizes legitimate tax advantages."
      },
      "typeVersion": 1
    },
    {
      "id": "c36be84c-3ec4-4b63-967b-dfbf74791e45",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -800,
        -96
      ],
      "parameters": {
        "color": 7,
        "width": 784,
        "height": 720,
        "content": "## Merge Revenue & Expenses\nWhat: Consolidates expense and revenue datasets into aligned records by period.\nWhy: Enables accurate deduction-to-revenue matching for tax calculations."
      },
      "typeVersion": 1
    },
    {
      "id": "866b13cc-f00b-4fb2-9a5c-02106faf2afb",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1856,
        -96
      ],
      "parameters": {
        "color": 7,
        "width": 1040,
        "height": 560,
        "content": " \n## Fetch & Validate Expenses \nWhat: Retrieves expense receipts and validates file types before processing.\nWhy: Ensures data quality and prevents processing errors from invalid formats."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "a3246386-1626-44aa-bdd6-125ebccf3c74",
  "connections": {
    "Format Tax Report": {
      "main": [
        [
          {
            "node": "Send to Tax Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Extract Deductible Categories",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Revenue Data": {
      "main": [
        [
          {
            "node": "Merge Revenue and Deductions",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Extract Receipt Data": {
      "main": [
        [
          {
            "node": "Extract Deductible Categories",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Expense Receipts": {
      "main": [
        [
          {
            "node": "Check Receipt File Type",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow Configuration": {
      "main": [
        [
          {
            "node": "Fetch Expense Receipts",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Revenue Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Receipt File Type": {
      "main": [
        [
          {
            "node": "Extract Receipt Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Tax Deductions": {
      "main": [
        [
          {
            "node": "Format Tax Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Extract Deductible Categories",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Merge Revenue and Deductions": {
      "main": [
        [
          {
            "node": "Match Expenses to Revenue Periods",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Deductible Categories": {
      "main": [
        [
          {
            "node": "Merge Revenue and Deductions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Monthly Tax Processing Schedule": {
      "main": [
        [
          {
            "node": "Workflow Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Match Expenses to Revenue Periods": {
      "main": [
        [
          {
            "node": "Calculate Tax Deductions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}