{
  "name": "AI-Based Dairy Milk Collection & Quality Pricing Workflow",
  "nodes": [
    {
      "parameters": {
        "formTitle": "Milk Collection Entry Form",
        "formDescription": "Enter daily milk collection details including farmer information, milk quantity, and quality (Fat & SNF). This data will be used for automatic rate calculation and payment processing.",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Farmer ID",
              "placeholder": "Farmer ID",
              "requiredField": true
            },
            {
              "fieldLabel": "Farmer Name",
              "placeholder": "Farmer Name",
              "requiredField": true
            },
            {
              "fieldLabel": "Mobile Number",
              "fieldType": "number"
            },
            {
              "fieldLabel": "Collection Date",
              "fieldType": "date"
            },
            {
              "fieldLabel": "Session",
              "fieldType": "dropdown",
              "fieldOptions": {
                "values": [
                  {
                    "option": "Morning"
                  },
                  {
                    "option": "Evening"
                  }
                ]
              },
              "requiredField": true
            },
            {
              "fieldLabel": "Milk Quantity",
              "fieldType": "number",
              "placeholder": "Milk Quantity (Min: 0, Step: 0.1)",
              "requiredField": true
            },
            {
              "fieldLabel": "Fat (%)",
              "fieldType": "number",
              "placeholder": "Fat (%) (Range: 2 - 10)",
              "requiredField": true
            },
            {
              "fieldLabel": "SNF (%)",
              "fieldType": "number"
            },
            {
              "fieldLabel": "Collection Center"
            },
            {
              "fieldLabel": "Operator Name"
            },
            {
              "fieldLabel": "Remarks",
              "fieldType": "textarea"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.5,
      "position": [
        0,
        0
      ],
      "id": "90cae82a-f2fa-4923-8055-1e2cfbdbc475",
      "name": "Milk Entry Form Trigger",
      "webhookId": "fd569648-be85-46c9-b504-6b6d07dea3f3"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "6f7e27ab-9c37-4d49-b636-59d2909ce5fa",
              "leftValue": "={{$json[\"Milk Quantity\"] > 0 \n&& Number($json[\"Milk Quantity\"]).toFixed(1) == $json[\"Milk Quantity\"]\n&& $json[\"Fat (%)\"] >= 2 \n&& $json[\"Fat (%)\"] <= 10 \n&& $json[\"SNF (%)\"] >= 6 \n&& $json[\"SNF (%)\"] <= 10}}",
              "rightValue": "true",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        208,
        0
      ],
      "id": "f44253e0-7ce2-4b05-ba97-e4f3db4c6aa2",
      "name": "Validate Milk Input"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc",
          "mode": "list",
          "cachedResultName": "Milk Collection Sheet",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc/edit#gid=0"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "Farmer Name",
              "lookupValue": "={{$json[\"Farmer Name\"]}}"
            },
            {
              "lookupColumn": "Collection Date",
              "lookupValue": "={{$json[\"Collection Date\"]}}"
            },
            {
              "lookupColumn": "Session",
              "lookupValue": "={{$json[\"Session\"]}}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        496,
        -128
      ],
      "id": "3203d566-911c-4900-ad56-f204a0cc11eb",
      "name": "Check Duplicate Entry (Sheet)",
      "alwaysOutputData": true,
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "wQXWIxCRV7ybbbNL",
          "name": "heet - Google Sheets"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "55cdebd9-6f98-48b6-97cc-48c48a6edc23",
              "leftValue": "={{$json[\"Farmer ID\"] !== undefined}}",
              "rightValue": 0,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        704,
        -128
      ],
      "id": "32287470-d05e-4de7-994b-2d6c28c87f09",
      "name": "Is Duplicate Entry?"
    },
    {
      "parameters": {
        "from": "whatsapp:+14155238886",
        "to": "=whatsapp:+{{ $('Milk Entry Form Trigger').item.json['Mobile Number'] }}",
        "message": "=Duplicate Entry Alert ⚠️\n\nFarmer: {{$json[\"Farmer Name\"]}}\nDate: {{$json[\"Collection Date\"]}}\nSession: {{$json[\"Session\"]}}\n\nThis entry already exists. ❌",
        "options": {}
      },
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        992,
        -272
      ],
      "id": "437ecf9d-756e-4e49-87fe-62d9aeec69de",
      "name": "Send Duplicate Alert Message",
      "credentials": {
        "twilioApi": {
          "id": "R6dWWTJFACSwxUGe",
          "name": "tarec16401 - twilio account"
        }
      }
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc",
          "mode": "list",
          "cachedResultName": "Milk Collection Sheet",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc/edit#gid=0"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Farmer ID": "={{ $('Validate Milk Input').item.json['Farmer ID'] }}",
            "Farmer Name": "={{ $('Validate Milk Input').item.json['Farmer Name'] }}",
            "Mobile Number": "={{ $('Validate Milk Input').item.json['Mobile Number'] }}",
            "Collection Date": "={{ $('Validate Milk Input').item.json['Collection Date'] }}",
            "Session": "={{ $('Validate Milk Input').item.json.Session }}",
            "Milk Quantity": "={{ $('Validate Milk Input').item.json['Milk Quantity'] }}",
            "Fat (%)": "={{ $('Validate Milk Input').item.json['Fat (%)'] }}",
            "SNF (%)": "={{ $('Validate Milk Input').item.json['SNF (%)'] }}",
            "Collection Center": "={{ $('Validate Milk Input').item.json['Collection Center'] }}",
            "Operator Name": "={{ $('Validate Milk Input').item.json['Operator Name'] }}",
            "Remarks": "={{ $('Validate Milk Input').item.json.Remarks }}",
            "Quality": "={{ $json.quality }}",
            "Rate": "={{ $json.rate }}",
            "Amount": "={{ $json.total_amount }}",
            "Created At": "={{ $('Validate Milk Input').item.json.submittedAt }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Farmer ID",
              "displayName": "Farmer ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Farmer Name",
              "displayName": "Farmer Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Mobile Number",
              "displayName": "Mobile Number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Collection Date",
              "displayName": "Collection Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Session",
              "displayName": "Session",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Milk Quantity",
              "displayName": "Milk Quantity",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Fat (%)",
              "displayName": "Fat (%)",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "SNF (%)",
              "displayName": "SNF (%)",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Collection Center",
              "displayName": "Collection Center",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Operator Name",
              "displayName": "Operator Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Remarks",
              "displayName": "Remarks",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Quality",
              "displayName": "Quality",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Rate",
              "displayName": "Rate",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Amount",
              "displayName": "Amount",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Created At",
              "displayName": "Created At",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1168,
        48
      ],
      "id": "962e9b67-960b-48d2-b0d7-54d4ab1d09f0",
      "name": "Save Milk Entry",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "wQXWIxCRV7ybbbNL",
          "name": "heet - Google Sheets"
        }
      }
    },
    {
      "parameters": {
        "from": "whatsapp:+14155238886",
        "to": "=whatsapp:+{{ $('Milk Entry Form Trigger').item.json['Mobile Number'] }}",
        "message": "=Milk Collection Successful 🥛\n\nFarmer: {{$json[\"Farmer Name\"]}}\nDate: {{$json[\"Collection Date\"]}}\nSession: {{$json[\"Session\"]}}\n\nQuantity: {{$json[\"Milk Quantity\"]}} L\nFat: {{$json[\"Fat (%)\"]}}%\nSNF: {{$json[\"SNF (%)\"]}}%\n\nRate: ₹70 / L\nTotal Amount: ₹{{ $json.Amount }}\n\nThank you for your contribution 🙏",
        "options": {}
      },
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        1392,
        48
      ],
      "id": "2044e145-b9c2-4f5d-a7de-68e0e31e77f8",
      "name": "Send Success Message",
      "credentials": {
        "twilioApi": {
          "id": "R6dWWTJFACSwxUGe",
          "name": "tarec16401 - twilio account"
        }
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 18
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        384
      ],
      "id": "6f12158c-ae5d-4504-a2ea-4ab3fe75692e",
      "name": "Daily Scheduler"
    },
    {
      "parameters": {
        "jsCode": "\nif (!$json[\"row_number\"]) {\n  return [\n    {\n      json: {\n        message: \"No data for today\",\n        date: new Date().toISOString().split('T')[0],\n        totalMilk: 0,\n        totalAmount: 0,\n        avgFat: 0\n      }\n    }\n  ];\n}\n\n\nconst data = items.map(i => i.json);\n\nlet totalMilk = 0;\nlet totalAmount = 0;\nlet totalFat = 0;\n\ndata.forEach(d => {\n  totalMilk += Number(d[\"Milk Quantity\"] || 0);\n  totalAmount += Number(d[\"Amount\"] || 0);\n  totalFat += Number(d[\"Fat (%)\"] || 0);\n});\n\nconst avgFat = data.length ? (totalFat / data.length) : 0;\n\n\nreturn [\n  {\n    json: {\n      message: \"Today's Total milk count.\",\n      date: new Date().toISOString().split('T')[0],\n      totalMilk,\n      totalAmount,\n      avgFat: avgFat.toFixed(2)\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        432,
        384
      ],
      "id": "f5b1d601-3daa-43ff-8b18-aebc5f7e560d",
      "name": "Aggregate Milk Data"
    },
    {
      "parameters": {
        "jsCode": "// 🟢 Check data exists ke nahi\nconst hasData = $json.totalMilk && Number($json.totalMilk) > 0;\n\n// 🟢 Common Date\nconst date = new Date().toISOString().split('T')[0];\n\n// 🟢 Message Generate\nlet message = \"\";\n\nif (!hasData) {\n  // ❌ No Data Message\n  message = `📊 Daily Milk Report\n\nDate: ${date}\n\n❌ No milk collection data found for today.\n\nPlease check collection center.`;\n} else {\n  // ✅ Data Available Message\n  message = `📊 Daily Milk Report\n\nDate: ${date}\n\n🥛 Total Milk: ${$json.totalMilk} L\n💰 Total Amount: ₹${$json.totalAmount}\n🧪 Avg Fat: ${$json.avgFat}%\n\n✅ Report generated successfully`;\n}\n\n// 🟢 Final Return\nreturn [\n  {\n    json: {\n      ...$json,\n      message\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        640,
        384
      ],
      "id": "22300daa-5357-46d6-abf8-2230c34c8db9",
      "name": "Generate Report Message"
    },
    {
      "parameters": {
        "from": "whatsapp:+14155238886",
        "to": "whatsapp:+918849216727",
        "message": "={{ $json.message }}",
        "options": {}
      },
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        864,
        384
      ],
      "id": "f16dbb03-6a18-45ad-aa3d-39bf6355355c",
      "name": "Send WhatsApp Alert",
      "credentials": {
        "twilioApi": {
          "id": "R6dWWTJFACSwxUGe",
          "name": "tarec16401 - twilio account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Google Sheet\nhttps://docs.google.com/spreadsheets/d/1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc/edit?gid=0#gid=0",
        "height": 144,
        "width": 320
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -400,
        -256
      ],
      "id": "14f4eb4c-231a-48e6-bee4-91e4b7f951ad",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "## Daily Milk Report Generation & WhatsApp Notification Scheduled",
        "height": 128,
        "width": 304
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -400,
        368
      ],
      "id": "1d649a28-2b16-4c36-96a8-bf8e41461671",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "content": "## Milk Collection Input & Storage Automation On Demand",
        "height": 144,
        "width": 320
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -400,
        -16
      ],
      "id": "00dc7b0e-d612-41e6-8feb-e6f31fe73fc6",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "from": "whatsapp:+14155238886",
        "to": "=whatsapp:+{{ $('Milk Entry Form Trigger').item.json['Mobile Number'] }}",
        "message": "=❌ Invalid Milk Entry\n\nFarmer: {{$json[\"Farmer Name\"]}}\n\nPlease check:\nMilk: {{$json[\"Milk Quantity\"]}}\nFat: {{$json[\"Fat (%)\"]}}\nSNF: {{$json[\"SNF (%)\"]}}\n\n❗ Values out of allowed range.",
        "options": {}
      },
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        480,
        112
      ],
      "id": "7f3fb2ae-1425-42ee-bb6c-b016bfaef926",
      "name": "Send Invalid Input Alert",
      "credentials": {
        "twilioApi": {
          "id": "R6dWWTJFACSwxUGe",
          "name": "tarec16401 - twilio account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// 🔹 Get data from \"Validate Milk Input\" node\nconst data = $('Validate Milk Input').first().json;\n\nconst fat = Number(data[\"Fat (%)\"]);\nconst snf = Number(data[\"SNF (%)\"]);\nconst qty = Number(data[\"Milk Quantity\"]);\n\n// 🔹 1. Quality Analysis\nlet quality = \"normal\";\nif (fat > 6) quality = \"premium\";\nelse if (fat < 3) quality = \"low\";\n\n// 🔹 2. Rate Calculation\nconst base_rate = 70;\nconst rate = base_rate + (fat * 1.5) + (snf * 1);\n\n// 🔹 3. Total Amount\nconst total_amount = qty * rate;\n\n// 🔹 Final Return\nreturn [\n  {\n    json: {\n      ...data,\n      quality,\n      rate: Math.round(rate),\n      total_amount: Math.round(total_amount)\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        48
      ],
      "id": "a3e89077-0d8e-4fdf-bcaf-fdb2a6689c1c",
      "name": "Calculate Qty, Rate & Amount"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc",
          "mode": "list",
          "cachedResultName": "Milk Collection Sheet",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc/edit#gid=0"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "Collection Date",
              "lookupValue": "={{$now.format('yyyy-MM-dd')}}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        208,
        384
      ],
      "id": "ed19c5cc-91ea-4046-8f8b-a971294a05da",
      "name": "Fetch Today Milk Records",
      "alwaysOutputData": true,
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "wQXWIxCRV7ybbbNL",
          "name": "heet - Google Sheets"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "Milk Entry Form Trigger": {
      "main": [
        [
          {
            "node": "Validate Milk Input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Milk Input": {
      "main": [
        [
          {
            "node": "Check Duplicate Entry (Sheet)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send Invalid Input Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Duplicate Entry (Sheet)": {
      "main": [
        [
          {
            "node": "Is Duplicate Entry?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is Duplicate Entry?": {
      "main": [
        [
          {
            "node": "Send Duplicate Alert Message",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Calculate Qty, Rate & Amount",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Milk Entry": {
      "main": [
        [
          {
            "node": "Send Success Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily Scheduler": {
      "main": [
        [
          {
            "node": "Fetch Today Milk Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Milk Data": {
      "main": [
        [
          {
            "node": "Generate Report Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Report Message": {
      "main": [
        [
          {
            "node": "Send WhatsApp Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Qty, Rate & Amount": {
      "main": [
        [
          {
            "node": "Save Milk Entry",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Today Milk Records": {
      "main": [
        [
          {
            "node": "Aggregate Milk Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate"
  },
  "versionId": "319fd5c3-1bf4-4bd4-9e65-80dfc2f4b6bc",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "9272721148ea09184b6bbb7ce6219dab088562dd450e2df8280d57c2e34c7d84"
  },
  "id": "5BP1fckJt8WVxyyR",
  "tags": []
}