{
  "name": "Dairy Milk Collection & Quality Pricing",
  "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": "423cfe1c-9acb-43c5-8861-8f1dbb43470a",
      "name": "Milk Entry Form Trigger",
      "webhookId": "62b65991-9c27-499c-a915-7f80d6966c2b"
    },
    {
      "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": "8973d743-75c7-48d7-830b-a45ba121c065",
      "name": "Validate Milk Input"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc",
          "mode": "list",
          "cachedResultName": "Milk Collection Sheet"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1"
        },
        "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": "f1f7a340-3b9f-4984-8ecd-3638073a0e31",
      "name": "Check Duplicate Entry (Sheet)",
      "alwaysOutputData": true,
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "Pkc8jJJZleMSmXoy",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "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": "1995aa2b-de15-4f63-92d0-93e28fcc5eb2",
      "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": "2396cff0-7011-42dc-8297-2aded49fbd57",
      "name": "Send Duplicate Alert Message",
      "credentials": {
        "twilioApi": {
          "id": "x3JY36aoL50A71ad",
          "name": "Twilio account"
        }
      }
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc",
          "mode": "list",
          "cachedResultName": "Milk Collection Sheet"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1"
        },
        "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": "3f98e5e8-c220-4adc-9b9f-c2893c826430",
      "name": "Save Milk Entry",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "Pkc8jJJZleMSmXoy",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "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: ${{ $json.Rate }} / L\nTotal Amount: ${{ $json.Amount }}\n\nThank you for your contribution 🙏",
        "options": {}
      },
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        1392,
        48
      ],
      "id": "a9097e0e-4e94-4b63-b842-3b4af7eb6eb5",
      "name": "Send Success Message",
      "credentials": {
        "twilioApi": {
          "id": "x3JY36aoL50A71ad",
          "name": "Twilio account"
        }
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 18
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        384
      ],
      "id": "02a669fa-f7cb-48d5-b2f0-3b9afa5e6f63",
      "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": "dcfad1df-7e61-4d04-a55b-da7babfff45b",
      "name": "Aggregate Milk Data"
    },
    {
      "parameters": {
        "jsCode": "// 🟢 Check whether data exists\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": "0407c7dc-6016-4dbf-b9b3-f4792d6d704e",
      "name": "Generate Report Message"
    },
    {
      "parameters": {
        "from": "whatsapp:+14155238886",
        "to": "whatsapp:+15555550101",
        "message": "={{ $json.message }}",
        "options": {}
      },
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        864,
        384
      ],
      "id": "d40df75b-f200-4fa3-8c25-a41f4e3b2e81",
      "name": "Send WhatsApp Alert",
      "credentials": {
        "twilioApi": {
          "id": "x3JY36aoL50A71ad",
          "name": "Twilio account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Google Sheet\nCreate your own spreadsheet with these tabs/columns, then select it in the Google Sheets nodes:\n- **Milk Collection Sheet → Sheet1**: `Farmer Name`, `Collection Date`, `Session`, `Farmer ID`, `Mobile Number`, `Milk Quantity`, `Fat (%)`, `SNF (%)`, `Collection Center`, `Operator Name`, `Remarks`, `Quality`, `Rate`, `Amount`, `Created At`",
        "height": 144,
        "width": 320
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -400,
        -256
      ],
      "id": "6438647f-835b-41c2-bb14-a5e14f6fb3d4",
      "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": "4f98e037-b5d1-4bd5-9a89-a06d136351da",
      "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": "eccb4dd5-12a3-472f-b534-16602232277a",
      "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": "50ef2a70-0065-4b8b-94d6-f5fcd6e16d3d",
      "name": "Send Invalid Input Alert",
      "credentials": {
        "twilioApi": {
          "id": "x3JY36aoL50A71ad",
          "name": "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 = 0.45;\nconst rate = base_rate + (fat * 0.03) + (snf * 0.02);\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 * 100) / 100,\n      total_amount: Math.round(total_amount * 100) / 100\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        960,
        48
      ],
      "id": "f4bdc796-34bb-4689-9089-e6b88ef1219a",
      "name": "Calculate Qty, Rate & Amount"
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "value": "1CFvdFYh6_NlKXnW6uh3Fdycjs3fgh2vV_Rspb-enccc",
          "mode": "list",
          "cachedResultName": "Milk Collection Sheet"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "Collection Date",
              "lookupValue": "={{$now.format('yyyy-MM-dd')}}"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        208,
        384
      ],
      "id": "7d1a52ad-022b-41cf-896a-9bfdcebbc9a2",
      "name": "Fetch Today Milk Records",
      "alwaysOutputData": true,
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "Pkc8jJJZleMSmXoy",
          "name": "Google Sheets account"
        }
      }
    }
  ],
  "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": "c4f84ba0-a9dc-4b8d-ba77-bbc2000e24ef",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "f1c26778ec36097a9722a22c47c5e9c01f00b8862dadd0121ec118026a370fa6"
  },
  "id": "i6SdTDhk6GnirkTR",
  "tags": []
}