# Bomabest Agriservices Contract Management System Documentation

## Overview
The Bomabest Agriservices platform manages contracts for farmers to access inputs (e.g., seeds, fertilizer) or produce crops under two contract types: `LOAN_PURCHASE` (for inputs on loan) and `CONTRACT_FARMING` (for crop production). Farmers can choose payment terms (`MONTHLY` installments or `HARVEST`) and sign contracts digitally. The system tracks signed inputs/products and payment information, ensuring traceability for both administrators and farmers.

This documentation summarizes the system's current state, what has been achieved, and the ongoing fixes to support a farmer selecting one input/product under either contract type with any payment term, using `ContractInput` for consistent tracking.

## Achieved Functionality
The system includes models, views, templates, and URLs to manage contracts, inputs, and payments, with a focus on creating, signing, and tracking contracts. Below is a summary of the implemented components.

### Models
1. **Contract**
   - **Purpose**: Represents a contract between a farmer and the platform.
   - **Fields**:
     - `type`: `LOAN_PURCHASE` or `CONTRACT_FARMING`.
     - `farmer`: Links to a `User` (type `FARMER`).
     - `product`, `quantity`, `price_per_unit`: Optional fields, previously required for `CONTRACT_FARMING`.
     - `status`: `DRAFT`, `PENDING_SIGN`, `SIGNED`, `ACTIVE`, `COMPLETED`.
     - `payment_term`: `MONTHLY` or `HARVEST`.
     - `deposit_amount`, `total_amount`, `additional_costs`, `interest_rate_snapshot`, `months_for_payment`: Financial details.
     - `signed_at`, `digital_signature`: Tracks signing.
     - `created_at`, `updated_at`: Timestamps.
   - **Behavior**:
     - Calculates `total_amount` based on `ContractInput` records (sum of `quantity * input.price + interest + additional_costs - deposit_amount`).
     - Validates digital signature for `SIGNED` status.
     - Supports multiple inputs via `contract_inputs` relationship.

2. **ContractInput**
   - **Purpose**: Links a contract to an input or product with quantity and payment terms.
   - **Fields**:
     - `contract`: ForeignKey to `Contract`.
     - `input`: ForeignKey to `Input`.
     - `quantity`, `payment_term`, `deposit_amount`, `interest_rate_snapshot`, `months_for_payment`.
     - `created_at`, `updated_at`.
   - **Behavior**:
     - Checks input stock availability and deducts `quantity` from `input.stock`.
     - Updates `contract.total_amount` on save.
     - Supports both contract types by linking inputs (e.g., "Maize Seeds") or products (e.g., "Maize").

3. **Input (Assumed)**
   - **Purpose**: Represents inputs (e.g., seeds, fertilizer) or products (e.g., crops).
   - **Fields**:
     - `name`: Name of the input/product.
     - `price`: Cost per unit.
     - `stock`: Available quantity.
     - `is_product`: Boolean to distinguish crops (`True`) from inputs (`False`).
     - `created_at`, `updated_at`.
   - **Behavior**: Tracks stock and price for inputs/products.

4. **Payment**
   - **Purpose**: Tracks payments for signed contracts.
   - **Fields**:
     - `contract`: ForeignKey to `Contract`.
     - `amount`: Payment amount.
     - `status`: `PENDING`, `COMPLETED`, `FAILED`.
     - `payment_date`: Date of payment completion.
     - `created_at`, `updated_at`.
   - **Behavior**: Sets `payment_date` for `COMPLETED` payments.

5. **ContractRequest**
   - **Purpose**: Allows farmers to request contracts, which admins can approve to create a `Contract`.
   - **Fields**:
     - Similar to `Contract` but with `status` (`PENDING`, `APPROVED`, `REJECTED`) and `rejection_reason`.
   - **Behavior**: Creates a `Contract` with `status='PENDING_SIGN'` on approval.

### Views
1. **contract_create**: Creates a `DRAFT` contract with type, farmer, payment term, and financial details, redirecting to add an input/product.
2. **contract_input_create**: Adds a single `ContractInput` for the chosen input (for `LOAN_PURCHASE`) or product (for `CONTRACT_FARMING`), updating `total_amount` and setting `status='PENDING_SIGN'`.
3. **contract_sign**: Allows farmers to review and sign a contract, setting `status='SIGNED'`.
4. **contract_detail**, **contract_list**, **contract_update**, **contract_delete**: Manage contract details, listing, editing, and deletion.
5. **contract_input_detail**, **contract_input_list**, **contract_input_update**, **contract_input_delete**: Manage input/product details for contracts.
6. **contract_payment_list**: Displays signed contracts with their inputs/products and payments.

