# Contract Farming System Breakdown

## Overview
The contract farming system is designed to facilitate agricultural operations where a company provides farmers with inputs (e.g., seeds, fertilizers) on a cash or loan basis, engages in contract farming with farmer or admin-initiated contracts, and manages the entire lifecycle from input provision to product sales. The system supports multiple user roles (farmers, buyers, business persons, field officers, admins) and includes features for authentication, contract management, farm event tracking, marketplace sales, and reporting. The technology stack is limited to Django, HTML, and Tailwind CSS.

### Key Requirements
1. **Inputs**: Provided on cash or loan basis, with repayment options:
   - Cash (immediate payment with possible discounts).
   - Loan, repayable at harvest or in installments.
2. **Contract Farming**:
   - Admin-initiated contracts with farmer signing for acceptance.
   - Farmer-initiated contract requests for admin approval.
   - Contracts include product details, payment terms, and interest calculations.
3. **Farm Events**: Field officers record events (e.g., planting, weeding) with costs, requiring farmer approval, then admin approval, updating the contract’s total cost.
4. **Contract Completion**: When products are ready, admins mark contracts as inactive (no further costs added). A report is generated with production details, cost breakdown, and interest applied to the subtotal for the final payable amount.
5. **Interest Rates**: Three types (harvest, installments, contract farming), defined annually, prorated based on user-selected months, with snapshots to protect past records.
6. **Marketplace**: Products (produce, inputs, equipment) are listed for sale, with fees, commissions, and taxes.
7. **Additional Features**: Aggregation centres for product collection and field officer assignments for farmer support.

## System Components

### 1. User Management and Authentication
- **Purpose**: Manage users with different roles and authentication workflows.
- **Model**: `User` (inherits `AbstractBaseUser`, `PermissionsMixin`)
  - **Fields**:
    - `type`: Choices (`FARMER`, `BUYER`, `BUSINESS_PERSON`, `FIELD_OFFICER`, `ADMIN`).
    - `email`, `phone_number`: Unique identifiers (at least one required).
    - `first_name`, `last_name`, `is_active`, `is_staff`, `date_joined`, `is_temporary_password`, `last_login`.
    - `groups`, `user_permissions`: For role-based access control.
  - **Manager**: `UserManager` for creating users and superusers.
  - **Key Methods**:
    - `get_full_name`: Returns full name or identifier.
    - `get_identifier`: Returns email or phone number.
  - **Related Model**: `Farmer` (one-to-one with `User`, adds `farmer_id`).
  - **Workflows**:
    - Registration (`signup`, `user_create`).
    - Login (`contract_login`, `marketplace_login`).
    - Password management (`forgot_password`, `change_password`).
    - Profile updates (`profile_update`).
    - Admin actions: Approve (`user_approve`), edit (`user_update`), delete (`user_delete`).
    - Dashboards: General (`dashboard`), shared (`shared_dashboard`), buyer-specific (`buyer_dashboard`), business person-specific (`business_person_dashboard`).

### 2. Inputs Management
- **Purpose**: Manage agricultural inputs provided to farmers on cash or loan basis.
- **Model**: `Input`
  - **Fields**:
    - `name`, `input_type` (`SEED`, `FERTILIZER`, `PESTICIDE`, `EQUIPMENT`).
    - `price`, `stock`, `cash_discount`, `interest_rate_snapshot`, `repayment_type` (`CASH`, `PROFIT_SHARE`, `INSTALLMENTS`).
    - `service_included`, `created_at`, `updated_at`.
  - **Related Model**: `ContractInput`
    - Links inputs to contracts with `quantity`, `payment_term` (`CASH`, `MONTHLY`, `HARVEST`), `deposit_amount`.
  - **Workflows**:
    - Admins create/edit/delete inputs (`input_create`, `input_update`, `input_delete`).
    - Farmers receive inputs via contracts, with repayment terms applied.
    - Cash payments may include discounts; loans apply interest based on repayment type.

### 3. Loan Management
- **Purpose**: Provide loans to farmers, repayable via cash, harvest, or installments.
- **Model**: `Loan`
  - **Fields**:
    - `farmer`, `amount`, `balance`, `payment_term` (`CASH`, `MONTHLY`, `HARVEST`), `deposit_amount`, `total_amount`, `interest_rate_snapshot`, `months_for_payment`.
    - `created_at`, `updated_at`.
  - **Key Methods**:
    - `save`: Calculates `total_amount` and `balance` with interest for non-cash terms.
  - **Workflows**:
    - Admins create/edit/delete loans (`loan_create`, `loan_update`, `loan_delete`).
    - Interest is applied based on payment term and months, using `InterestRate`.

