{
  "name": "Crop Planning",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "ai-crop-planning",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "5aa25d41-2715-4520-a63c-c1b9f6419a67",
      "name": "AI Planning Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// AI Crop Planning Logic\nvar request = $input.all()[0].json;\n// Added this so we could access data within the request body\nrequest = request.body;\n\n// Validate AI planning specific requests\nif (!request.data || !request.data.crop_type) {\n  console.log(request)\n  throw new Error('Error no data or crop_type');\n}\n\n// Extract planning parameters\nconst planningParams = {\n  cropType: request.data.crop_type,\n  season: request.data.season || 'current',\n  location: request.data.location || 'unknown',\n  plotSize: request.data.plot_size || '100_sq_ft',\n  soilType: request.data.soil_type || 'mixed',\n  userId: request.userId,\n  orchestratorId: request.routing?.orchestratorId\n};\n\n// Prepare AI prompt based on action type\nlet aiPrompt = '';\nswitch(request.action) {\n  case 'ai_schedule':\n    aiPrompt = `Create a detailed planting and harvest schedule for ${planningParams.cropType} in ${planningParams.season} season. Location: ${planningParams.location}. Plot size: ${planningParams.plotSize}. Include: optimal planting dates, growth milestones, care instructions, harvest timeline, and expected yield.`;\n    break;\n  case 'crop_optimization':\n    aiPrompt = `Optimize growing conditions for ${planningParams.cropType} in ${planningParams.location}. Soil type: ${planningParams.soilType}. Provide specific recommendations for: soil preparation, spacing, companion planting, pest management, and yield maximization techniques.`;\n    break;\n  case 'harvest_prediction':\n    aiPrompt = `Predict harvest timing and yield for ${planningParams.cropType} planted in ${planningParams.season}. Consider location: ${planningParams.location} and plot size: ${planningParams.plotSize}. Include harvest windows, quality indicators, and storage recommendations.`;\n    break;\n  default:\n    aiPrompt = `General agricultural advice for ${planningParams.cropType} cultivation.`;\n}\n\nconsole.log('AI Planning - Processing:', planningParams);\n\nreturn [{\n  ...request,\n  aiPrompt,\n  planningParams\n}];"
      },
      "id": "68f79fee-dde8-4794-96df-7954456cb68a",
      "name": "AI Planning Logic",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        224,
        0
      ]
    },
    {
      "parameters": {
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "table": "ai_planning_requests",
        "columns": {
          "0": "u",
          "1": "s",
          "2": "e",
          "3": "r",
          "4": "_",
          "5": "i",
          "6": "d",
          "7": ",",
          "8": " ",
          "9": "o",
          "10": "r",
          "11": "c",
          "12": "h",
          "13": "e",
          "14": "s",
          "15": "t",
          "16": "r",
          "17": "a",
          "18": "t",
          "19": "o",
          "20": "r",
          "21": "_",
          "22": "i",
          "23": "d",
          "24": ",",
          "25": " ",
          "26": "c",
          "27": "r",
          "28": "o",
          "29": "p",
          "30": "_",
          "31": "t",
          "32": "y",
          "33": "p",
          "34": "e",
          "35": ",",
          "36": " ",
          "37": "s",
          "38": "e",
          "39": "a",
          "40": "s",
          "41": "o",
          "42": "n",
          "43": ",",
          "44": " ",
          "45": "l",
          "46": "o",
          "47": "c",
          "48": "a",
          "49": "t",
          "50": "i",
          "51": "o",
          "52": "n",
          "53": ",",
          "54": " ",
          "55": "a",
          "56": "c",
          "57": "t",
          "58": "i",
          "59": "o",
          "60": "n",
          "61": "_",
          "62": "t",
          "63": "y",
          "64": "p",
          "65": "e",
          "66": ",",
          "67": " ",
          "68": "a",
          "69": "i",
          "70": "_",
          "71": "p",
          "72": "r",
          "73": "o",
          "74": "m",
          "75": "p",
          "76": "t",
          "77": ",",
          "78": " ",
          "79": "s",
          "80": "t",
          "81": "a",
          "82": "t",
          "83": "u",
          "84": "s",
          "85": ",",
          "86": " ",
          "87": "c",
          "88": "r",
          "89": "e",
          "90": "a",
          "91": "t",
          "92": "e",
          "93": "d",
          "94": "_",
          "95": "a",
          "96": "t",
          "mappingMode": "defineBelow",
          "value": {
            "user_id": "={{ $json.userId }}",
            "orchestrator_id": "={{ $json.planningParams.orchestratorId }}",
            "season": "={{ $json.planningParams.season }}",
            "crop_type": "={{ $json.planningParams.cropType }}",
            "location": "={{ $json.planningParams.location }}",
            "action_type": "={{ $json.action }}",
            "ai_prompt": "={{ $json.aiPrompt }}",
            "status": "open"
          },
          "matchingColumns": [
            "id"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "user_id",
              "displayName": "user_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "orchestrator_id",
              "displayName": "orchestrator_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "crop_type",
              "displayName": "crop_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "season",
              "displayName": "season",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "location",
              "displayName": "location",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "action_type",
              "displayName": "action_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "ai_prompt",
              "displayName": "ai_prompt",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "dateTime",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "f6f9a25d-7d3e-4901-81e2-26ce2a9ce423",
      "name": "Log AI Request to DB",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.4,
      "position": [
        448,
        0
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Process AI response and structure for database storage\nconst aiResponse = $input.all()[0].json;\nconst originalRequest = $('AI Planning Logic').item.json;\n\n// Extract AI recommendations\nlet recommendations = '';\nif (aiResponse.generated_text) {\n  recommendations = aiResponse.generated_text;\n} else if (aiResponse[0] && aiResponse[0].generated_text) {\n  recommendations = aiResponse[0].generated_text;\n} else {\n  recommendations = 'AI service unavailable - using fallback recommendations';\n}\n\n// Structure the planning result\nconst planningResult = {\n  userId: originalRequest.userId,\n  orchestratorId: originalRequest.orchestratorId,\n  cropType: originalRequest.planningParams.cropType,\n  season: originalRequest.planningParams.season,\n  location: originalRequest.planningParams.location,\n  actionType: originalRequest.action,\n  aiRecommendations: $input.first().json.content.parts[0].text,\n  confidence: aiResponse.confidence || 0.8,\n  generatedAt: new Date().toISOString(),\n  status: 'completed'\n};\n\n// Calculate estimated planting/harvest dates based on crop type\nconst today = new Date();\nconst plantingDate = new Date(today.getTime() + (7 * 24 * 60 * 60 * 1000)); // 1 week from now\nlet harvestDate = new Date(plantingDate);\n\n// Basic harvest timing by crop type (days to harvest)\nconst cropTimings = {\n  'tomatoes': 80,\n  'lettuce': 45,\n  'carrots': 70,\n  'beans': 60,\n  'corn': 100,\n  'peppers': 85,\n  'squash': 95\n};\n\nconst daysToHarvest = cropTimings[originalRequest.planningParams.cropType.toLowerCase()] || 75;\nharvestDate.setDate(plantingDate.getDate() + daysToHarvest);\n\nplanningResult.estimatedPlantingDate = plantingDate.toISOString().split('T')[0];\nplanningResult.estimatedHarvestDate = harvestDate.toISOString().split('T')[0];\n\nconsole.log('AI Planning Result:', planningResult);\n\nreturn [planningResult];"
      },
      "id": "2c4b57ef-8366-41d6-8e92-10a71324d472",
      "name": "Process AI Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1504,
        0
      ]
    },
    {
      "parameters": {
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "table": "crop_plans",
        "columns": {
          "0": "u",
          "1": "s",
          "2": "e",
          "3": "r",
          "4": "_",
          "5": "i",
          "6": "d",
          "7": ",",
          "8": " ",
          "9": "o",
          "10": "r",
          "11": "c",
          "12": "h",
          "13": "e",
          "14": "s",
          "15": "t",
          "16": "r",
          "17": "a",
          "18": "t",
          "19": "o",
          "20": "r",
          "21": "_",
          "22": "i",
          "23": "d",
          "24": ",",
          "25": " ",
          "26": "c",
          "27": "r",
          "28": "o",
          "29": "p",
          "30": "_",
          "31": "t",
          "32": "y",
          "33": "p",
          "34": "e",
          "35": ",",
          "36": " ",
          "37": "s",
          "38": "e",
          "39": "a",
          "40": "s",
          "41": "o",
          "42": "n",
          "43": ",",
          "44": " ",
          "45": "l",
          "46": "o",
          "47": "c",
          "48": "a",
          "49": "t",
          "50": "i",
          "51": "o",
          "52": "n",
          "53": ",",
          "54": " ",
          "55": "a",
          "56": "c",
          "57": "t",
          "58": "i",
          "59": "o",
          "60": "n",
          "61": "_",
          "62": "t",
          "63": "y",
          "64": "p",
          "65": "e",
          "66": ",",
          "67": " ",
          "68": "a",
          "69": "i",
          "70": "_",
          "71": "r",
          "72": "e",
          "73": "c",
          "74": "o",
          "75": "m",
          "76": "m",
          "77": "e",
          "78": "n",
          "79": "d",
          "80": "a",
          "81": "t",
          "82": "i",
          "83": "o",
          "84": "n",
          "85": "s",
          "86": ",",
          "87": " ",
          "88": "e",
          "89": "s",
          "90": "t",
          "91": "i",
          "92": "m",
          "93": "a",
          "94": "t",
          "95": "e",
          "96": "d",
          "97": "_",
          "98": "p",
          "99": "l",
          "100": "a",
          "101": "n",
          "102": "t",
          "103": "i",
          "104": "n",
          "105": "g",
          "106": "_",
          "107": "d",
          "108": "a",
          "109": "t",
          "110": "e",
          "111": ",",
          "112": " ",
          "113": "e",
          "114": "s",
          "115": "t",
          "116": "i",
          "117": "m",
          "118": "a",
          "119": "t",
          "120": "e",
          "121": "d",
          "122": "_",
          "123": "h",
          "124": "a",
          "125": "r",
          "126": "v",
          "127": "e",
          "128": "s",
          "129": "t",
          "130": "_",
          "131": "d",
          "132": "a",
          "133": "t",
          "134": "e",
          "135": ",",
          "136": " ",
          "137": "c",
          "138": "o",
          "139": "n",
          "140": "f",
          "141": "i",
          "142": "d",
          "143": "e",
          "144": "n",
          "145": "c",
          "146": "e",
          "147": "_",
          "148": "s",
          "149": "c",
          "150": "o",
          "151": "r",
          "152": "e",
          "153": ",",
          "154": " ",
          "155": "s",
          "156": "t",
          "157": "a",
          "158": "t",
          "159": "u",
          "160": "s",
          "161": ",",
          "162": " ",
          "163": "c",
          "164": "r",
          "165": "e",
          "166": "a",
          "167": "t",
          "168": "e",
          "169": "d",
          "170": "_",
          "171": "a",
          "172": "t",
          "mappingMode": "defineBelow",
          "value": {
            "id": 0,
            "confidence_score": 0
          },
          "matchingColumns": [
            "id"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "user_id",
              "displayName": "user_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "orchestrator_id",
              "displayName": "orchestrator_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "crop_type",
              "displayName": "crop_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "season",
              "displayName": "season",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "location",
              "displayName": "location",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "action_type",
              "displayName": "action_type",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "ai_recommendations",
              "displayName": "ai_recommendations",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "estimated_planting_date",
              "displayName": "estimated_planting_date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "dateTime",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "estimated_harvest_date",
              "displayName": "estimated_harvest_date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "dateTime",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "confidence_score",
              "displayName": "confidence_score",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "status",
              "displayName": "status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "dateTime",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "3970b0fd-3cfb-4b1c-8197-286fce19e7ef",
      "name": "Save Crop Plan to DB",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.4,
      "position": [
        1712,
        -272
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "url": "https://n8n.collective.local/webhook/microinvestment",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"action\": \"check_tool_needs\",\n  \"role\": \"system\",\n  \"userId\": \"{{ $json.userId }}\",\n  \"data\": {\n    \"crop_type\": \"{{ $json.cropType }}\",\n    \"season\": \"{{ $json.season }}\",\n    \"plot_size\": \"{{ $('AI Planning Logic').item.json.planningParams.plotSize }}\",\n    \"recommendations\": \"{{ $json.aiRecommendations }}\",\n    \"check_type\": \"tool_optimization\"\n  }\n}",
        "options": {
          "timeout": 15000
        }
      },
      "id": "08058e0e-8fe8-454a-a4c5-4dd07daea218",
      "name": "Check for Tool Investment Opportunities",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1936,
        -256
      ]
    },
    {
      "parameters": {
        "jsCode": "// Prepare final response for orchestrator\nconst cropPlan = $('Process AI Response').item.json;\nconst toolCheck = $input.all()[0].json;\n\nconst finalResponse = {\n  success: true,\n  workflowType: 'ai-crop-planning',\n  result: {\n    cropPlan: {\n      cropType: cropPlan.cropType,\n      season: cropPlan.season,\n      location: cropPlan.location,\n      estimatedPlantingDate: cropPlan.estimatedPlantingDate,\n      estimatedHarvestDate: cropPlan.estimatedHarvestDate,\n      aiRecommendations: cropPlan.aiRecommendations,\n      confidence: cropPlan.confidence\n    },\n    toolInvestmentOpportunities: toolCheck.success ? toolCheck.recommendations : [],\n    nextSteps: [\n      'Review AI recommendations',\n      'Check microinvestment opportunities',\n      'Schedule planting activities',\n      'Set harvest reminders'\n    ]\n  },\n  timestamp: new Date().toISOString(),\n  orchestratorId: cropPlan.orchestratorId\n};\n\nconsole.log('AI Planning - Final Response:', finalResponse);\n\nreturn [finalResponse];"
      },
      "id": "05e027fd-cd2d-44a5-81f8-3e055ed05eb4",
      "name": "Prepare Final Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2112,
        -256
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json }}",
        "options": {}
      },
      "id": "2c53d7ef-8715-4aff-bd1c-8f2135b3cfc3",
      "name": "AI Planning Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        1744,
        0
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('AI Planning Logic').item.json.model }}",
                    "rightValue": "gemini",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "1475837c-0671-44c7-ad6d-06b354c808bb"
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "f8473bae-aab5-472d-bfa4-7ef595a7cf48",
                    "leftValue": "={{ $('AI Planning Logic').item.json.model }}",
                    "rightValue": "chatgpt",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              }
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        656,
        0
      ],
      "id": "a2538499-40e4-4801-a507-4d3ee24171f6",
      "name": "Switch"
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.0-flash-lite",
          "mode": "list",
          "cachedResultName": "models/gemini-2.0-flash-lite"
        },
        "messages": {
          "values": [
            {
              "content": "={{ $json.ai_prompt }}"
            }
          ]
        },
        "jsonOutput": true,
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1,
      "position": [
        864,
        -96
      ],
      "id": "02e00c23-6cd8-4333-a625-41b2132c8253",
      "name": "Message a model",
      "credentials": {
        "googlePalmApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-3.5-turbo",
          "mode": "list",
          "cachedResultName": "GPT-3.5-TURBO"
        },
        "messages": {
          "values": [
            {
              "content": "={{ $('AI Planning Logic').item.json.aiPrompt }}"
            }
          ]
        },
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.8,
      "position": [
        864,
        96
      ],
      "id": "68d7bf7c-01cc-40b6-887c-86aaccc0e9b7",
      "name": "Message a model1",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "AI Planning Webhook": {
      "main": [
        [
          {
            "node": "AI Planning Logic",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Planning Logic": {
      "main": [
        [
          {
            "node": "Log AI Request to DB",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log AI Request to DB": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process AI Response": {
      "main": [
        [
          {
            "node": "AI Planning Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Crop Plan to DB": {
      "main": [
        []
      ]
    },
    "Check for Tool Investment Opportunities": {
      "main": [
        []
      ]
    },
    "Prepare Final Response": {
      "main": [
        []
      ]
    },
    "AI Planning Response": {
      "main": [
        []
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Message a model",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Message a model1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Message a model": {
      "main": [
        [
          {
            "node": "Process AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Message a model1": {
      "main": [
        [
          {
            "node": "Process AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "0ec9799c-a2aa-4375-8fa3-9a406ccf1186",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "LZlAHmdNaE09qHJy",
  "tags": [
    {
      "name": "AI Crop Planning",
      "id": "VHYc5GPscHpNLgTe",
      "createdAt": "2025-09-30T13:40:31.657Z",
      "updatedAt": "2025-09-30T13:40:31.657Z"
    }
  ]
}