### Templates
1. **contract_form.html**: Form for creating/editing contracts (type, farmer, payment term, deposit, months).
2. **contract_input_form.html**: Form for adding/editing a single input/product, filtering inputs by contract type (`is_product` for `CONTRACT_FARMING`).
3. **contract_sign.html**: Displays contract details (ID, type, input/product, financials) for farmer signing.
4. **contract_payment_list.html**: Lists signed contracts, their inputs/products, and payment history.
5. Others: `contract_detail.html`, `contract_list.html`, `contract_confirm_delete.html`, etc., for managing contracts.

### URLs
- Defined in `urls.py` with `app_name='contract_market_place'`.
- Key routes:
  - `/contracts/create/` → `contract_create`
  - `/contracts/<contract_pk>/inputs/create/` → `contract_input_create`
  - `/contracts/<pk>/sign/` → `contract_sign`
  - `/contracts/payments/` → `contract_payment_list`
  - Other routes for listing, details, updates, and deletions.

### Achievements
- **Contract Creation**: Admins can create contracts (`LOAN_PURCHASE` or `CONTRACT_FARMING`) with flexible payment terms (`MONTHLY` or `HARVEST`).
- **Input/Product Linking**: `ContractInput` links inputs (e.g., "Maize Seeds") for `LOAN_PURCHASE` and can link products (e.g., "Maize") for `CONTRACT_FARMING` using the `is_product` flag.
- **Farmer Signing**: Farmers review contract details (ID, type, input/product, financials) and sign digitally, updating `status='SIGNED'`.
- **Tracking**:
  - Signed inputs: Query `contract.contract_inputs.all()` for `status='SIGNED'` contracts.
  - Payments: `Payment` model links to `Contract`, tracked via `contract.payment_set.all()`.
- **Traceability**: The `contract_payment_list` view/template shows signed contracts, their inputs/products, and payment history for admins and farmers.
- **Validation**: Ensures stock availability, valid payment terms, and digital signatures.

## Current Fixes
The system is being updated to address the following requirements:
1. **Support One Input/Product with Farmer’s Choice**:
   - Allow a farmer to select one input (e.g., "Maize Seeds") or product (e.g., "Maize") under:
     - `LOAN_PURCHASE` with `MONTHLY` installments.
     - `LOAN_PURCHASE` with `HARVEST` payment.
     - `CONTRACT_FARMING` with `HARVEST` or `MONTHLY` payment.
   - **Fix**: Use `ContractInput` for both contract types, with `Input.is_product` to distinguish products (for `CONTRACT_FARMING`) from inputs (for `LOAN_PURCHASE`).

2. **Unify Input/Product Tracking**:
   - **Issue**: The original `Contract` model required `product`, `quantity`, and `price_per_unit` for `CONTRACT_FARMING`, limiting it to one product and not linking to `Input`.
   - **Fix**: 
     - Make `product`, `quantity`, `price_per_unit` optional in `Contract`.
     - Calculate `total_amount` from `ContractInput` for both types.
     - Use `Input` model with `is_product` flag to represent both inputs and products.
     - Update `contract_input_create` to filter inputs by contract type (`is_product=True` for `CONTRACT_FARMING`).

3. **Traceability of Signed Inputs and Payments**:
   - **Issue**: Need a clear way to track the single input/product and payment status for signed contracts.
   - **Fix**:
     - Added `Payment` model to track payments (`PENDING`, `COMPLETED`, `FAILED`).
     - Created `contract_payment_list` view and `contract_payment_list.html` to display signed contracts, their inputs/products, and payments.
     - Ensured `contract_sign.html` shows the single input/product clearly.

4. **Streamlined Contract Creation**:
   - **Issue**: Original flow required `product` fields for `CONTRACT_FARMING`, complicating multi-product support.
   - **Fix**:
     - Updated `contract_form.html` to exclude `product`, `quantity`, `price_per_unit`.
     - Redirect from `contract_create` to `contract_input_create` to add one input/product.
     - Set contract to `PENDING_SIGN` after adding input/product.

### Updated Models
- **Contract**: Removed `CONTRACT_FARMING` validation for `product`, `quantity`, `price_per_unit`. Calculates `total_amount` from `ContractInput`.
- **ContractInput**: Supports both contract types, validates stock, and updates `contract.total_amount`.
- **Input**: Added `is_product` to distinguish crops (e.g., "Maize") from inputs (e.g., "Maize Seeds").
- **Payment**: Tracks payment history for signed contracts.