### 4. Contract Farming
- **Purpose**: Manage contracts initiated by admins or farmers, with farmer signing and admin approval.
- **Model**: `Contract`
  - **Fields**:
    - `farmer`, `product`, `quantity`, `price_per_unit`, `status` (`DRAFT`, `PENDING_SIGN`, `SIGNED`, `ACTIVE`, `COMPLETED`).
    - `payment_term` (`CASH`, `MONTHLY`, `HARVEST`), `deposit_amount`, `total_amount`, `additional_costs`, `interest_rate_snapshot`, `months_for_payment`, `signed_at`, `digital_signature`.
    - `created_at`, `updated_at`.
  - **Key Methods**:
    - `save`: Calculates `total_amount` with interest for non-cash terms.
  - **Proposed Model**: `ContractRequest` (for farmer-initiated requests)
    - Fields: `farmer`, `product`, `quantity`, `price_per_unit` (optional), `proposed_payment_term`, `notes`, `status` (`PENDING`, `APPROVED`, `REJECTED`), `rejection_reason`.
    - Method: `approve` creates a `Contract` upon admin approval.
  - **Workflows**:
    - **Admin-Initiated**:
      - Admin creates contract (`contract_create`, status=`DRAFT`).
      - Farmer signs (`digital_signature`, status=`PENDING_SIGN` to `SIGNED`).
      - Contract becomes `ACTIVE` and progresses to `COMPLETED`.
    - **Farmer-Initiated**:
      - Farmer submits `ContractRequest` (`contract_request_create`, status=`PENDING`).
      - Admin reviews (`contract_request_list`), approves (`approve` creates `Contract`) or rejects (sets `rejection_reason`).
      - Notifications sent to admins on request creation (via signals or messages).
    - Admins manage contracts (`contract_list`, `contract_update`, `contract_delete`).

### 5. Farm Event Tracking
- **Purpose**: Track farm activities with costs, requiring farmer and admin approvals.
- **Model**: `FarmEvent`
  - **Fields**:
    - `contract`, `field_officer`, `event_type` (`WEEDING`, `SPRAYING`, `VISIT`, `HARVESTING`, `OTHER`), `description`, `amount`, `date`.
    - `status` (`DRAFT`, `FARMER_APPROVED`, `FULLY_APPROVED`), `farmer_approval_signature`, `admin_approved_at`.
    - `created_at`, `updated_at`.
  - **Key Methods**:
    - `save`: Updates `Contract.additional_costs` and `total_amount` on `FULLY_APPROVED`.
  - **Related Model**: `FieldOfficerAssignment`
    - Links field officers to farmers for event recording.
  - **Workflows**:
    - Field officer records event (`farm_event_create`, status=`DRAFT`).
    - Farmer approves (`farmer_approval_signature`, status=`FARMER_APPROVED`).
    - Admin approves (`admin_approved_at`, status=`FULLY_APPROVED`), updating contract costs.
    - Events viewable via contract details (`contract_detail`).

### 6. Interest Rates
- **Purpose**: Manage three interest rate types (harvest, installments, contract farming) with annual rates, prorated by months, and snapshots for historical integrity.
- **Model**: `InterestRate`
  - **Proposed Fields** (to be updated):
    - `rate_type` (`HARVEST`, `INSTALLMENTS`, `CONTRACT`).
    - `annual_rate`, `effective_from`, `created_at`.
  - **Key Methods**:
    - `get_prorated_rate`: Returns rate * (months / 12), capped at 12 months.
  - **Behavior**:
    - Admins create/update rates (`interest_rate_create`, `interest_rate_update`).
    - Rates are applied to `Contract`, `Loan`, and `Input` via `interest_rate_snapshot` at creation, ensuring past records are unaffected.
    - Proration applies to all types based on user-selected `months_for_payment`.

### 7. Contract Completion and Reporting
- **Purpose**: Mark contracts as inactive (`COMPLETED`) to stop cost additions, generate reports with production and cost breakdowns, and apply interest.
- **Model**: `Contract`
  - **Behavior**:
    - When status=`COMPLETED`, no further `FarmEvent` or `ContractInput` additions allowed (enforced in views).
    - `total_amount` includes `quantity * price_per_unit + additional_costs + interest - deposit_amount`.
  - **Reporting**:
    - Handled via views/templates (recommended).
    - View (`contract_report`) aggregates:
      - Contract details (product, quantity, price).
      - Farm events (costs from `FarmEvent`).
      - Inputs (costs from `ContractInput`).
      - Sales (from `Sale`).
      - Subtotal, interest (via `interest_rate_snapshot`), and total payable.
    - Rendered in HTML with Tailwind styling (`contract_report.html`).
  - **Workflows**:
    - Admin sets contract to `COMPLETED` (`contract_update`).
    - Generate report (`contract_report`) for farmer review.

