A modern, full-stack web application for managing dairy farm operations, built with Next.js 14, TypeScript, Prisma, and MySQL. This comprehensive system helps dairy farmers manage every aspect of their operations, from animal care to financial tracking, with advanced automation features.
- Secure login and registration with NextAuth.js
- Role-based access control (Admin/Manager/User)
- Password encryption with bcrypt
- Session management with JWT
- Complete animal profiles with unique tag numbers
- Track breed, age, gender, and health status
- Record purchase information and current weight
- View complete animal history and timeline
- Full CRUD operations (Create, Read, Update, Delete)
- Individual animal view with detailed information
- Animal status tracking (Active, Sold, Deceased, Transferred)
- Record health examinations and treatments
- Track diseases, symptoms, and medications
- Assign veterinarians and record costs
- Schedule follow-up checkups
- Health status monitoring (Healthy, Under Treatment, Critical, Recovered)
- Complete health history per animal
- Monitor animal growth and body condition
- Track weight changes over time
- Record height and body condition scores
- Visual weight progression charts
- Growth analytics and trends
- Manage breeding cycles (Natural & Artificial Insemination)
- Track male and female animals in breeding
- Expected and actual delivery dates
- Record breeding outcomes (Successful, Failed, Aborted, Pending)
- Offspring tracking and breeding costs
- Daily milk production recording (Morning, Afternoon, Evening)
- Automatic total calculation
- Quality assessment (Excellent, Good, Average, Poor)
- Fat content tracking
- Per-animal production tracking
- Production reports and analytics
- Customer Management Integration
- Complete customer database with contact details
- Default price per customer
- Purchase history tracking
- Smart Payment System
- Track total amount vs. amount paid
- Customer Balance Management (Credit/Due tracking)
- Auto-payment from customer credit balance
- Support for advance payments
- Payment status tracking (Paid, Pending, Overdue)
- Automatic Financial Integration
- Auto-create income records when payment status is PAID
- Track cash payments separately
- Detailed transaction history
- Auto-Settle Pending Dues
- One-click settlement of pending dues from customer credit
- Intelligent partial payment handling
- Oldest dues settled first
- Automatic status updates
- Real-time stock calculation (Production - Sales)
- Current milk stock display on dashboard
- Color-coded stock alerts (Low, Medium, High)
- Weekly and monthly stock analysis
- Dedicated milk stock page with detailed analytics
- Recent activity tracking (Production & Sales)
- Complete customer database
- Contact information (Phone, Email, Address)
- Default pricing per customer
- Customer Balance Tracking
- Positive balance = Advance/Credit
- Negative balance = Due/Pending payment
- Total purchases tracking
- Last purchase date
- Full purchase history with due amounts
- Customer-wise sales reports
- Feed type management (Concentrate, Roughage, Supplements)
- Purchase tracking with supplier information
- Expiry date monitoring
- Current stock levels
- Minimum stock alerts
- Cost tracking per unit
- Auto-integration with Finance (Expense tracking)
- Employee records with unique IDs
- Position and department tracking
- Contact information
- Salary management
- Join/leave date tracking
- Employee status (Active, Inactive, Terminated, Resigned)
- Comprehensive income tracking
- Milk sales (automatic)
- Balance adjustments
- Other income sources
- Expense tracking
- Stock feed purchases (automatic)
- Health treatments
- Employee salaries
- Other expenses
- Advanced Features
- Automatic integration with Milk Sales
- Automatic integration with Stock Feed
- Transaction categorization
- Reference number tracking
- Detailed descriptions with breakdowns
- Payment method tracking
- Pagination (5 records per page)
- Date-wise filtering
- Financial Analytics
- Income vs. Expense comparison
- Monthly/Yearly summaries
- Profitability tracking
- Real-time Statistics
- Total animals count
- Health alerts
- Today's milk production
- Current milk stock with alerts
- Active employees
- Monthly sales
- Quick Actions (One-click shortcuts)
- Add Milk Production
- Add Milk Sale
- Add Health Record
- Add Stock Feed
- Recent Activity Feed
- Latest milk production records
- Recent milk sales
- New health reports
- Newly added animals
- Recent stock feed purchases
- Time-ago formatting
- Color-coded activity icons
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MILK SALE WORKFLOW โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ 1. Select Customer โ
โ โโ Shows customer's available credit (if any) โ
โ โโ Shows customer's pending dues (if any) โ
โ โโ Auto-fills default price โ
โ โ
โ 2. Enter Sale Details โ
โ โโ Quantity (Liters) โ
โ โโ Price per Liter โ
โ โโ Total Amount = Quantity ร Price โ
โ โ
โ 3. Auto-Payment Calculation โ
โ โโ System checks customer's credit balance โ
โ โโ Auto-applies credit to current sale โ
โ โโ Shows remaining due (if any) โ
โ โ
โ 4. Additional Payment (Optional) โ
โ โโ Customer can pay extra cash โ
โ โ
โ 5. Payment Status (Auto-Updated) โ
โ โโ PAID: If fully paid (credit + cash) โ
โ โโ PENDING: If partial payment โ
โ โ
โ 6. Automatic Backend Actions โ
โ โโ Update customer balance โ
โ โโ Record milk sale โ
โ โโ Create finance income record (if PAID) โ
โ โโ Update customer purchase history โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Example Scenarios:
Scenario A: Customer with Credit
- Customer Balance: +เงณ500 (Advance)
- New Sale: 10L ร เงณ80 = เงณ800
- Auto-payment: เงณ500 from credit
- Customer pays: เงณ300 cash
- Result: Balance = เงณ0, Status = PAID โ
Scenario B: Customer with Insufficient Credit
- Customer Balance: +เงณ200
- New Sale: 10L ร เงณ80 = เงณ800
- Auto-payment: เงณ200 from credit
- Customer pays: เงณ0 cash
- Result: Balance = -เงณ600, Status = PENDING (เงณ600 due)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AUTO-SETTLE PENDING DUES WORKFLOW โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ 1. Customer Gives Advance Payment โ
โ โโ Add เงณ2000 to customer balance โ
โ โ
โ 2. System Detects Pending Dues โ
โ โโ Checks all customer's sales โ
โ โโ Identifies sales with due amounts โ
โ โโ Shows "Auto-Settle" card on customer detail page โ
โ โ
โ 3. View Settlement Preview โ
โ โโ Shows number of pending sales โ
โ โโ Shows total due amount โ
โ โโ Shows available credit โ
โ โโ Indicates full/partial settlement possibility โ
โ โ
โ 4. Click "Auto-Settle Dues" Button โ
โ โโ Confirmation dialog appears โ
โ โ
โ 5. Automatic Settlement Process (Oldest First) โ
โ โโ Get all sales with due amounts โ
โ โโ Sort by date (oldest first) โ
โ โโ Pay each sale using available credit โ
โ โโ Update sale status to PAID (if fully paid) โ
โ โโ Create finance income records โ
โ โโ Update customer's remaining balance โ
โ โ
โ 6. Settlement Complete โ
โ โโ Shows success message โ
โ โโ Displays settled count and amount โ
โ โโ Shows remaining balance โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Example:
- Customer Balance: +เงณ2000
- Pending Sales:
- Oct 1: เงณ500 due โ Paid โ
- Oct 3: เงณ800 due โ Paid โ
- Oct 5: เงณ400 due โ Paid โ
- Total Settled: เงณ1700
- Remaining Balance: เงณ300
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MILK STOCK TRACKING WORKFLOW โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Real-time Calculation: โ
โ โโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ Current Stock = Total Production - Total Sales โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ Milk Production โ โ Milk Sales โ โ
โ โ Record Added โ โ โ Record Added โ โ โ
โ โ (+50L today) โ โ (-30L today) โ โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ โ โ โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Current Stock = 50L - 30L = 20L โ โ
โ โ โ โ
โ โ Status: ๐ด Low Stock (< 50L) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ Dashboard Display: โ
โ โโโโโโโโโโโโโโโโโ โ
โ - Current Stock with color alerts โ
โ - Weekly production vs. sales โ
โ - Monthly trends โ
โ - Recent activities โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AUTOMATIC FINANCE INTEGRATION WORKFLOW โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ INCOME (Automatic): โ
โ โโโโโโโโโโโโโโโโ โ
โ โ
โ Milk Sale (PAID) โ Finance Record Created โ
โ โโ Amount: Cash payment only โ
โ โโ Category: "Milk Sale" โ
โ โโ Description: Details with breakdown โ
โ โโ Reference: MILK-SALE-{id} โ
โ โ
โ Customer Balance Adjustment โ Finance Record Created โ
โ โโ Amount: Adjustment amount โ
โ โโ Category: "Balance Adjustment" โ
โ โโ Reference: BALANCE-ADJ-{id} โ
โ โ
โ โ
โ EXPENSE (Automatic): โ
โ โโโโโโโโโโโโโโโโโ โ
โ โ
โ Stock Feed Purchase โ Finance Record Created โ
โ โโ Amount: Total cost โ
โ โโ Category: "Stock Feed Purchase" โ
โ โโ Description: Feed details โ
โ โโ Reference: STOCKFEED-{id} โ
โ โ
โ Actions that Sync Finance: โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Create โ Finance record created โ
โ โ Update โ Finance record updated โ
โ โ Delete โ Finance record deleted โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ COMPLETE CUSTOMER JOURNEY โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Day 1: Customer Registration โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ - Add new customer: "Karim" โ
โ - Set default price: เงณ80/L โ
โ - Add contact info โ
โ - Initial balance: เงณ0 โ
โ โ
โ Day 2: First Sale (Credit Sale) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ - Sale: 20L ร เงณ80 = เงณ1600 โ
โ - Customer pays: เงณ0 โ
โ - Balance: -เงณ1600 (Due) โ
โ - Status: PENDING โ
โ โ
โ Day 3: Second Sale (More Debt) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ - Sale: 15L ร เงณ80 = เงณ1200 โ
โ - Customer pays: เงณ0 โ
โ - Balance: -เงณ2800 (Total Due) โ
โ - Status: PENDING โ
โ โ
โ Day 5: Customer Gives Advance โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ - Customer pays: เงณ5000 (Advance for future) โ
โ - Balance: -เงณ2800 + เงณ5000 = +เงณ2200 โ
โ โ
โ Day 5: Auto-Settle Pending Dues โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ - Click "Auto-Settle" button โ
โ - System settles 2 pending sales (เงณ2800) โ
โ - Both marked as PAID โ
โ - Finance records created โ
โ - New Balance: +เงณ2200 - เงณ2800 = -เงณ600 (Adjusted) โ
โ โ
โ Day 7: New Sale (Auto-Payment) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ - Sale: 10L ร เงณ80 = เงณ800 โ
โ - Auto-payment from credit: เงณ600 โ
โ - Customer pays cash: เงณ200 โ
โ - Balance: เงณ0 โ
โ - Status: PAID โ โ
โ โ
โ Day 10: New Sale (Advance Payment) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ - Sale: 5L ร เงณ80 = เงณ400 โ
โ - Customer pays: เงณ1000 โ
โ - Balance: +เงณ600 (Credit for next time) โ
โ - Status: PAID โ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Morning:
โโโโโโโโ
1. Login to Dashboard
2. Check health alerts
3. Record morning milk production
4. Check milk stock levels
5. If low stock alert โ Plan sales
Midday:
โโโโโโโ
1. Record any health issues
2. Add animal weight records
3. Check breeding schedules
4. Record afternoon milk production
Evening:
โโโโโโโโ
1. Record evening milk production
2. Process milk sales
- Select customer
- Auto-payment applied
- Update balances
3. Check pending dues
4. Settle dues if customer paid
5. Update stock feed inventory
6. Review financial summary
Weekly:
โโโโโโโ
1. Analyze milk production trends
2. Review customer balances
3. Settle pending dues
4. Check stock feed levels
5. Employee attendance/salary
6. Financial reports
Monthly:
โโโโโโโโ
1. Complete financial analysis
2. Customer payment review
3. Health record summary
4. Breeding outcomes
5. Profitability assessment
- Framework: Next.js 14 (App Router)
- Language: TypeScript
- Database: PostgreSQL with Prisma ORM ๐
- Authentication: NextAuth.js v4
- UI Components: Radix UI + Tailwind CSS
- Styling: Tailwind CSS
- Form Handling: React Hook Form + Zod
- Charts: Recharts
- Date Handling: date-fns
- Icons: Lucide React
Before you begin, ensure you have the following installed:
- Node.js 18.x or higher
- npm or yarn or pnpm
- PostgreSQL 14+ (or use cloud PostgreSQL like Supabase, Neon, Railway)
- Git
cd next.jsnpm install
# or
yarn install
# or
pnpm installCreate a .env file in the root directory:
cp .env.example .envThen update the .env file with your configuration:
# Database (PostgreSQL)
DATABASE_URL="postgresql://username:password@localhost:5432/dairy_farm"
# NextAuth
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="your-secret-key-here-change-in-production"
# Email (Optional)
EMAIL_SERVER_HOST="smtp.gmail.com"
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER="your-email@gmail.com"
EMAIL_SERVER_PASSWORD="your-app-password"
EMAIL_FROM="noreply@dairyfarm.com"
# App
NEXT_PUBLIC_APP_NAME="Dairy Farm Management System"Option 1: Using psql (Command Line)
psql -U postgresCREATE DATABASE dairy_farm;
\qOption 2: Using pgAdmin (GUI)
- Open pgAdmin
- Right-click on "Databases"
- Select "Create" โ "Database"
- Enter database name:
dairy_farm - Click "Save"
Option 3: Cloud Database (Recommended for Production)
- Supabase: Free PostgreSQL hosting with dashboard
- Neon: Serverless PostgreSQL
- Railway: One-click PostgreSQL deployment
- Render: Managed PostgreSQL
npx prisma generate
npx prisma db pushThis will create all tables in your PostgreSQL database.
You can create an initial admin user by signing up through the application, or use Prisma Studio:
npx prisma studionpm run dev
# or
yarn dev
# or
pnpm devOpen http://localhost:3000 in your browser.
- Navigate to
http://localhost:3000 - Click on "Sign Up" to create your account
- Fill in your details and select your role (Admin/Manager/User)
- Login with your credentials
- Start managing your dairy farm!
Once logged in, follow these steps to get started:
- Go to Animals page
- Click "Add New Animal"
- Fill in details (Tag Number, Breed, Gender, Date of Birth, etc.)
- Save the animal
- Go to Customers page
- Click "Add New Customer"
- Enter customer name, contact info
- Set default price per liter (optional)
- Save customer
- Go to Milk Production page
- Click "Add New Record"
- Select animal
- Enter production amounts (Morning, Afternoon, Evening)
- Total is calculated automatically
- Save record
- Go to Milk Sales page
- Click "Add New Sale"
- Select customer from dropdown (or enter new buyer name)
- Enter quantity and price
- Payment Features:
- System shows customer's available credit
- Credit is automatically applied to sale
- Enter additional cash payment (if any)
- Payment status auto-updates if fully paid
- Save sale
Result:
- Milk stock automatically updated โ
- Customer balance updated โ
- Finance income record created (if PAID) โ
- Go to Dashboard
- View:
- Total animals
- Today's milk production
- Current milk stock (with color alerts)
- Recent activities
- Use Quick Actions for fast data entry:
- Add Milk Production
- Add Milk Sale
- Add Health Record
- Add Stock Feed
- Go to Customers page
- Click on a customer to view details
- View:
- Current balance (Credit/Due)
- Complete purchase history
- Pending dues
- Balance Actions:
- Adjust Balance: Manually add/deduct amount
- Auto-Settle Dues: One-click to settle all pending dues from credit
- Go to Finance page
- View all income and expenses
- Automatic Records:
- Milk sales (when PAID)
- Stock feed purchases
- Customer balance adjustments
- Filter by date and type
- View total income vs. expenses
- Check Dashboard for current stock
- Go to Milk Stock page for detailed analysis:
- Current stock with alerts
- Weekly/Monthly production vs. sales
- Recent activities
- Quick action buttons
- Go to Stock Feed page
- Click "Add New Stock Feed"
- Enter feed details (Type, Quantity, Supplier, Cost)
- Save record
Result:
- Finance expense record automatically created โ
- Go to Health Management page
- Click "Add New Health Record"
- Select animal
- Enter disease, symptoms, treatment, medication
- Add veterinarian name and cost
- Set next checkup date
- Save record
- Always select an existing customer to automatically apply credit
- The system shows a real-time payment summary
- Green badge = Credit, Red badge = Due
- If customer has credit, it's automatically applied to new sales
- Set default price per customer to save time
- Use "Auto-Settle Dues" when customer pays advance
- Orange highlighted rows in purchase history = Has pending dues
- Customer balance: + (Credit) / - (Due)
- No need to manually add milk sale income (automatic)
- No need to manually add stock feed expense (automatic)
- Use pagination to view older records (5 per page)
- Check reference numbers to trace back to original transactions
- Red alert (<50L) = Low stock, need to reduce sales
- Orange alert (<100L) = Medium stock
- Cyan/Green (โฅ100L) = Good stock
- Stock calculation: Production - Sales (automatic)
- Use Quick Actions for fast data entry
- Recent Activity shows last 5 actions across all modules
- Color-coded icons help identify activity type
- Stock alert visible at a glance
next.js/
โโโ prisma/
โ โโโ schema.prisma # Database schema with 11 models
โ โโโ migrations/ # Database migration files
โโโ src/
โ โโโ app/
โ โ โโโ api/ # API routes (RESTful endpoints)
โ โ โ โโโ auth/
โ โ โ โ โโโ [...nextauth]/route.ts # NextAuth handler
โ โ โ โ โโโ signup/route.ts # User registration
โ โ โ โโโ animals/
โ โ โ โ โโโ route.ts # GET, POST /api/animals
โ โ โ โ โโโ [id]/route.ts # GET, PUT, DELETE /api/animals/:id
โ โ โ โโโ health/
โ โ โ โ โโโ route.ts # Health records listing/create
โ โ โ โ โโโ [id]/route.ts # Individual record operations
โ โ โ โโโ weight/
โ โ โ โ โโโ route.ts
โ โ โ โ โโโ [id]/route.ts
โ โ โ โโโ breeding/
โ โ โ โ โโโ route.ts
โ โ โ โ โโโ [id]/route.ts
โ โ โ โโโ milk/
โ โ โ โ โโโ route.ts
โ โ โ โ โโโ [id]/route.ts
โ โ โ โโโ milk-sales/
โ โ โ โ โโโ route.ts # + Auto-payment + Finance integration
โ โ โ โ โโโ [id]/route.ts # + Balance sync + Status updates
โ โ โ โโโ customers/
โ โ โ โ โโโ route.ts # Customer CRUD
โ โ โ โ โโโ [id]/
โ โ โ โ โโโ route.ts # Customer details
โ โ โ โ โโโ adjust-balance/route.ts # Manual balance adjustment
โ โ โ โ โโโ settle-dues/route.ts # Auto-settle pending dues
โ โ โ โโโ stockfeed/
โ โ โ โ โโโ route.ts # + Auto finance expense
โ โ โ โ โโโ [id]/route.ts # + Finance sync on edit/delete
โ โ โ โโโ employees/
โ โ โ โ โโโ route.ts
โ โ โ โ โโโ [id]/route.ts
โ โ โ โโโ finance/
โ โ โ โโโ route.ts # With pagination support
โ โ โ โโโ [id]/route.ts
โ โ โ
โ โ โโโ dashboard/ # Protected dashboard pages
โ โ โ โโโ page.tsx # Dashboard home (Stats + Quick Actions)
โ โ โ โโโ layout.tsx # Dashboard layout with Sidebar
โ โ โ โโโ animals/
โ โ โ โ โโโ page.tsx # Animals list
โ โ โ โ โโโ new/page.tsx # Add new animal
โ โ โ โ โโโ [id]/
โ โ โ โ โโโ page.tsx # View animal details
โ โ โ โ โโโ edit/page.tsx # Edit animal
โ โ โ โโโ health/
โ โ โ โ โโโ page.tsx # Health records list
โ โ โ โ โโโ new/page.tsx # Add health record
โ โ โ โ โโโ [id]/
โ โ โ โ โโโ page.tsx # View health record
โ โ โ โ โโโ edit/page.tsx # Edit health record
โ โ โ โโโ weight/
โ โ โ โ โโโ page.tsx
โ โ โ โ โโโ new/page.tsx
โ โ โ โ โโโ [id]/ (view + edit)
โ โ โ โโโ breeding/
โ โ โ โ โโโ page.tsx
โ โ โ โ โโโ new/page.tsx
โ โ โ โ โโโ [id]/ (view + edit)
โ โ โ โโโ milk/
โ โ โ โ โโโ page.tsx
โ โ โ โ โโโ new/page.tsx
โ โ โ โ โโโ [id]/ (view + edit)
โ โ โ โโโ milk-sales/
โ โ โ โ โโโ page.tsx # Sales list
โ โ โ โ โโโ new/page.tsx # + Payment summary + Auto-payment
โ โ โ โ โโโ [id]/
โ โ โ โ โโโ page.tsx # View with finance link
โ โ โ โ โโโ edit/page.tsx # Edit with payment tracking
โ โ โ โโโ customers/
โ โ โ โ โโโ page.tsx # Customers list with balance
โ โ โ โ โโโ new/page.tsx # Add new customer
โ โ โ โ โโโ [id]/
โ โ โ โ โโโ page.tsx # + Purchase history + Auto-settle
โ โ โ โ โโโ edit/page.tsx # Edit customer
โ โ โ โโโ milk-stock/
โ โ โ โ โโโ page.tsx # Stock analysis + Alerts
โ โ โ โโโ stockfeed/
โ โ โ โ โโโ page.tsx
โ โ โ โ โโโ new/page.tsx # + Finance integration info
โ โ โ โ โโโ [id]/ (view + edit)
โ โ โ โโโ employees/
โ โ โ โ โโโ page.tsx
โ โ โ โ โโโ new/page.tsx
โ โ โ โ โโโ [id]/ (view + edit)
โ โ โ โโโ finance/
โ โ โ โโโ page.tsx # With pagination (5 per page)
โ โ โ โโโ new/page.tsx
โ โ โ โโโ [id]/ (view + edit)
โ โ โ
โ โ โโโ login/
โ โ โ โโโ page.tsx # Login form
โ โ โโโ signup/
โ โ โ โโโ page.tsx # Registration form
โ โ โโโ page.tsx # Landing page
โ โ โโโ layout.tsx # Root layout
โ โ โโโ globals.css # Global styles
โ โ
โ โโโ components/
โ โ โโโ layout/
โ โ โ โโโ Sidebar.tsx # Navigation with all modules
โ โ โ โโโ Header.tsx # User menu + logout
โ โ โโโ ui/ # Shadcn/ui components
โ โ โโโ button.tsx
โ โ โโโ card.tsx
โ โ โโโ input.tsx
โ โ โโโ label.tsx
โ โ โโโ select.tsx
โ โ โโโ table.tsx
โ โ โโโ badge.tsx
โ โ โโโ tabs.tsx
โ โ โโโ dialog.tsx
โ โ โโโ toast.tsx
โ โ โโโ toaster.tsx
โ โ โโโ use-toast.ts
โ โ
โ โโโ lib/
โ โโโ prisma.ts # Prisma client singleton
โ โโโ auth.ts # NextAuth configuration
โ โโโ utils.ts # Utility functions
โ # (formatDate, formatCurrency, etc.)
โ
โโโ public/ # Static assets
โโโ .env # Environment variables
โโโ package.json # Dependencies
โโโ tsconfig.json # TypeScript config
โโโ tailwind.config.ts # Tailwind CSS config
โโโ next.config.js # Next.js config
โโโ README.md # This file
โโโ SETUP_GUIDE.md # Detailed setup instructions
Smart API Routes:
milk-sales/route.ts: Auto-payment logic, customer balance updates, finance integrationcustomers/[id]/settle-dues/route.ts: Automatic pending dues settlementstockfeed/route.ts: Auto finance expense creation
Interactive Pages:
milk-sales/new/page.tsx: Real-time payment summary with credit auto-applicationcustomers/[id]/page.tsx: Customer details with auto-settle carddashboard/page.tsx: Live stats with quick actions and recent activity
Utility Functions:
formatDate(): Consistent date formattingformatCurrency(): Taka (เงณ) formattingcalculateAge(): Animal age calculationgetAgeString(): Human-readable age
npm run dev- Start development servernpm run build- Build for productionnpm run start- Start production servernpm run lint- Run ESLintnpx prisma studio- Open Prisma Studio (database GUI)npx prisma generate- Generate Prisma Clientnpx prisma db push- Push schema changes to database
- Add, edit, and track animals with unique tag numbers
- Record breed, age, gender, and health status
- Track purchase information and current weight
- View complete animal history
- Record health examinations and treatments
- Track diseases, symptoms, and medications
- Schedule follow-up checkups
- Monitor health costs
- Log daily milk production (morning, afternoon, evening)
- Track milk quality and fat content
- Generate production reports
- Identify top-producing animals
- Track all farm income and expenses
- Categorize transactions
- View financial summaries
- Monitor profitability
- Secure password hashing with bcrypt
- JWT-based session management
- Protected API routes
- Role-based access control (RBAC) ready
- SQL injection prevention with Prisma
- Push your code to GitHub
- Import your repository to Vercel
- Add environment variables
- Deploy!
The application can be deployed to any platform that supports Next.js:
- Netlify
- Railway
- DigitalOcean App Platform
- AWS Amplify
- Google Cloud Run
POST /api/auth/signup - Register new user
POST /api/auth/signin - User login
POST /api/auth/signout - User logout
GET /api/auth/session - Get current session
GET /api/animals - Get all animals (with filters)
POST /api/animals - Create new animal
GET /api/animals/:id - Get animal details by ID
PUT /api/animals/:id - Update animal
DELETE /api/animals/:id - Delete animal
GET /api/health - Get all health records
POST /api/health - Create health record
GET /api/health/:id - Get health record by ID
PUT /api/health/:id - Update health record
DELETE /api/health/:id - Delete health record
GET /api/weight - Get all weight records
POST /api/weight - Create weight record
GET /api/weight/:id - Get weight record by ID
PUT /api/weight/:id - Update weight record
DELETE /api/weight/:id - Delete weight record
GET /api/breeding - Get all breeding records
POST /api/breeding - Create breeding record
GET /api/breeding/:id - Get breeding record by ID
PUT /api/breeding/:id - Update breeding record
DELETE /api/breeding/:id - Delete breeding record
GET /api/milk - Get all milk production records
POST /api/milk - Create milk record
GET /api/milk/:id - Get milk record by ID
PUT /api/milk/:id - Update milk record
DELETE /api/milk/:id - Delete milk record
GET /api/milk-sales - Get all milk sales
POST /api/milk-sales - Create milk sale
โข Auto-applies customer credit
โข Creates finance record (if PAID)
โข Updates customer balance
โข Auto-creates customer if new
GET /api/milk-sales/:id - Get milk sale by ID
PUT /api/milk-sales/:id - Update milk sale
โข Updates finance record
โข Updates customer balance
โข Handles status changes
DELETE /api/milk-sales/:id - Delete milk sale
โข Deletes finance record
โข Reverses customer balance
GET /api/customers - Get all customers
POST /api/customers - Create new customer
GET /api/customers/:id - Get customer details
โข Includes purchase history
โข Shows balance
โข Shows pending dues
PUT /api/customers/:id - Update customer
DELETE /api/customers/:id - Delete customer
POST /api/customers/:id/adjust-balance
- Manually adjust customer balance
โข Creates finance record
โข Updates balance
POST /api/customers/:id/settle-dues
- Auto-settle pending dues
โข Oldest dues first
โข Creates finance records
โข Updates payment status
GET /api/stockfeed - Get all stock feed records
POST /api/stockfeed - Create stock feed
โข Auto-creates finance expense
GET /api/stockfeed/:id - Get stock feed by ID
PUT /api/stockfeed/:id - Update stock feed
โข Updates finance record
DELETE /api/stockfeed/:id - Delete stock feed
โข Deletes finance record
GET /api/employees - Get all employees
POST /api/employees - Create employee
GET /api/employees/:id - Get employee by ID
PUT /api/employees/:id - Update employee
DELETE /api/employees/:id - Delete employee
GET /api/finance - Get all finance records
โข Supports pagination
โข Date filtering
POST /api/finance - Create finance record
GET /api/finance/:id - Get finance record by ID
PUT /api/finance/:id - Update finance record
DELETE /api/finance/:id - Delete finance record
model User {
id String @id @default(cuid())
name String
email String @unique
password String
role String @default("USER")
createdAt DateTime @default(now())
}
model Animal {
id String @id @default(cuid())
tagNumber String @unique
name String?
breed String
dateOfBirth DateTime
gender Gender
purchaseDate DateTime?
purchasePrice Float?
currentWeight Float?
status AnimalStatus @default(ACTIVE)
// Relations
healthRecords HealthRecord[]
weightRecords WeightRecord[]
milkRecords MilkRecord[]
breedingMale Breeding[] @relation("MaleAnimal")
breedingFemale Breeding[] @relation("FemaleAnimal")
}
model Customer {
id String @id @default(cuid())
name String
phone String?
email String?
address String?
defaultPricePerLiter Float?
balance Float @default(0) // + = Credit, - = Due
lastPurchaseDate DateTime?
totalPurchases Float @default(0)
notes String?
// Relations
milkSales MilkSale[]
}
model MilkSale {
id String @id @default(cuid())
customerId String?
customer Customer? @relation(fields: [customerId])
saleDate DateTime
quantity Float
pricePerLiter Float
totalAmount Float
amountPaid Float @default(0)
buyer String?
paymentStatus PaymentStatus @default(PENDING)
paymentMethod String?
notes String?
}
model Finance {
id String @id @default(cuid())
date DateTime
type FinanceType // INCOME or EXPENSE
category String
description String
amount Float
paymentMethod String?
referenceNumber String? @unique
notes String?
}
model MilkRecord {
id String @id @default(cuid())
animalId String
animal Animal @relation(fields: [animalId])
date DateTime
morningAmount Float @default(0)
afternoonAmount Float @default(0)
eveningAmount Float @default(0)
totalAmount Float
quality MilkQuality?
fatContent Float?
}
model HealthRecord {
id String @id @default(cuid())
animalId String
animal Animal @relation(fields: [animalId])
checkupDate DateTime
disease String?
symptoms String?
treatment String?
medication String?
veterinarian String?
cost Float?
nextCheckupDate DateTime?
status HealthStatus
notes String?
}
model WeightRecord {
id String @id @default(cuid())
animalId String
animal Animal @relation(fields: [animalId])
recordDate DateTime
weight Float
height Float?
bodyCondition Float?
notes String?
}
model Breeding {
id String @id @default(cuid())
maleAnimalId String
femaleAnimalId String
maleAnimal Animal @relation("MaleAnimal", fields: [maleAnimalId])
femaleAnimal Animal @relation("FemaleAnimal", fields: [femaleAnimalId])
breedingDate DateTime
breedingType BreedingType
expectedDelivery DateTime?
actualDelivery DateTime?
outcome BreedingOutcome?
notes String?
}
model StockFeed {
id String @id @default(cuid())
feedType String
quantity Float
unit String
supplier String?
purchaseDate DateTime
expiryDate DateTime?
costPerUnit Float
totalCost Float
currentStock Float
minimumStock Float?
notes String?
}
model Employee {
id String @id @default(cuid())
employeeId String @unique
name String
position String
department String?
phone String?
email String?
address String?
salary Float?
joinDate DateTime
leaveDate DateTime?
status EmployeeStatus @default(ACTIVE)
notes String?
}
// Enums
enum Gender { MALE FEMALE }
enum AnimalStatus { ACTIVE SOLD DECEASED TRANSFERRED }
enum HealthStatus { HEALTHY UNDER_TREATMENT CRITICAL RECOVERED }
enum MilkQuality { EXCELLENT GOOD AVERAGE POOR }
enum PaymentStatus { PAID PENDING OVERDUE }
enum BreedingType { NATURAL ARTIFICIAL_INSEMINATION }
enum BreedingOutcome { SUCCESSFUL FAILED ABORTED PENDING }
enum FinanceType { INCOME EXPENSE }
enum EmployeeStatus { ACTIVE INACTIVE TERMINATED RESIGNED }Contributions are welcome! Please feel free to submit a Pull Request. Whether it's bug fixes, new features, or documentation improvements, your contribution is valued.
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This system includes several smart automation features that save time and reduce errors:
- Milk Sales (PAID) โ Auto-creates income record
- Stock Feed Purchases โ Auto-creates expense record
- Customer Balance Adjustments โ Auto-creates finance record
- Edit/Delete โ Finance records automatically sync
- Auto-payment: Credit balance automatically applied to new sales
- Real-time calculation: Shows exactly how much is covered by credit
- Status auto-update: Payment status automatically set to PAID when fully covered
- Balance tracking: Positive (Credit) / Negative (Due) tracking
- One-click settlement: Settle all pending dues at once
- Intelligent payment: Oldest dues paid first
- Partial settlement: Works even if credit doesn't cover all dues
- Auto-status update: Sales marked as PAID automatically
- Live calculation: Stock = Production - Sales
- Color alerts: Low (Red), Medium (Orange), Good (Cyan)
- Dashboard display: Always see current stock at a glance
- Auto-registration: New buyers automatically added as customers
- Price memory: Default price auto-filled for existing customers
- Balance display: Shows available credit or pending dues
- Purchase history: Complete transaction history with each customer
| Module | Create | Read | Update | Delete | Auto-Integration | Special Features |
|---|---|---|---|---|---|---|
| ๐ฎ Animals | โ | โ | โ | โ | - | View page, Status tracking |
| โค๏ธ Health | โ | โ | โ | โ | - | Per-animal history |
| โ๏ธ Weight | โ | โ | โ | โ | - | Growth tracking |
| ๐ถ Breeding | โ | โ | โ | โ | - | Outcome tracking |
| ๐ฅ Milk Production | โ | โ | โ | โ | Stock Calculation | 3-session tracking |
| ๐ฐ Milk Sales | โ | โ | โ | โ | Finance + Balance | Auto-payment, Auto-customer |
| ๐ฅ Customers | โ | โ | โ | โ | Finance (Adjust) | Balance tracking, Settle dues |
| ๐ฆ Milk Stock | - | โ | - | - | Production/Sales | Real-time calculation |
| ๐พ Stock Feed | โ | โ | โ | โ | Finance (Expense) | Expiry tracking |
| ๐ฅ Employees | โ | โ | โ | โ | - | Status tracking |
| ๐ฆ Finance | โ | โ | โ | โ | - | Pagination, Categories |
This Dairy Farm Management System is perfect for:
- Small to Medium Dairy Farms (10-200 animals)
- Farm Managers who want to digitize operations
- Farm Owners who need real-time insights
- Dairy Cooperatives managing multiple farmers
- Agricultural Students learning farm management
- Veterinarians tracking animal health
- Covers ALL aspects of dairy farm management
- From animal health to financial tracking
- Auto-payment from customer credit
- Auto-finance integration
- Auto-settle pending dues
- Real-time stock tracking
- Clean, modern interface
- Intuitive navigation
- Color-coded alerts
- Quick action shortcuts
- Built with enterprise-grade tech stack
- Secure authentication
- Data validation
- Error handling
- Handles growing farm operations
- Pagination for large datasets
- Optimized database queries
- Fast performance
- Mobile app (React Native)
- Real-time notifications
- Advanced analytics with charts
- Export to PDF/Excel
- Multi-language support (Bengali, English)
- Barcode/QR code scanning for animals
- Weather integration for milk production correlation
- Automated backup system
- SMS notifications for payment reminders
- Integration with IoT devices (milk meters)
- Offline mode support
- Multi-farm support
- WhatsApp integration for customer notifications
- Inventory forecasting
- Feed efficiency calculator
This project is licensed under the MIT License - see the LICENSE file for details.
Built with modern web technologies to help dairy farmers manage their operations more efficiently. Special thanks to:
- Next.js team for the amazing framework
- Prisma for the excellent ORM
- Shadcn/ui for beautiful components
- The open-source community
For questions, issues, or feature requests:
- ๐ง Email: support@dairyfarm.com
- ๐ Issues: Open an issue on GitHub
- ๐ฌ Discussions: Join our community discussions
Dairy Farm Management System - Modernizing Traditional Farming