### Updated Views
- **contract_create**: Creates `DRAFT` contract, redirects to add input/product.
- **contract_input_create**: Adds one input/product, filters by `is_product`, sets `PENDING_SIGN`.
- **contract_sign**: Shows contract details with one input/product for signing.
- **contract_payment_list**: Lists signed contracts, inputs/products, and payments.

### Updated Templates
- **contract_form.html**: Simplified to exclude `product` fields.
- **contract_input_form.html**: Filters inputs by contract type, supports one input/product.
- **contract_sign.html**: Displays single input/product and financial details.
- **contract_payment_list.html**: Shows signed contracts, inputs/products, and payments.

### Updated URLs
- Added `/contracts/payments/` for `contract_payment_list`.

## Example Flow
1. **Create Contract**:
   - Admin visits `/contracts/create/`, selects:
     - Type: `LOAN_PURCHASE` or `CONTRACT_FARMING`.
     - Farmer: John Doe.
     - Payment Term: `MONTHLY` or `HARVEST`.
     - Deposit, Months.
   - Creates `DRAFT` contract, redirects to `/contracts/<pk>/inputs/create/`.

2. **Add Input/Product**:
   - Admin selects:
     - Input: "Maize Seeds" (`LOAN_PURCHASE`, `is_product=False`) or "Maize" (`CONTRACT_FARMING`, `is_product=True`).
     - Quantity, Payment Term, etc.
   - Creates `ContractInput`, updates `total_amount`, sets `status='PENDING_SIGN'`.

3. **Farmer Signs**:
   - Farmer visits `/contracts/<pk>/sign/`, sees:
     - Contract ID, type, farmer, payment term, total amount.
     - Input/Product: e.g., "Maize Seeds, 50 units" or "Maize, 100 units".
   - Submits `digital_signature`, sets `status='SIGNED'`.

4. **Track Inputs/Payments**:
   - Admin/farmer visits `/contracts/payments/`, sees:
     - Contract 123: `LOAN_PURCHASE`, Input: Maize Seeds (50 units, $20/unit), Total: $1000, Payments: $500 (COMPLETED).
     - Contract 124: `CONTRACT_FARMING`, Product: Maize (100 units, $10/unit), Total: $1000, Payments: None.

## Current Limitations and Fixes in Progress
1. **Single Input/Product**:
   - **Limitation**: Currently assumes one input/product per contract for simplicity.
   - **Fix**: Can extend `contract_input_create` to allow adding multiple inputs by removing the redirect and adding a "Add Another Input" button (pending confirmation).

2. **Payment Creation**:
   - **Limitation**: Payments are manual; no automatic creation on signing.
   - **Fix**: Can add logic in `contract_sign` to create a `PENDING` payment for `total_amount` (pending confirmation).

3. **Input vs. Product**:
   - **Limitation**: Using `Input` with `is_product` to handle both inputs and products. A separate `Product` model might be cleaner.
   - **Fix**: Can introduce a `Product` model and link it to `ContractInput` if preferred (pending confirmation).

4. **ContractRequest Integration**:
   - **Limitation**: `ContractRequest` still uses `product`, `quantity`, `price_per_unit`, not aligned with `ContractInput`.
   - **Fix**: Update `ContractRequest` to use a similar `ContractRequestInput` model or rely on `ContractInput` post-approval (pending confirmation).

## Next Steps
- **Confirm Requirements**:
  - Allow multiple inputs/products per contract?
  - Automatic payment creation on signing?
  - Separate `Product` model or continue with `Input.is_product`?
  - Update `ContractRequest` to support input/product selection?
- **Additional Features**:
  - View for creating/editing payments.
  - Reports for payment status (e.g., overdue payments).
  - Farmer-facing contract request form.
- **Code Refinements**:
  - Update `ContractRequest` model and views.
  - Add form validation for matching payment terms.
  - Enhance templates with more financial details (e.g., interest breakdown).

## Conclusion
The system supports creating, signing, and tracking contracts with one input/product under `LOAN_PURCHASE` (`MONTHLY` or `HARVEST`) or `CONTRACT_FARMING`, using `ContractInput` for unified tracking. The `contract_payment_list` view ensures traceability of signed inputs and payments. Ongoing fixes address single input/product support, payment tracking, and model unification. Further refinements depend on confirming multi-input support, payment automation, and model structure preferences.