### 8. Marketplace and Sales
- **Purpose**: List and sell products (produce, inputs, equipment) with fees and commissions.
- **Models**:
  - **MarketplaceProduct**:
    - Fields: `seller` (business person/admin), `contract` (optional), `name`, `product_type` (`PRODUCE`, `INPUT`, `EQUIPMENT`), `description`, `quantity`, `price_per_unit`, `category`, `visibility_days`, `end_date`, `tax_amount`.
    - Method: `save` sets `end_date` based on `visibility_days`.
  - **Sale**:
    - Fields: `contract` (optional), `buyer`, `product`, `quantity`, `price_per_unit`, `commission_rate`, `profit`, `tax_amount`.
    - Method: `save` calculates `profit` (total sale - commission - tax).
  - **PostingFee**:
    - Fields: `product`, `seller`, `amount`, `visibility_days`, `payment_method` (`CASH`, `MOBILE`, `BANK`), `transaction_id`, `status`, `tax_amount`.
  - **Workflows**:
    - Sellers list products (`marketplace_product_create`).
    - Pay fees (`posting_fee_create`).
    - Buyers purchase (`sale_create`), triggering commission and profit calculations.
    - Admins manage listings (`marketplace_product_update`, `marketplace_product_delete`).

### 9. Aggregation Centres and Field Officer Assignments
- **Purpose**: Manage product collection points and assign field officers to farmers.
- **Models**:
  - **AggregationCentre**:
    - Fields: `name`, `location`, `map_coordinates`, `capacity`.
    - Unique constraint on `name` and `location`.
  - **FieldOfficerAssignment**:
    - Fields: `field_officer`, `farmer`.
    - Unique constraint on officer-farmer pair.
  - **Workflows**:
    - Admins manage centres (`aggregation_centre_create`, `aggregation_centre_update`).
    - Assign officers to farmers (`field_officer_assignment_create`).

### 10. Technology Stack
- **Stack**: Django (backend, ORM), HTML (templates), Tailwind CSS (styling).
- **Constraints**: No additional frameworks or libraries (e.g., no JavaScript frameworks, external APIs unless specified).

## Key Workflows

### Input Provision
1. Admin creates `Input` with type, price, and repayment options.
2. Farmer receives inputs via `ContractInput` linked to a `Contract` or `Loan`.
3. Cash payments apply discounts; loans apply interest (`interest_rate_snapshot`) based on `repayment_type` and `months_for_payment`.

### Contract Lifecycle
1. **Admin-Initiated**:
   - Create `Contract` (`DRAFT`).
   - Farmer signs (`digital_signature`, `PENDING_SIGN` to `SIGNED`).
   - Contract becomes `ACTIVE`, accrues costs via `FarmEvent` and `ContractInput`.
2. **Farmer-Initiated**:
   - Farmer submits `ContractRequest` (`PENDING`).
   - Admin approves (creates `Contract`) or rejects.
3. Field officer records `FarmEvent` (`DRAFT`).
4. Farmer approves (`FARMER_APPROVED`), admin approves (`FULLY_APPROVED`), updating contract costs.
5. Contract marked `COMPLETED`, report generated.

### Marketplace
1. Seller lists `MarketplaceProduct`, pays `PostingFee`.
2. Buyer purchases, creating `Sale` with commission and profit.
3. Admins monitor listings and fees.

## Gaps and Proposed Enhancements
1. **Interest Rates**:
   - **Gap**: Current `InterestRate` model has only `MONTHLY` and `PROFIT_SHARE`; missing `CONTRACT` type.
   - **Proposed**: Update `RATE_TYPES` to include `HARVEST`, `INSTALLMENTS`, `CONTRACT`, with uniform proration behavior.
2. **Farmer-Initiated Contracts**:
   - **Gap**: No explicit model for farmer requests.
   - **Proposed**: Add `ContractRequest` model with `approve` method to create `Contract`.
3. **Reporting**:
   - **Gap**: No dedicated reporting model or view.
   - **Proposed**: Use views/templates for dynamic reports, aggregating contract data in `contract_report`.

## Next Steps
- Update `models.py` to incorporate `InterestRate` changes and add `ContractRequest`.
- Implement reporting view and template (`contract_report`).
- Add URLs and views for `ContractRequest` management.
- Ensure notifications for admin approvals (signals or Django messages).