{
  "id": "yyx2r9xzuvhOJENa",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "SIP and Mutual Fund Goal Tracker - Form + Smart SIP Calculator + ChatGPT AI Advisory + Gmail + Sheets",
  "tags": [],
  "nodes": [
    {
      "id": "9d3fdace-de0c-4072-8e4b-8a3c3ef151ad",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        736,
        -192
      ],
      "parameters": {
        "color": 4,
        "width": 536,
        "height": 1372,
        "content": "## \ud83d\udcc8 SIP and Mutual Fund Goal Tracker - Form + Smart SIP Calculator + ChatGPT AI Advisory + Gmail + Sheets\n\nFor Indian mutual fund investors who want to know if their SIP is on track to meet their financial goal. The investor fills a short form with their fund, monthly SIP amount, start date, current value, and goal. A built-in calculator (no external API) computes total invested, absolute returns, a CAGR approximation, goal completion percentage, and the extra monthly amount needed to reach the goal in time. A ChatGPT AI model then writes a personalized, plain-English investment advisory. The investor receives a full colour-coded HTML performance report by email, and every submission is logged to Google Sheets so progress can be tracked over time.\n\n## What each node does\n- **1. Form - Investor SIP Details** collects investor name, email, fund name, fund category, monthly SIP amount, start date, current value, goal amount, goal timeline, and goal description\n- **2. Code - Calculate SIP Performance Metrics** runs the SIP calculator and returns months invested, total invested, returns, CAGR approximation, goal completion percentage, required monthly top-up, performance status, goal status, and the ELSS 80C tax saving flag\n- **3. HTTP - AI Write SIP Advisory** sends the metrics to a ChatGPT AI model and gets back a structured advisory covering performance summary, strengths, concerns, top-up advice, goal analysis, and tax benefit\n- **4. Code - Parse Advisory + Assign Colors** safely parses the advisory (with a fallback if parsing fails) and assigns performance, goal, and returns colours for the report\n- **5. Code - Build HTML SIP Report Email** builds the full colour-coded HTML report with KPI cards, goal progress bar, and advisory sections\n- **6. Sheets - Save SIP Record** appends the SIP record to the tracking log (parallel branch)\n- **7. Gmail - Send SIP Report to Investor** emails the performance report to the investor (parallel branch)\n\n## How the calculations work\nNode 2 computes months invested from the start date, total invested, absolute returns, a CAGR approximation, goal completion percentage, and the additional monthly SIP needed to reach the goal in time at an assumed 12 percent annual return. Performance status: Excellent, Good, Moderate, Below Average, Negative. Goal status: Goal Achieved, On Track, In Progress, Early Stage. These are estimates for tracking, not exact XIRR figures.\n\n## Key things to know\n1. **India focused** - all amounts are in INR with Indian comma formatting, and ELSS funds automatically get an 80C tax saving section in the report\n2. **Fallback advisory** - if the AI response cannot be parsed for any reason, a sensible default advisory is used so the report always goes out\n3. **Not investment advice** - the AI is instructed to avoid specific buy or sell recommendations, and the email always carries a disclaimer that this is not SEBI registered advice\n4. **History tracking** - every submission is appended to Sheets, so the investor can submit monthly and watch their goal completion grow over time\n\n## Google Sheet setup\nCreate a Google Sheet, add a tab named **SIP Log**, and put these column headers in row 1:\nDate, Investor Name, Email, Fund Name, Category, Monthly SIP, SIP Start Date, Months Invested, Total Invested, Current Value, Absolute Returns, Returns Pct, CAGR Pct, Goal Amount, Goal Years, Goal Description, Goal Completion Pct, Goal Status, Performance Status, Processed At\n\n## Set up steps\n1. **OpenAI** - in **3. HTTP - AI Write SIP Advisory**, connect your OpenAI API credential. A ChatGPT AI model writes the advisory\n2. **Google Sheets** - in **6. Sheets - Save SIP Record**, connect Google Sheets OAuth2 and replace `YOUR_SIP_TRACKER_SHEET_ID` with your sheet ID (from the sheet URL after /d/)\n3. **Gmail** - in **7. Gmail - Send SIP Report to Investor**, connect Gmail OAuth2. The recipient comes from the form\n4. Activate the workflow, open the Form URL, enter your SIP details, and submit. The report is emailed and logged instantly"
      },
      "typeVersion": 1
    },
    {
      "id": "5a2ae4b2-eee7-42af-8e0d-3725bea38db2",
      "name": "Section - Form and SIP Calculations",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1328,
        64
      ],
      "parameters": {
        "color": 5,
        "width": 490,
        "height": 602,
        "content": "## Form and SIP Calculations\nInvestor fills their SIP details. Code validates the inputs and calculates months invested, total invested, returns, CAGR approximation, goal completion percentage, and the required monthly top-up, all without any external API."
      },
      "typeVersion": 1
    },
    {
      "id": "c9ce83de-db78-4c00-9eb5-1eee23e877c7",
      "name": "Section - AI Advisory and Report Colors",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1872,
        48
      ],
      "parameters": {
        "color": 6,
        "width": 540,
        "height": 602,
        "content": "## AI Advisory and Report Colors\nThe ChatGPT AI model analyzes the SIP performance against the goal and writes a personalized advisory with specific suggestions. Code parses the advisory safely, with a fallback if needed, and assigns the report colours."
      },
      "typeVersion": 1
    },
    {
      "id": "a3e12b8b-bd1e-42c5-8e09-6e84419c916c",
      "name": "Section - Build Report, Log, and Send",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2496,
        -80
      ],
      "parameters": {
        "color": 4,
        "width": 588,
        "height": 1024,
        "content": "## Build Report, Log, and Send\nCode builds the full colour-coded HTML performance report with KPI cards and the goal progress bar. Two parallel branches run: Sheets saves the SIP record to the tracking log, and Gmail sends the report to the investor."
      },
      "typeVersion": 1
    },
    {
      "id": "26b6bbf5-8945-423b-830a-2f7846cfd5a9",
      "name": "1. Form - Investor SIP Details",
      "type": "n8n-nodes-base.formTrigger",
      "position": [
        1392,
        320
      ],
      "parameters": {
        "options": {
          "path": "sip-tracker",
          "buttonLabel": "Analyze My SIP",
          "appendAttribution": false
        },
        "formTitle": "\ud83d\udcc8 SIP and Mutual Fund Tracker",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Your Full Name",
              "placeholder": "e.g. Rahul Kumar",
              "requiredField": true
            },
            {
              "fieldLabel": "Your Email Address",
              "placeholder": "your@email.com - SIP report will be sent here",
              "requiredField": true
            },
            {
              "fieldLabel": "Fund Name",
              "placeholder": "e.g. Parag Parikh Flexi Cap Fund, Axis Bluechip, Mirae Asset ELSS",
              "requiredField": true
            },
            {
              "fieldType": "dropdown",
              "fieldLabel": "Fund Category",
              "fieldOptions": {
                "values": [
                  {
                    "option": "Equity - Large Cap"
                  },
                  {
                    "option": "Equity - Mid Cap"
                  },
                  {
                    "option": "Equity - Small Cap"
                  },
                  {
                    "option": "Equity - Flexi Cap or Multi Cap"
                  },
                  {
                    "option": "ELSS - Tax Saving (80C)"
                  },
                  {
                    "option": "Index Fund"
                  },
                  {
                    "option": "Hybrid - Balanced or Aggressive"
                  },
                  {
                    "option": "Debt - Short Term or Liquid"
                  }
                ]
              },
              "requiredField": true
            },
            {
              "fieldLabel": "Monthly SIP Amount (in INR)",
              "placeholder": "e.g. 5000",
              "requiredField": true
            },
            {
              "fieldLabel": "SIP Start Date",
              "placeholder": "YYYY-MM-DD e.g. 2022-01-01",
              "requiredField": true
            },
            {
              "fieldLabel": "Current Portfolio Value (in INR)",
              "placeholder": "e.g. 145000 - check your mutual fund app for current value",
              "requiredField": true
            },
            {
              "fieldLabel": "Financial Goal Amount (in INR)",
              "placeholder": "e.g. 1000000 - what you want to accumulate",
              "requiredField": true
            },
            {
              "fieldLabel": "Goal Timeline (years from today)",
              "placeholder": "e.g. 10 - number of years to reach your goal",
              "requiredField": true
            },
            {
              "fieldLabel": "Goal Description",
              "placeholder": "e.g. Retirement corpus, Child education fund, House down payment, Emergency fund",
              "requiredField": true
            }
          ]
        },
        "formDescription": "Enter your SIP details to get a performance report against your financial goal. You will receive a full analysis with AI advisory by email."
      },
      "typeVersion": 2.2
    },
    {
      "id": "99b0e035-5e56-466e-8788-7abea67f3711",
      "name": "2. Code - Calculate SIP Performance Metrics",
      "type": "n8n-nodes-base.code",
      "position": [
        1632,
        320
      ],
      "parameters": {
        "jsCode": "// Validate inputs and calculate SIP performance metrics\nconst row = $json;\n\nconst investorName    = (row['Your Full Name']                    || '').trim();\nconst email           = (row['Your Email Address']               || '').trim();\nconst fundName        = (row['Fund Name']                        || '').trim();\nconst fundCategory    = (row['Fund Category']                    || '').trim();\nconst monthlySIP      = parseFloat(row['Monthly SIP Amount (in INR)'].toString().replace(/,/g, '')) || 0;\nconst sipStartDate    = (row['SIP Start Date']                   || '').trim();\nconst currentValue    = parseFloat(row['Current Portfolio Value (in INR)'].toString().replace(/,/g, '')) || 0;\nconst goalAmount      = parseFloat(row['Financial Goal Amount (in INR)'].toString().replace(/,/g, '')) || 0;\nconst goalYears       = parseFloat(row['Goal Timeline (years from today)']) || 5;\nconst goalDescription = (row['Goal Description']                 || '').trim();\n\n// Validate\nif (!investorName)  throw new Error('Investor name is required.');\nif (!email || !email.includes('@')) throw new Error('Valid email address is required.');\nif (!fundName)      throw new Error('Fund name is required.');\nif (monthlySIP <= 0) throw new Error('Monthly SIP amount must be greater than 0.');\nif (currentValue <= 0) throw new Error('Current portfolio value must be greater than 0.');\nif (goalAmount <= 0) throw new Error('Goal amount must be greater than 0.');\nif (!sipStartDate)  throw new Error('SIP start date is required.');\n\n// Calculate months invested\nconst today       = new Date();\nconst startDate   = new Date(sipStartDate);\nif (isNaN(startDate.getTime())) throw new Error('Invalid SIP start date. Use YYYY-MM-DD format.');\n\nconst monthsInvested = Math.max(1, Math.floor(\n  (today - startDate) / (1000 * 60 * 60 * 24 * 30.44)\n));\nconst yearsInvested  = +(monthsInvested / 12).toFixed(2);\n\n// Total invested\nconst totalInvested = monthlySIP * monthsInvested;\n\n// Absolute returns\nconst absoluteReturns    = currentValue - totalInvested;\nconst absoluteReturnsPct = totalInvested > 0\n  ? +((absoluteReturns / totalInvested) * 100).toFixed(2)\n  : 0;\n\n// CAGR approximation (not exact XIRR but good enough for SIP tracking)\nlet cagr = 0;\nif (yearsInvested >= 1 && currentValue > 0 && totalInvested > 0) {\n  cagr = +((Math.pow(currentValue / totalInvested, 1 / yearsInvested) - 1) * 100).toFixed(2);\n}\n\n// Goal completion percentage\nconst goalCompletionPct = +((currentValue / goalAmount) * 100).toFixed(2);\nconst goalRemaining     = Math.max(0, goalAmount - currentValue);\n\n// Monthly required to reach goal (simple future value approximation)\n// FV = PMT * ((1+r)^n - 1) / r, assuming 12% annual return (standard equity MF assumption)\nconst assumedMonthlyReturn = 0.12 / 12;\nconst goalMonths = goalYears * 12;\nconst requiredMonthly = goalAmount > currentValue\n  ? +((goalRemaining * assumedMonthlyReturn) / (Math.pow(1 + assumedMonthlyReturn, goalMonths) - 1)).toFixed(0)\n  : 0;\n\n// Performance status\nconst performanceStatus =\n  cagr >= 15 ? 'Excellent' :\n  cagr >= 10 ? 'Good' :\n  cagr >= 6  ? 'Moderate' :\n  cagr >= 0  ? 'Below Average' : 'Negative';\n\n// Goal status\nconst goalStatus =\n  goalCompletionPct >= 100 ? 'Goal Achieved' :\n  goalCompletionPct >= 75  ? 'On Track' :\n  goalCompletionPct >= 50  ? 'In Progress' :\n  'Early Stage';\n\n// ELSS tax benefit flag\nconst isELSS = fundCategory.includes('ELSS');\nconst annualSIP = monthlySIP * 12;\nconst taxSavingAmount = isELSS ? Math.min(annualSIP, 150000) : 0;\n\nconst processedAt = new Date().toISOString();\nconst dateOnly    = processedAt.split('T')[0];\n\n// Format numbers with Indian comma system\nconst fmtINR = (n) => Number(Math.round(n)).toLocaleString('en-IN');\n\nreturn [{\n  json: {\n    investorName, email, fundName, fundCategory,\n    monthlySIP, sipStartDate, currentValue, goalAmount,\n    goalYears, goalDescription, monthsInvested, yearsInvested,\n    totalInvested, absoluteReturns, absoluteReturnsPct, cagr,\n    goalCompletionPct, goalRemaining, requiredMonthly,\n    performanceStatus, goalStatus, isELSS, taxSavingAmount, annualSIP,\n    processedAt, dateOnly,\n    // Formatted strings for email\n    fmt: {\n      monthlySIP:       '\u20b9' + fmtINR(monthlySIP),\n      totalInvested:    '\u20b9' + fmtINR(totalInvested),\n      currentValue:     '\u20b9' + fmtINR(currentValue),\n      absoluteReturns:  (absoluteReturns >= 0 ? '+\u20b9' : '-\u20b9') + fmtINR(Math.abs(absoluteReturns)),\n      goalAmount:       '\u20b9' + fmtINR(goalAmount),\n      goalRemaining:    '\u20b9' + fmtINR(goalRemaining),\n      requiredMonthly:  '\u20b9' + fmtINR(requiredMonthly),\n      taxSaving:        '\u20b9' + fmtINR(taxSavingAmount)\n    }\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "3b6ac54e-fcde-4d65-8548-e56762afa242",
      "name": "3. HTTP - AI Write SIP Advisory",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1984,
        320
      ],
      "parameters": {
        "url": "https://api.openai.com/v1/chat/completions",
        "method": "POST",
        "options": {
          "timeout": 30000,
          "response": {
            "response": {
              "responseFormat": "json"
            }
          }
        },
        "jsonBody": "={\n  \"model\": \"gpt-4o-mini\",\n  \"temperature\": 0.4,\n  \"max_tokens\": 900,\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a friendly and knowledgeable mutual fund advisor helping retail investors in India understand their SIP performance. You give clear, practical, and encouraging advice. You are not SEBI-registered so you do not make specific buy or sell recommendations. Instead you explain the data and suggest questions the investor should ask a financial advisor. Return ONLY valid JSON with no markdown and no code fences.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": {{ JSON.stringify(\n        \"Analyze this SIP investment and provide advisory.\\n\\n\" +\n        \"INVESTOR: \" + $json.investorName + \"\\n\" +\n        \"FUND: \" + $json.fundName + \"\\n\" +\n        \"CATEGORY: \" + $json.fundCategory + \"\\n\" +\n        \"GOAL: \" + $json.goalDescription + \"\\n\" +\n        \"GOAL AMOUNT: Rs \" + $json.goalAmount + \"\\n\" +\n        \"GOAL TIMELINE: \" + $json.goalYears + \" years\\n\" +\n        \"MONTHLY SIP: Rs \" + $json.monthlySIP + \"\\n\" +\n        \"SIP DURATION: \" + $json.monthsInvested + \" months (\" + $json.yearsInvested + \" years)\\n\" +\n        \"TOTAL INVESTED: Rs \" + $json.totalInvested + \"\\n\" +\n        \"CURRENT VALUE: Rs \" + $json.currentValue + \"\\n\" +\n        \"ABSOLUTE RETURNS: \" + $json.absoluteReturnsPct + \"%\\n\" +\n        \"CAGR APPROX: \" + $json.cagr + \"% per year\\n\" +\n        \"GOAL COMPLETION: \" + $json.goalCompletionPct + \"%\\n\" +\n        \"PERFORMANCE STATUS: \" + $json.performanceStatus + \"\\n\" +\n        \"GOAL STATUS: \" + $json.goalStatus + \"\\n\" +\n        \"ADDITIONAL MONTHLY NEEDED: Rs \" + $json.requiredMonthly + \" (to reach goal in time at 12% assumed return)\\n\" +\n        ($json.isELSS ? \"TAX BENEFIT: ELSS fund, eligible for 80C deduction up to Rs 1.5 lakh per year\\n\" : \"\") +\n        \"\\nReturn this exact JSON structure:\\n\" +\n        \"{\\n\" +\n        \"  \\\"performanceSummary\\\": \\\"2 sentences summarizing how the SIP is performing and whether it is on track to meet the goal\\\",\\n\" +\n        \"  \\\"whatIsWorking\\\": \\\"one positive observation about this SIP, such as consistency, returns, or goal alignment\\\",\\n\" +\n        \"  \\\"concernOrWatch\\\": \\\"one thing to watch out for or consider, such as category risk, timeline pressure, or a gap in the monthly amount\\\",\\n\" +\n        \"  \\\"sipTopUpAdvice\\\": \\\"specific advice on whether to increase the SIP amount and by how much based on the goal gap\\\",\\n\" +\n        \"  \\\"goalAdvice\\\": \\\"2 sentences on whether the goal is achievable at current pace and what adjustment is needed\\\",\\n\" +\n        ($json.isELSS ? \"  \\\"taxAdvice\\\": \\\"explain the 80C benefit for this ELSS fund and how much tax the investor can save\\\",\\n\" : \"  \\\"taxAdvice\\\": null,\\n\") +\n        \"  \\\"disclaimer\\\": \\\"one sentence standard disclaimer that this is not SEBI-registered advice\\\"\\n\" +\n        \"}\"\n      ) }}\"\n    }\n  ]\n}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "authentication": "predefinedCredentialType",
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "nodeCredentialType": "openAiApi"
      },
      "typeVersion": 4.2
    },
    {
      "id": "5d436a64-912f-4e17-81a3-dea8139bff96",
      "name": "4. Code - Parse Advisory + Assign Colors",
      "type": "n8n-nodes-base.code",
      "position": [
        2224,
        320
      ],
      "parameters": {
        "jsCode": "// Parse the AI advisory and merge with SIP metrics\nconst resp    = $input.first().json;\nconst metrics = $('2. Code - Calculate SIP Performance Metrics').first().json;\n\nconst raw = resp?.choices?.[0]?.message?.content || '';\nif (!raw) throw new Error('The AI returned an empty response. Check your OpenAI API credential.');\n\nlet advisory = {};\ntry {\n  const cleaned = raw.trim()\n    .replace(/^```json\\s*/i, '')\n    .replace(/^```\\s*/i, '')\n    .replace(/```$/i, '')\n    .trim();\n  const s = cleaned.indexOf('{');\n  const e = cleaned.lastIndexOf('}');\n  if (s !== -1 && e !== -1) advisory = JSON.parse(cleaned.substring(s, e + 1));\n  else throw new Error('No JSON object in response');\n} catch (err) {\n  advisory = {\n    performanceSummary: 'Your SIP is performing at ' + metrics.cagr + '% CAGR. Goal completion is at ' + metrics.goalCompletionPct + '%.',\n    whatIsWorking:      'Consistent monthly investing is the key strength of your plan.',\n    concernOrWatch:     'Keep monitoring performance against benchmark annually.',\n    sipTopUpAdvice:     'Consider increasing SIP by 10% each year to combat inflation.',\n    goalAdvice:         'Review your goal timeline and SIP amount with a financial advisor.',\n    taxAdvice:          metrics.isELSS ? 'Your ELSS investment qualifies for 80C deduction.' : null,\n    disclaimer:         'This is not SEBI-registered financial advice. Please consult a qualified financial advisor.'\n  };\n}\n\n// Performance color\nconst perfColor =\n  metrics.cagr >= 15 ? '#27ae60' :\n  metrics.cagr >= 10 ? '#2196f3' :\n  metrics.cagr >= 6  ? '#f39c12' : '#e74c3c';\n\n// Goal completion color\nconst goalColor =\n  metrics.goalCompletionPct >= 75 ? '#27ae60' :\n  metrics.goalCompletionPct >= 50 ? '#f39c12' : '#e74c3c';\n\n// Returns color\nconst retColor = metrics.absoluteReturns >= 0 ? '#27ae60' : '#e74c3c';\n\nreturn [{\n  json: {\n    ...metrics,\n    advisory,\n    perfColor,\n    goalColor,\n    retColor\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "2a3cfc18-5909-44a5-908a-bc6fa3f9daf6",
      "name": "5. Code - Build HTML SIP Report Email",
      "type": "n8n-nodes-base.code",
      "position": [
        2576,
        320
      ],
      "parameters": {
        "jsCode": "// Build complete HTML email report for investor\nconst d   = $input.first().json;\nconst adv = d.advisory;\n\nconst htmlEmail =\n  '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"></head>'\n  + '<body style=\"font-family:Arial,sans-serif;max-width:680px;margin:0 auto;background:#f5f5f5;\">'\n\n  // Header\n  + '<div style=\"background:linear-gradient(135deg,#1a237e 0%,#283593 100%);padding:26px 28px;border-radius:8px 8px 0 0;\">'\n  + '<h1 style=\"color:#fff;font-size:19px;margin:0;\">\ud83d\udcc8 SIP Performance Report</h1>'\n  + '<p style=\"color:#c5cae9;font-size:13px;margin:6px 0 0;\">' + d.investorName + ' &nbsp;|&nbsp; ' + d.fundName + ' &nbsp;|&nbsp; ' + d.dateOnly + '</p>'\n  + '</div>'\n\n  // Category and goal bar\n  + '<div style=\"background:#283593;padding:10px 24px;display:flex;gap:20px;flex-wrap:wrap;\">'\n  + '<span style=\"color:#c5cae9;font-size:13px;\">\ud83c\udff7\ufe0f ' + d.fundCategory.split(' - ')[0].trim() + '</span>'\n  + '<span style=\"color:#c5cae9;font-size:13px;\">\ud83c\udfaf ' + d.goalDescription + '</span>'\n  + '<span style=\"color:#c5cae9;font-size:13px;\">\ud83d\udcc5 ' + d.monthsInvested + ' months invested</span>'\n  + '</div>'\n\n  + '<div style=\"background:#fff;padding:20px 24px;\">'\n\n  // KPI row\n  + '<div style=\"display:flex;flex-wrap:wrap;gap:0;margin-bottom:20px;border-radius:8px;overflow:hidden;border:1px solid #e8eaf6;\">'\n  + '<div style=\"flex:1;min-width:130px;padding:14px 16px;text-align:center;border-right:1px solid #e8eaf6;\">'\n  + '<div style=\"font-size:11px;color:#888;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;\">Invested</div>'\n  + '<div style=\"font-size:18px;font-weight:700;color:#1a237e;\">' + d.fmt.totalInvested + '</div></div>'\n\n  + '<div style=\"flex:1;min-width:130px;padding:14px 16px;text-align:center;border-right:1px solid #e8eaf6;\">'\n  + '<div style=\"font-size:11px;color:#888;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;\">Current Value</div>'\n  + '<div style=\"font-size:18px;font-weight:700;color:#1a237e;\">' + d.fmt.currentValue + '</div></div>'\n\n  + '<div style=\"flex:1;min-width:120px;padding:14px 16px;text-align:center;border-right:1px solid #e8eaf6;\">'\n  + '<div style=\"font-size:11px;color:#888;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;\">Returns</div>'\n  + '<div style=\"font-size:18px;font-weight:700;color:' + d.retColor + ';\">' + d.fmt.absoluteReturns + '</div>'\n  + '<div style=\"font-size:12px;color:' + d.retColor + ';\">' + (d.absoluteReturnsPct >= 0 ? '+' : '') + d.absoluteReturnsPct + '%</div></div>'\n\n  + '<div style=\"flex:1;min-width:120px;padding:14px 16px;text-align:center;\">'\n  + '<div style=\"font-size:11px;color:#888;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;\">CAGR</div>'\n  + '<div style=\"font-size:18px;font-weight:700;color:' + d.perfColor + ';\">' + d.cagr + '%</div>'\n  + '<div style=\"font-size:12px;color:' + d.perfColor + ';\">' + d.performanceStatus + '</div></div>'\n  + '</div>'\n\n  // Goal progress bar\n  + '<div style=\"margin-bottom:20px;\">'\n  + '<div style=\"display:flex;justify-content:space-between;margin-bottom:6px;\">'\n  + '<span style=\"font-size:13px;color:#333;font-weight:600;\">Goal Progress - ' + d.goalDescription + '</span>'\n  + '<span style=\"font-size:13px;color:' + d.goalColor + ';font-weight:700;\">' + d.goalCompletionPct + '% complete</span>'\n  + '</div>'\n  + '<div style=\"background:#e8eaf6;border-radius:10px;height:12px;overflow:hidden;\">'\n  + '<div style=\"background:' + d.goalColor + ';height:100%;width:' + Math.min(d.goalCompletionPct, 100) + '%;border-radius:10px;transition:width 0.3s;\"></div>'\n  + '</div>'\n  + '<div style=\"display:flex;justify-content:space-between;margin-top:6px;\">'\n  + '<span style=\"font-size:12px;color:#888;\">Current: ' + d.fmt.currentValue + '</span>'\n  + '<span style=\"font-size:12px;color:#888;\">Goal: ' + d.fmt.goalAmount + '</span>'\n  + '</div>'\n  + '</div>'\n\n  // AI Advisory\n  + '<div style=\"background:#e8eaf6;border-left:4px solid #3f51b5;padding:14px 16px;border-radius:0 6px 6px 0;margin-bottom:14px;\">'\n  + '<h2 style=\"margin:0 0 8px;font-size:14px;color:#1a237e;\">\ud83d\udcca Performance Summary</h2>'\n  + '<p style=\"margin:0;font-size:14px;color:#333;line-height:1.7;\">' + (adv.performanceSummary || '') + '</p>'\n  + '</div>'\n\n  + '<div style=\"display:flex;gap:12px;margin-bottom:14px;flex-wrap:wrap;\">'\n  + '<div style=\"flex:1;min-width:200px;background:#e8f5e9;border-left:4px solid #43a047;padding:12px 14px;border-radius:0 6px 6px 0;\">'\n  + '<div style=\"font-size:12px;font-weight:700;color:#1b5e20;margin-bottom:4px;\">\u2705 What Is Working</div>'\n  + '<p style=\"margin:0;font-size:13px;color:#333;line-height:1.6;\">' + (adv.whatIsWorking || '') + '</p></div>'\n  + '<div style=\"flex:1;min-width:200px;background:#fff8e1;border-left:4px solid #ffa000;padding:12px 14px;border-radius:0 6px 6px 0;\">'\n  + '<div style=\"font-size:12px;font-weight:700;color:#e65100;margin-bottom:4px;\">\u26a0\ufe0f Watch Out For</div>'\n  + '<p style=\"margin:0;font-size:13px;color:#333;line-height:1.6;\">' + (adv.concernOrWatch || '') + '</p></div>'\n  + '</div>'\n\n  + '<div style=\"background:#e3f2fd;border-left:4px solid #1e88e5;padding:12px 14px;border-radius:0 6px 6px 0;margin-bottom:14px;\">'\n  + '<div style=\"font-size:12px;font-weight:700;color:#0d47a1;margin-bottom:4px;\">\ud83d\udcb0 SIP Top-Up Advice</div>'\n  + '<p style=\"margin:0;font-size:13px;color:#333;line-height:1.6;\">' + (adv.sipTopUpAdvice || '') + '</p>'\n  + (d.requiredMonthly > 0 ? '<p style=\"margin:8px 0 0;font-size:13px;color:#0d47a1;font-weight:600;\">To reach ' + d.fmt.goalAmount + ' in ' + d.goalYears + ' years, you may need to invest approximately ' + d.fmt.requiredMonthly + ' per month additionally (at 12% assumed return).</p>' : '')\n  + '</div>'\n\n  + '<div style=\"background:#f3e5f5;border-left:4px solid #8e24aa;padding:12px 14px;border-radius:0 6px 6px 0;margin-bottom:14px;\">'\n  + '<div style=\"font-size:12px;font-weight:700;color:#4a148c;margin-bottom:4px;\">\ud83c\udfaf Goal Analysis</div>'\n  + '<p style=\"margin:0;font-size:13px;color:#333;line-height:1.6;\">' + (adv.goalAdvice || '') + '</p></div>'\n\n  + (d.isELSS && adv.taxAdvice ? '<div style=\"background:#e8f5e9;border-left:4px solid #2e7d32;padding:12px 14px;border-radius:0 6px 6px 0;margin-bottom:14px;\">'\n  + '<div style=\"font-size:12px;font-weight:700;color:#1b5e20;margin-bottom:4px;\">\ud83d\udc9a 80C Tax Saving Benefit</div>'\n  + '<p style=\"margin:0;font-size:13px;color:#333;line-height:1.6;\">' + adv.taxAdvice + '</p>'\n  + '<p style=\"margin:8px 0 0;font-size:13px;color:#1b5e20;font-weight:600;\">Your annual SIP of ' + d.fmt.monthlySIP + ' x 12 = ' + d.fmt.annualSIP + ' qualifies for 80C deduction up to ' + d.fmt.taxSaving + '.</p></div>' : '')\n\n  // Monthly SIP info\n  + '<div style=\"background:#f0f4ff;border-radius:6px;padding:12px 16px;margin-bottom:14px;\">'\n  + '<div style=\"display:flex;gap:20px;flex-wrap:wrap;\">'\n  + '<div><div style=\"font-size:11px;color:#888;margin-bottom:2px;\">Monthly SIP</div><div style=\"font-size:15px;font-weight:700;color:#1a237e;\">' + d.fmt.monthlySIP + '</div></div>'\n  + '<div><div style=\"font-size:11px;color:#888;margin-bottom:2px;\">Duration</div><div style=\"font-size:15px;font-weight:700;color:#1a237e;\">' + d.monthsInvested + ' months</div></div>'\n  + '<div><div style=\"font-size:11px;color:#888;margin-bottom:2px;\">Goal Status</div><div style=\"font-size:15px;font-weight:700;color:' + d.goalColor + ';\">' + d.goalStatus + '</div></div>'\n  + '<div><div style=\"font-size:11px;color:#888;margin-bottom:2px;\">Remaining</div><div style=\"font-size:15px;font-weight:700;color:#1a237e;\">' + d.fmt.goalRemaining + '</div></div>'\n  + '</div>'\n  + '</div>'\n\n  // Disclaimer\n  + '<div style=\"background:#f3f4f6;border-radius:6px;padding:12px 16px;\">'\n  + '<p style=\"font-size:11px;color:#888;margin:0;line-height:1.7;\">'\n  + '<strong>Disclaimer:</strong> ' + (adv.disclaimer || 'This report is for informational purposes only and does not constitute SEBI-registered financial advice. Please consult a qualified financial advisor before making investment decisions.') + '</p></div>'\n\n  + '</div>'\n\n  + '<div style=\"background:#1a237e;padding:12px 24px;text-align:center;border-radius:0 0 8px 8px;\">'\n  + '<p style=\"color:#c5cae9;font-size:11px;margin:0;\">SIP and Mutual Fund Tracker - n8n + ChatGPT AI</p>'\n  + '</div>'\n  + '</body></html>';\n\nreturn [{\n  json: {\n    ...d,\n    htmlEmail,\n    emailSubject: '\ud83d\udcc8 SIP Report - ' + d.fundName + ' | ' + d.goalCompletionPct + '% Goal | CAGR ' + d.cagr + '% | ' + d.dateOnly\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "a7c532c2-f983-4987-a2db-0bc9958b3b90",
      "name": "6. Sheets - Save SIP Record",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        2816,
        192
      ],
      "parameters": {
        "columns": {
          "value": {
            "Date": "={{ $json.dateOnly }}",
            "Email": "={{ $json.email }}",
            "CAGR Pct": "={{ $json.cagr }}",
            "Category": "={{ $json.fundCategory }}",
            "Fund Name": "={{ $json.fundName }}",
            "Goal Years": "={{ $json.goalYears }}",
            "Goal Amount": "={{ $json.goalAmount }}",
            "Goal Status": "={{ $json.goalStatus }}",
            "Monthly SIP": "={{ $json.monthlySIP }}",
            "Returns Pct": "={{ $json.absoluteReturnsPct }}",
            "Processed At": "={{ $json.processedAt }}",
            "Current Value": "={{ $json.currentValue }}",
            "Investor Name": "={{ $json.investorName }}",
            "SIP Start Date": "={{ $json.sipStartDate }}",
            "Total Invested": "={{ $json.totalInvested }}",
            "Months Invested": "={{ $json.monthsInvested }}",
            "Absolute Returns": "={{ $json.absoluteReturns }}",
            "Goal Description": "={{ $json.goalDescription }}",
            "Performance Status": "={{ $json.performanceStatus }}",
            "Goal Completion Pct": "={{ $json.goalCompletionPct }}"
          },
          "schema": [
            {
              "id": "Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Investor Name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Investor Name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Email",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Email",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Fund Name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Fund Name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Category",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Category",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Monthly SIP",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Monthly SIP",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "SIP Start Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "SIP Start Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Months Invested",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Months Invested",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Total Invested",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Total Invested",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Current Value",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Current Value",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Absolute Returns",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Absolute Returns",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Returns Pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Returns Pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "CAGR Pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "CAGR Pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Goal Amount",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Goal Amount",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Goal Years",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Goal Years",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Goal Description",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Goal Description",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Goal Completion Pct",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Goal Completion Pct",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Goal Status",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Goal Status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Performance Status",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Performance Status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Processed At",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Processed At",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "SIP Log"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_SIP_TRACKER_SHEET_ID"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "d0eca2d1-3d7a-4dc0-942a-e1d55693d604",
      "name": "7. Gmail - Send SIP Report to Investor",
      "type": "n8n-nodes-base.gmail",
      "position": [
        2832,
        448
      ],
      "parameters": {
        "sendTo": "={{ $('5. Code - Build HTML SIP Report Email').first().json.email }}",
        "message": "={{ $('5. Code - Build HTML SIP Report Email').first().json.htmlEmail }}",
        "options": {
          "senderName": "SIP Performance Tracker",
          "appendAttribution": false
        },
        "subject": "={{ $('5. Code - Build HTML SIP Report Email').first().json.emailSubject }}"
      },
      "typeVersion": 2.1
    }
  ],
  "active": false,
  "settings": {
    "binaryMode": "separate",
    "executionOrder": "v1"
  },
  "versionId": "530d81fa-37fe-4a47-ac2f-662fa3689f9e",
  "nodeGroups": [],
  "connections": {
    "1. Form - Investor SIP Details": {
      "main": [
        [
          {
            "node": "2. Code - Calculate SIP Performance Metrics",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "3. HTTP - AI Write SIP Advisory": {
      "main": [
        [
          {
            "node": "4. Code - Parse Advisory + Assign Colors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "5. Code - Build HTML SIP Report Email": {
      "main": [
        [
          {
            "node": "6. Sheets - Save SIP Record",
            "type": "main",
            "index": 0
          },
          {
            "node": "7. Gmail - Send SIP Report to Investor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "4. Code - Parse Advisory + Assign Colors": {
      "main": [
        [
          {
            "node": "5. Code - Build HTML SIP Report Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2. Code - Calculate SIP Performance Metrics": {
      "main": [
        [
          {
            "node": "3. HTTP - AI Write SIP Advisory",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}