# Product Requirements Document: Hybrowlabs Engagement Management and Automated Billing System

## 1. Executive Summary

### 1.1 Business Objectives
The Hybrowlabs Engagement Management and Automated Billing System is a comprehensive Frappe/ERPNext custom module designed to revolutionize retainer-based client engagement management and eliminate manual billing processes. The system addresses critical business challenges in professional services organizations by providing:

- **99.5% Billing Accuracy**: Automated Sales Order creation for retainer billing with minimal manual intervention
- **Engagement Lifecycle Management**: Complete visibility and control over client engagement processes
- **Operational Efficiency**: Elimination of manual Sales Order creation and billing errors
- **Streamlined Administration**: Centralized system administration with simplified role management

### 1.2 Key Stakeholders and Roles
- **System Administrators**: Primary role for all engagement record creation, management, billing operations, and system maintenance
- **Other ERPNext Users**: Read-only access to engagement data as needed for their specific roles
- **Clients**: Engagement portal users and billing transparency recipients (when portal access is enabled)

### 1.3 Integration with Existing ERPNext Modules
The system seamlessly integrates with core ERPNext functionality:
- **Sales Module**: Automated Sales Order generation and management
- **Projects Module**: Project-based engagement tracking
- **CRM Module**: Customer relationship management and communication
- **Items Module**: Service catalog and pricing management
- **HR Module**: Resource allocation and time tracking integration

## 2. Module Architecture

### 2.1 DocType Specifications

#### 2.1.1 Engagement Record (Master DocType)
**Primary Purpose**: Central hub for managing client engagement lifecycle, billing parameters, and automation controls.

**Key Business Fields and Logic**:

**Core Engagement Fields**:
- **customer**: Link to Customer master - establishes billing relationship and customer data inheritance
- **engagement_title**: Human-readable identifier for easy recognition across teams and reports
- **status**: Workflow controller determining billing eligibility and engagement state
- **retainer_amount**: Core billing amount (monthly/periodic fee) used in automated calculations
- **billing_day_of_month**: Specific calendar day triggering Sales Order creation (1-31)
- **start_date/end_date**: Engagement lifecycle boundaries controlling billing period validation
- **total_contract_value**: Auto-calculated field (retainer_amount × billing_periods) for financial forecasting
- **total_billed_amount**: Running total auto-updated when Sales Orders are generated
- **billing_manager**: User receiving auto-generated Sales Orders for review
- **project_manager**: Primary engagement owner responsible for setup and maintenance
- **project**: Optional link to Project (can be created later via "Create Project" button)
- **has_project**: Boolean checkbox indicating if associated project exists
- **quotation**: Link field to source Quotation (populated when created from Quotation)

**Sales Order Integration Fields** (inherited from Sales Order DocType):

**Customer Information**:
- **customer_name**: Customer display name for quick reference
- **customer_address**: Default billing address for the customer
- **contact_person**: Primary contact for this engagement
- **contact_display**: Contact person display name
- **contact_email**: Primary email for communications
- **contact_mobile**: Primary mobile contact number

**Financial Configuration**:
- **currency**: Transaction currency for this engagement
- **conversion_rate**: Currency conversion rate (if different from company currency)
- **selling_price_list**: Default price list for engagement items
- **price_list_currency**: Currency of the selected price list
- **plc_conversion_rate**: Price list currency conversion rate
- **ignore_pricing_rule**: Boolean to bypass automatic pricing rules

**Tax and Charges**:
- **taxes_and_charges**: Default tax template for Sales Orders
- **tax_category**: Tax category for proper tax calculations
- **shipping_rule**: Default shipping rules (if applicable)

**Company Details**:
- **company**: Company entity for this engagement
- **letter_head**: Default letterhead for documents
- **select_print_heading**: Print heading for engagement documents

**Order Configuration**:
- **order_type**: Type of orders to generate (Sales, Maintenance, etc.)
- **transaction_date**: Reference date for transactions
- **delivery_date**: Expected delivery/completion date
- **po_no**: Customer's purchase order number (if available)
- **po_date**: Customer's purchase order date

**Terms and Conditions**:
- **payment_terms_template**: Default payment terms for Sales Orders
- **tc_name**: Terms and conditions template
- **terms**: Detailed terms and conditions text

**Financial Dimensions**:
- **cost_center**: Default cost center for accounting purposes
- **source**: Lead/opportunity source tracking
- **campaign**: Marketing campaign attribution

**Sales Team Configuration**:
- **sales_team**: Child table for sales team allocation
- **sales_partner**: External sales partner (if applicable)
- **commission_rate**: Commission rate for sales partners

**Pricing Controls**:
- **customer_group**: Customer group for pricing rules
- **territory**: Geographic territory for regional pricing
- **apply_discount_on**: Base amount for discount calculation (Net Total/Grand Total)
- **additional_discount_percentage**: Overall discount percentage
- **discount_amount**: Fixed discount amount

**Warehouse Management**:
- **set_warehouse**: Default source warehouse
- **set_target_warehouse**: Default target warehouse (if applicable)

#### 2.1.2 Engagement Line Item (Child Table DocType)
**Primary Purpose**: Detailed specification of services, items, and deliverables included in each billing cycle.

**Key Business Fields and Logic**:
- **item_code**: Link to Item master enabling service catalog integration and pricing consistency
- **quantity**: Number of units to be billed (supports fractional values for partial services)
- **rate**: Unit price (can override Item master price for engagement-specific rates)
- **amount**: Auto-calculated (quantity × rate) for line-level billing accuracy
- **description**: Detailed service description appearing on Sales Orders and invoices
- **billing_frequency**: Individual line item billing schedule (monthly, quarterly, half yearly, annually)

#### 2.1.3 Engagement Activity (Child Table DocType)
**Primary Purpose**: Comprehensive audit trail of engagement lifecycle events and status changes.

**Key Business Fields and Logic**:
- **activity_date**: Timestamp of activity occurrence for chronological tracking
- **activity_type**: Categorization (Status Change, Billing Event, Manual Update, System Action)
- **from_status/to_status**: Workflow transition tracking for compliance and analysis
- **activity_description**: Detailed narrative of what occurred and why
- **user**: Person responsible for the activity (system vs manual actions)
- **reference_document**: Link to related documents (Sales Order, Project, etc.)

#### 2.1.4 Custom Fields Integration
**Sales Order Enhancements**:
- **engagement_record**: Link field connecting auto-generated SOs to their source engagement
- **is_auto_generated**: Boolean flag distinguishing automated vs manual Sales Orders
- **billing_period**: Text field indicating which period the SO covers (e.g., "January 2024")
- **project**: Optional link to Project (included only if engagement has associated project)

**Customer Enhancements**:
- **default_billing_day**: Customer preference for standard billing day across engagements
- **billing_manager_default**: Default billing manager for new engagements
- **engagement_portal_access**: Boolean enabling customer engagement visibility

**Quotation Enhancements**:
- **create_engagement**: Custom button visible when Quotation status is "Submitted"
- **engagement_created**: Boolean flag to track if engagement was already created

**Project Enhancements**:
- **engagement_record**: Link field connecting Projects to their source engagement
- **created_from_engagement**: Boolean flag indicating project origin

### 2.2 Entity Relationship Diagram

```
    ┌─────────────────────┐         ┌─────────────────────┐         ┌─────────────────────┐
    │     Customer        │         │ Engagement Record   │         │     Quotation       │
    ├─────────────────────┤         ├─────────────────────┤         ├─────────────────────┤
    │ customer_name       │────────▶│ customer            │◀────────│ party_name          │
    │ customer_group      │   1:N   │ engagement_title    │   0:1   │ grand_total         │
    │ territory           │         │ status              │         │ valid_till          │
    │ default_billing_day │         │ retainer_amount     │         │ status              │
    │ billing_manager_def │         │ billing_day_of_month│         │ engagement_created  │
    └─────────────────────┘         │ start_date          │         └─────────────────────┘
                                    │ end_date            │
                                    │ total_contract_value│
                                    │ total_billed_amount │
                                    │ billing_manager     │
                                    │ project_manager     │
                                    │ project (optional)  │
                                    │ has_project         │
                                    │ quotation           │
                                    └─────────┬───────────┘
                                              │
                                              │ 1:N
                        ┌─────────────────────┼─────────────────────┬─────────────────────┐
                        │                     │                     │                     │
                        ▼                     ▼                     ▼                     ▼
            ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
            │ Engagement Line Item│ │ Engagement Activity │ │    Sales Order      │ │      Project        │
            ├─────────────────────┤ ├─────────────────────┤ ├─────────────────────┤ ├─────────────────────┤
            │ parent              │ │ parent              │ │ customer            │ │ project_name        │
            │ item_code           │ │ activity_date       │ │ engagement_record   │ │ customer            │
            │ quantity            │ │ activity_type       │ │ is_auto_generated   │ │ engagement_record   │
            │ rate                │ │ from_status         │ │ billing_period      │ │ expected_start_date │
            │ amount              │ │ to_status           │ │ transaction_date    │ │ expected_end_date   │
            │ description         │ │ activity_description│ │ project (optional)  │ │ status              │
            │ billing_frequency   │ │ user                │ │ total               │ │ created_from_engage │
            └─────────────────────┘ │ reference_document  │ │ status              │ └─────────────────────┘
                        │           └─────────────────────┘ └─────────────────────┘           │
                        │                                             │                       │
                        │           ┌─────────────────────┐           │                       │
                        └──────────▶│       Item          │◀──────────┘                       │
                                    ├─────────────────────┤                                   │
                                    │ item_code           │                                   │
                                    │ item_name           │◀──────────────────────────────────┘
                                    │ standard_rate       │
                                    │ item_group          │
                                    │ description         │
                                    └─────────────────────┘
```

## 3. Workflow Specifications

### 3.1 Complete System Workflow: Quotation → Engagement → Project

#### 3.1.1 Main Process Flow

```
    ┌─────────────┐   Create Eng.   ┌─────────────┐   Create Proj.  ┌─────────────┐
    │ Quotation   │─────Button─────▶│ Engagement  │─────Button─────▶│   Project   │
    │ (Submitted) │                 │   (Draft)   │                 │   (Open)    │
    └─────────────┘                 └─────┬───────┘                 └─────────────┘
                                          │
                                          │ Direct Submit
                                          ▼
                                   ┌─────────────┐
                                   │ Engagement  │
                                   │  (Active)   │
                                   └─────────────┘
```

#### 3.1.2 Engagement Record Workflow States and Transitions

```
    ┌─────────┐    Direct        ┌──────────┐
    │  Draft  │─────Submit──────▶│  Active  │
    └─────────┘                  └─────┬────┘
         │                             │
         │ Cancel                      │
         ▼                             │
    ┌─────────┐                        │
    │Cancelled│                        │
    └─────────┘                        │
                                       │
                   ┌──────────────┐    │
                   │    Paused    │◀───┴───Pause
                   └──────┬───────┘
                          │
                          │ Resume (back to Active)
                          ▼
                   ┌──────────────┐    Natural/Manual
                   │    Active    │─────Ending────────┐
                   └──────────────┘                   │
                                                      ▼
                   ┌──────────────┐              ┌──────────┐
                   │   Stopped    │◀─────Stop────│ Expired  │
                   └──────────────┘              └──────────┘
```

**State Definitions and Business Logic**:

1. **Draft**: Initial state for new engagements
   - Editable by System Administrator during creation process
   - Not eligible for billing
   - Can transition to: Active (direct submission), Cancelled

2. **Active**: Operational state eligible for automated billing
   - Achieved directly upon submission from Draft
   - Triggers daily billing process evaluation
   - Generates Sales Orders on matching billing day
   - Can transition to: Paused, Stopped, Expired

3. **Paused**: Temporarily suspended billing
   - Maintains engagement record but stops billing
   - Can transition to: Active (resume), Stopped

4. **Stopped**: Manually terminated engagement
   - Final state - no further billing
   - Audit trail preserved

5. **Expired**: Naturally ended engagement
   - End date reached or contract fulfilled
   - Final state - no further billing

6. **Cancelled**: Abandoned before activation
   - No billing occurred
   - Can be deleted if no activities recorded

### 3.2 Quotation to Engagement Creation Process

```
    ┌─────────────────┐    Check        ┌─────────────────┐
    │   Quotation     │────Status──────▶│   Submitted?    │
    │                 │                 └─────┬─────┬─────┘
    └─────────────────┘                       │     │
                                             Yes    No
                                              │     │
                                              ▼     ▼
                                      ┌───────────┐ ┌───────────┐
                                      │Show "Create│ │Hide Button│
                                      │Engagement"│ └───────────┘
                                      │  Button   │
                                      └─────┬─────┘
                                            │
                                            ▼
                                    ┌───────────────┐
                                    │Map Quotation  │
                                    │Data to        │
                                    │Engagement     │
                                    └───────┬───────┘
                                            │
                                            ▼
                                    ┌───────────────┐
                                    │Create New     │
                                    │Engagement     │
                                    │(Draft Status) │
                                    └───────────────┘
```

### 3.3 Project Creation from Engagement Process

```
    ┌─────────────────┐    Check        ┌─────────────────┐
    │   Engagement    │────Status──────▶│    Active?      │
    │    Record       │                 └─────┬─────┬─────┘
    └─────────────────┘                       │     │
                                             Yes    No
                                              │     │
                                              ▼     ▼
                                      ┌───────────┐ ┌───────────┐
                                      │Show "Create│ │Hide Button│
                                      │ Project" │ └───────────┘
                                      │  Button   │
                                      └─────┬─────┘
                                            │
                                            ▼
                                    ┌───────────────┐
                                    │Create New     │
                                    │Project with   │
                                    │Engagement Data│
                                    └───────┬───────┘
                                            │
                                            ▼
                                    ┌───────────────┐
                                    │Link Project   │
                                    │Back to        │
                                    │Engagement     │
                                    └───────┬───────┘
                                            │
                                            ▼
                                    ┌───────────────┐
                                    │Set has_project│
                                    │= True         │
                                    └───────────────┘
```

### 3.4 Direct Activation Logic

```
    Engagement Created (Draft)
           │
           ▼
    ┌────────────────┐
    │   Validation   │
    │   Complete     │
    └────────┬───────┘
             │
             ▼
    ┌────────────────┐
    │   Directly     │
    │   Activate     │
    └────────────────┘
```

## 4. Use Cases and User Journeys

### 4.1 Use Case Diagram

```
         ┌────────────────────────────────────────────────────────────┐
         │              Engagement Management System                  │
         │                                                            │
         │  ○─────Create Engagement from Quotation                    │
         │  │                                                         │
         │  ○─────Create and Manage All Engagements                   │
         │  │                                                         │
         │  ○─────Update Engagement Details                           │
         │  │                                                         │
         │  ○─────Monitor Billing Status                              │
         │  │                                                         │
         │  ○─────Create Project from Engagement                      │
         │  │                                                         │    👤
         │  ○─────Handle All Billing Operations                       │──System
         │  │                                                         │   Admin
         │  ○─────Review Auto-Generated Sales Orders                  │
         │  │                                                         │
         │  ○─────System Maintenance and Configuration                │
         │  │                                                         │
         │  ○─────Monitor Automated Processes                         │
         │                                                             │
         │                    ○─────View Engagement Data           │───👤
         │                    │                                    │   Other
         │                    ○─────Access Reports (Read-Only)     │   Users
         │                                                             │
         │                          ○─────View Engagement Portal  │───👤
         │                          │                             │ Client
         │                          ○─────Access Billing History  │
         │                                                           │
         └────────────────────────────────────────────────────────────┘
```

### 4.2 Detailed Use Case Descriptions

#### Use Case 1: Create Engagement from Quotation
**Primary Actor**: System Administrator
**Goal**: Convert a submitted quotation into a new engagement record
**Preconditions**: Quotation exists in Submitted status, System Administrator permissions
**Main Flow**:
1. Open submitted Quotation
2. Click "Create Engagement" button
3. System maps quotation data to new engagement:
   - Customer → customer
   - Grand Total → retainer_amount (if applicable)
   - Items → Engagement Line Items
   - Valid Till → suggested end_date
4. Review and modify engagement details as needed
5. Submit to directly activate the engagement
**Postconditions**: Engagement created in Active state, quotation marked as engagement_created
**Alternative Flows**: Manual engagement creation without quotation reference

#### Use Case 1b: Create Project from Engagement
**Primary Actor**: System Administrator
**Goal**: Create a project linked to an active engagement
**Preconditions**: Engagement exists in Active status, System Administrator permissions
**Main Flow**:
1. Open active Engagement Record
2. Click "Create Project" button
3. System creates new project with:
   - Project Name: {Engagement Title} - {Customer Name}
   - Customer: Linked from Engagement
   - Expected dates from engagement timeline
4. System links project back to engagement
5. Sets has_project = True on engagement
**Postconditions**: Project created and linked, engagement shows project association
**Alternative Flows**: Manual project linking if project already exists

#### Use Case 2: Automated Sales Order Generation Process
**Primary Actor**: System Scheduler
**Goal**: Generate Sales Orders for due engagements without manual intervention
**Preconditions**: Active engagements exist, scheduler running
**Main Flow**:
1. Query active engagements matching current billing day
2. Validate no duplicate Sales Orders exist
3. Create Sales Order with engagement line items
4. Update engagement billing totals and next billing date
5. Notify system administrator and billing manager
6. Log activity in engagement record
**Postconditions**: Sales Orders created, notifications sent, records updated
**Exception Flows**: Handle duplicate detection, customer validation failures

## 5. Process Flows and Business Logic

### 5.1 Quotation to Engagement Creation Sequence Diagram

```
User        Quotation     System       Engagement    Customer
 │             │            │           Record       Master
 │             │            │             │            │
 │─Click "Create─────────────▶│             │            │
 │  Engagement"│            │             │            │
 │             │            │             │            │
 │             │───Validate▶│             │            │
 │             │   Status   │             │            │
 │             │◀─Submitted──│             │            │
 │             │            │             │            │
 │             │───Get Data▶│             │            │
 │             │◀─Quotation──│             │            │
 │             │    Data     │             │            │
 │             │            │             │            │
 │             │────────────Map Data────▶│            │
 │             │            │            │            │
 │             │────────────Get Customer─────────────▶│
 │             │            │            │◀─Customer───│
 │             │            │            │    Data     │
 │             │            │            │            │
 │             │────────────Create New──▶│            │
 │             │            │  Engagement │            │
 │             │            │◀─Draft Created─────────│
 │             │            │            │            │
 │◀─Engagement─────────────Open Form────│            │
 │   Form      │            │            │            │
 │             │            │            │            │
 │─Submit──────────────────Direct Activate▶│            │
 │◀─Active─────────────────Status Update───│            │
```

### 5.2 Project Creation from Engagement Sequence Diagram

```
User        Engagement    System       Project      Customer
 │           Record        Validation    Module       Master
 │             │            │             │            │
 │─Click "Create─────────────▶│             │            │
 │  Project"  │            │             │            │
 │             │            │             │            │
 │             │───Validate▶│             │            │
 │             │   Status   │             │            │
 │             │◀─Active────│             │            │
 │             │            │             │            │
 │             │───Get Data▶│             │            │
 │             │◀─Engagement─│             │            │
 │             │    Data     │             │            │
 │             │            │             │            │
 │             │────────────Create Project─────────────▶│
 │             │            │            │            │
 │             │────────────Get Customer─────────────────▶│
 │             │            │            │◀─Customer────│
 │             │            │            │    Data     │
 │             │            │            │            │
 │             │            │◀─Project────│            │
 │             │            │   Created   │            │
 │             │            │            │            │
 │             │◀───────────Link Project▶│            │
 │             │            │            │            │
 │             │───Update──▶│             │            │
 │             │has_project │             │            │
 │             │◀─Updated───│             │            │
 │             │            │             │            │
 │◀─Project────────────────Success────────│            │
 │   Created   │            │             │            │
```

### 5.3 Enhanced Automated Billing Process Sequence Diagram

```
System      Engagement    Sales Order    Project     Customer     Billing      Finance
Scheduler     Record        Module       Module       Master       Manager       Team
   │            │             │            │            │            │            │
   │──Query──┐  │             │            │            │            │            │
   │         │  │             │            │            │            │            │
   │◀────────┘  │             │            │            │            │            │
   │            │             │            │            │            │            │
   │─Validate───▶│             │            │            │            │            │
   │◀─Active─────│             │            │            │            │            │
   │            │             │            │            │            │            │
   │─Check Project────────────────────────▶│            │            │            │
   │◀─Project Info──────────────────────────│            │            │            │
   │            │             │            │            │            │            │
   │─Check Duplicates────────▶ │            │            │            │            │
   │◀─No Duplicates───────────│            │            │            │            │
   │            │             │            │            │            │            │
   │─Get Customer Info─────────────────────────────────▶│            │            │
   │◀─Customer Data────────────────────────────────────│            │            │
   │            │             │            │            │            │            │
   │─Create SO──▶│             │            │            │            │            │
   │            │─Line Items──▶│            │            │            │            │
   │            │─Project Link────────────▶│            │            │            │
   │            │◀─SO Created──│            │            │            │            │
   │◀─Success───│             │            │            │            │            │
   │            │             │            │            │            │            │
   │─Update Totals─▶│          │            │            │            │            │
   │◀─Updated───────│          │            │            │            │            │
   │            │             │            │            │            │            │
   │─Send Notification─────────────────────────────────────────────▶│            │
   │─Send Notification──────────────────────────────────────────────────────────▶│
   │            │             │            │            │            │            │
   │─Log Activity──▶│          │            │            │            │            │
   │◀─Complete──────│          │            │            │            │            │
```

### 5.4 Business Rules and Calculations

#### 5.4.1 Quotation to Engagement Mapping Logic
```
ALGORITHM: Create Engagement from Quotation
INPUT: quotation_doc
OUTPUT: engagement_record (dict)

BEGIN
  // Validate quotation status
  IF quotation.docstatus != 1 THEN
    THROW "Quotation must be submitted"
  END IF
  
  IF quotation.engagement_created == True THEN
    THROW "Engagement already created from this quotation"
  END IF
  
  // Map basic fields
  engagement_data = {
    "customer": quotation.party_name,
    "engagement_title": quotation.title OR "Engagement for " + quotation.party_name,
    "quotation": quotation.name,
    "retainer_amount": quotation.grand_total,
    "start_date": TODAY(),
    "end_date": quotation.valid_till OR ADD_MONTHS(TODAY(), 12)
  }
  
  // Map line items
  FOR each item IN quotation.items DO
    engagement_line_item = {
      "item_code": item.item_code,
      "quantity": item.qty,
      "rate": item.rate,
      "amount": item.amount,
      "description": item.description
    }
    ADD engagement_line_item TO engagement_data.line_items
  END FOR
  
  // Create engagement record
  engagement = CREATE_DOC("Engagement Record", engagement_data)
  SAVE engagement
  
  // Mark quotation as processed
  SET quotation.engagement_created = True
  SAVE quotation
  
  RETURN engagement.name
END
```

#### 5.4.2 Project Creation Logic
```
ALGORITHM: Create Project from Engagement
INPUT: engagement_record
OUTPUT: project_name (string)

BEGIN
  // Validate engagement status
  IF engagement.status != "Active" THEN
    THROW "Engagement must be active to create project"
  END IF
  
  IF engagement.has_project == True THEN
    THROW "Project already exists for this engagement"
  END IF
  
  // Create project data
  project_data = {
    "project_name": engagement.engagement_title + " - " + engagement.customer,
    "customer": engagement.customer,
    "engagement_record": engagement.name,
    "expected_start_date": engagement.start_date,
    "expected_end_date": engagement.end_date,
    "status": "Open",
    "created_from_engagement": True
  }
  
  // Create and save project
  project = CREATE_DOC("Project", project_data)
  SAVE project
  
  // Update engagement record
  SET engagement.project = project.name
  SET engagement.has_project = True
  SAVE engagement
  
  RETURN project.name
END
```

#### 5.4.3 Billing Eligibility Algorithm
```
ALGORITHM: Determine Billing Eligibility
INPUT: engagement_record, current_date
OUTPUT: boolean (eligible_for_billing)

BEGIN
  IF engagement.status != "Active" THEN
    RETURN FALSE
  END IF
  
  IF engagement.start_date > current_date THEN
    RETURN FALSE
  END IF
  
  IF engagement.end_date < current_date THEN
    SET engagement.status = "Expired"
    RETURN FALSE
  END IF
  
  IF current_date.day != engagement.billing_day_of_month THEN
    RETURN FALSE
  END IF
  
  // Check for existing Sales Order in current period
  existing_so = QUERY Sales_Order WHERE
    engagement_record = engagement.name AND
    MONTH(transaction_date) = MONTH(current_date) AND
    YEAR(transaction_date) = YEAR(current_date)
  
  IF existing_so EXISTS THEN
    LOG "Duplicate billing prevented for " + engagement.name
    RETURN FALSE
  END IF
  
  RETURN TRUE
END
```

#### 5.4.4 Total Contract Value Calculation
```
ALGORITHM: Calculate Total Contract Value
INPUT: engagement_record
OUTPUT: decimal (total_contract_value)

BEGIN
  billing_periods = CALCULATE_BILLING_PERIODS(
    engagement.start_date,
    engagement.end_date,
    engagement.billing_frequency
  )
  
  line_items_total = SUM(
    SELECT (quantity * rate) FROM engagement_line_items 
    WHERE parent = engagement.name
  )
  
  total_contract_value = (engagement.retainer_amount + line_items_total) * billing_periods
  
  RETURN total_contract_value
END
```

#### 5.4.5 Direct Activation Logic
```
ALGORITHM: Process Engagement Submission
INPUT: engagement_record
OUTPUT: activation_status (string)

BEGIN
  // Validate required fields
  IF NOT VALIDATE_REQUIRED_FIELDS(engagement) THEN
    RETURN "validation_failed"
  END IF
  
  // Validate business rules
  IF NOT VALIDATE_BUSINESS_RULES(engagement) THEN
    RETURN "business_validation_failed"
  END IF
  
  // Direct activation
  SET engagement.status = "Active"
  SAVE engagement
  
  RETURN "activated"
END
```

## 6. Reports and Dashboards

### 6.1 Report Specifications

#### 6.1.1 Engagement Revenue Report (Script Report)
**Purpose**: Comprehensive revenue analysis across all engagements
**Data Sources**: Engagement Record, Sales Order, Customer
**Key Metrics**:
- Total Contract Value by customer/period
- Billed vs Unbilled amounts
- Revenue recognition status
- Billing accuracy metrics

**Filters**:
- Date range (start_date, end_date)
- Customer selection
- Engagement status
- Project Manager
- Revenue threshold ranges

#### 6.1.2 Automated Billing Summary (Query Report)
**Purpose**: Daily/weekly summary of automated billing activities
**Data Sources**: Engagement Record, Sales Order, Engagement Activity
**Key Metrics**:
- Sales Orders generated per day
- Billing success rate
- Exception handling statistics
- Average processing time

**Filters**:
- Processing date range
- Success/failure status
- Billing Manager
- Customer group

#### 6.1.3 Engagement Pipeline Report (Report Builder)
**Purpose**: Sales pipeline analysis for engagement forecasting
**Data Sources**: Engagement Record, Customer
**Key Metrics**:
- Pipeline value by status
- Conversion rates
- Average time in each workflow state
- Seasonal billing patterns

### 6.2 Dashboard Design

#### 6.2.1 Executive Dashboard
**KPI Number Cards**:
- Total Active Engagements
- Monthly Recurring Revenue (MRR)
- Billing Accuracy Percentage
- Average Contract Value

**Charts**:
- Revenue Trend (Line Chart) - Monthly recurring revenue over time
- Engagement Status Distribution (Donut Chart) - Active vs Paused vs Stopped
- Top Customers by Value (Bar Chart) - Revenue contribution analysis
- Billing Success Rate (Gauge) - Real-time accuracy metrics

#### 6.2.2 Operations Dashboard
**KPI Number Cards**:
- Today's Active Engagements Count
- Today's Billing Queue Size
- Failed Billing Attempts
- System Health Score

**Charts**:
- Daily Billing Volume (Bar Chart) - Sales Orders generated per day
- Exception Trends (Line Chart) - Failed billings over time
- Engagement Status Distribution (Funnel Chart) - State analysis
- Resource Utilization (Heat Map) - Project Manager workload

## 7. User Interface Requirements

### 7.1 Form Layouts

#### 7.1.1 Engagement Record Form Layout
**Section 1: Basic Information**
- Customer (mandatory, link field with filters)
- Engagement Title (mandatory, 150 char limit)
- Status (read-only, workflow controlled)
- Project Manager (assigned by System Administrator, user field)

**Section 2: Billing Configuration**
- Retainer Amount (mandatory, currency field)
- Billing Frequency (dropdown: Monthly, Quarterly, Half Yearly, Annually)
- Billing Day of Month (number field, 1-31 range)
- Billing Manager (mandatory, user field with role filter)

**Section 3: Contract Details**
- Start Date (mandatory, date validation)
- End Date (mandatory, must be after start date)
- Total Contract Value (read-only, calculated)
- Total Billed Amount (read-only, auto-updated)

**Section 4: Line Items Table**
- Item Code, Quantity, Rate, Amount
- Description, Billing Frequency
- Inline editing with real-time calculations

**Section 5: Activity Log**
- Read-only child table showing all activities
- Filterable by activity type and date range

#### 7.1.2 Custom Buttons and Actions
**Engagement Record Buttons**:
- "Create Project" (visible when Active and has_project = False)
- "View Project" (visible when has_project = True, link to associated project)
- "Pause Engagement" (visible when Active)
- "Resume Engagement" (visible when Paused)
- "Generate Preview SO" (test billing without creation)
- "View Billing History" (filtered Sales Order list)
- "Customer Portal Link" (quick access for sharing)

**Quotation Custom Buttons**:
- "Create Engagement" (visible when Submitted and engagement_created = False)
- "View Engagement" (visible when engagement_created = True, link to created engagement)

**Bulk Actions**:
- Bulk status updates for selected engagements
- Bulk billing manager reassignment
- Export engagement data for analysis

### 7.2 List Views and Filters

#### 7.2.1 Engagement Record List View
**Default Columns**:
- Engagement Title, Customer, Status
- Retainer Amount, Next Billing Date
- Project Manager, Total Billed Amount

**Standard Filters**:
- Status (multiselect with color coding)
- Customer (searchable dropdown)
- Project Manager (user filter)
- Billing Date Range
- Contract Value Range

**Saved Filters**:
- "My Active Engagements"
- "High Value Contracts"
- "Billing Due Today"
- "Expiring This Month"
- "Recently Created"

#### 7.2.2 Advanced Search and Filtering
**Global Search Integration**:
- Full-text search across engagement titles and descriptions
- Customer name and code search
- Search within line item descriptions

**Dynamic Filters**:
- Revenue threshold sliders
- Date range pickers with presets
- Multi-status filtering by engagement state

## 8. Integration Requirements with ERPNext Modules

### 8.1 Sales Module Integration

#### 8.1.1 Sales Order Auto-Generation
**Process Flow**:
1. Daily scheduler identifies eligible engagements (created by System Administrator)
2. System creates Sales Order with engagement data
3. Line items copied from Engagement Line Items
4. Customer billing address auto-populated
5. Sales Order linked to original engagement
6. **Project linking**: If engagement has associated project (has_project = True), Sales Order includes project reference

**Field Mappings**:
- Engagement Record → Sales Order (custom link field)
- Customer → Customer (direct copy)
- Engagement Line Items → Sales Order Items
- Project → Project (conditional - only if engagement.has_project = True)
- Billing Manager → Sales Person (optional)
- Engagement Title → Sales Order Description

#### 8.1.2 Sales Pipeline Integration
**Quotation to Engagement Flow**:
- **Manual User Action**: System Administrator uses "Create Engagement" button on submitted Quotations
- System maps quotation data to new engagement record automatically
- Preserve quotation reference and customer relationship data
- Maintain complete audit trail from quotation to active engagement

**Key Integration Points**:
- Quotation (Submitted) → [User clicks "Create Engagement"] → Engagement Record (Draft)
- Field mapping: Customer, Items, Grand Total, Valid Till date
- Automatic linking preserves sales context and customer data


### 8.3 Projects Module Integration

#### 8.3.1 Project-Based Engagements
**Project Creation Process**:
- **Manual User Action**: "Create Project" button available on Active engagements (System Administrator only)
- **Optional Functionality**: Projects are NOT mandatory for engagements
- **Dynamic Creation**: System Administrator decides when to create projects based on engagement needs
- **Automatic Linking**: Created projects automatically link back to source engagement

**Project Data Mapping**:
- Project Name: "{Engagement Title} - {Customer Name}"
- Customer: Inherited from engagement
- Timeline: Expected dates from engagement start/end dates
- Status: Created as "Open" status
- Engagement Reference: Bidirectional linking maintained

**Integration Features**:
- **has_project Flag**: Engagement tracks whether associated project exists
- **Sales Order Integration**: When project exists, Sales Orders include project reference
- **Time Tracking**: Optional integration for service validations
- **Resource Allocation**: Project-based capacity planning when needed

**Deliverable Tracking**:
- Project tasks can be linked to engagement line items
- Progress-based billing adjustments (if configured)
- Client deliverable tracking through project module
- Milestone-based billing triggers (optional feature)

### 8.4 CRM Module Integration

#### 8.4.1 Customer Communication
**Automated Notifications**:
- Engagement status change alerts
- Billing reminders and confirmations
- Contract renewal notifications
- Custom email templates integration

**Communication Timeline**:
- Engagement activities in customer timeline
- Centralized communication history
- Integration with Email Account management

### 8.5 Items Module Integration

#### 8.5.1 Service Catalog Management
**Item Master Enhancement**:
- Service-specific item categories
- Standard rates for engagement services
- Item variants for different service levels
- Bulk pricing rules integration

**Pricing Integration**:
- Customer-specific pricing overrides
- Volume-based pricing tiers
- Seasonal pricing adjustments
- Currency conversion handling

## 9. System Architecture and Technical Specifications

### 9.1 DocType Architecture Diagram

```
                    ┌─────────────────────────────────────────────┐
                    │              Frappe Framework               │
                    │                                             │
                    │  ┌───────────────┐    ┌───────────────────┐│
                    │  │   Scheduler   │    │   Workflow        ││
                    │  │   Framework   │    │   Engine          ││
                    │  └───────┬───────┘    └─────────┬─────────┘│
                    └──────────┼──────────────────────┼──────────┘
                               │                      │
    ┌──────────────────────────┼──────────────────────┼─────────────────────┐
    │                          ▼                      ▼                     │
    │  ┌─────────────────────────────────────────────────────────────────┐  │
    │  │                Engagement Management Module                     │  │
    │  │                                                                 │  │
    │  │  ┌──────────────────┐         ┌──────────────────────────────┐ │  │
    │  │  │ Engagement Record│◄────────┤        Master DocType        │ │  │
    │  │  │                  │         │                              │ │  │
    │  │  │ • Workflow States│         │ • Customer Integration       │ │  │
    │  │  │ • Billing Logic  │         │ • Direct Activation        │ │  │
    │  │  │ • Automation     │         │ • Revenue Calculations      │ │  │
    │  │  └──────┬───────────┘         └──────────────────────────────┘ │  │
    │  │         │                                                      │  │
    │  │         ├──────────────────┬─────────────────────────────────┐ │  │
    │  │         ▼                  ▼                                 ▼ │  │
    │  │  ┌──────────────┐   ┌─────────────────┐   ┌─────────────────┐│  │
    │  │  │ Line Items   │   │   Activities    │   │  Custom Fields  ││  │
    │  │  │              │   │                 │   │                 ││  │
    │  │  │ • Service    │   │ • Audit Trail   │   │ • Sales Order   ││  │
    │  │  │   Catalog    │   │ • Status Changes│   │   Integration   ││  │
    │  │  │ • Pricing    │   │ • User Actions  │   │ • Customer      ││  │
    │  │  │ • Billing    │   │ • System Events │   │   Enhancements  ││  │
    │  │  └──────────────┘   └─────────────────┘   └─────────────────┘│  │
    │  └─────────────────────────────────────────────────────────────────┘  │
    └─────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
    ┌─────────────────────────────────────────────────────────────────────────┐
    │                          ERPNext Integration                            │
    │                                                                         │
    │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────────┐│
    │  │ Sales   │  │Accounts │  │Projects │  │   CRM   │  │      Items      ││
    │  │ Orders  │  │Revenue  │  │Resource │  │Customer │  │   Service       ││
    │  │Auto-Gen │  │Recogn.  │  │Planning │  │ Portal  │  │   Catalog       ││
    │  └─────────┘  └─────────┘  └─────────┘  └─────────┘  └─────────────────┘│
    └─────────────────────────────────────────────────────────────────────────┘
```

### 9.2 Data Flow Architecture

```
    ┌─────────────┐      ┌──────────────────┐      ┌─────────────────────┐
    │   Client    │─────▶│    Engagement    │─────▶│    Billing          │
    │ Onboarding  │      │    Creation      │      │    Automation       │
    └─────────────┘      └──────────────────┘      └─────────────────────┘
           │                       │                          │
           │                       ▼                          ▼
           │              ┌──────────────────┐      ┌─────────────────────┐
           │              │    Direct        │      │   Sales Order       │
           │              │   Activation     │      │    Generation       │
           │              └──────────────────┘      └─────────────────────┘
           │                       │                          │
           ▼                       ▼                          ▼
    ┌─────────────┐      ┌──────────────────┐      ┌─────────────────────┐
    │  Customer   │      │     Active       │      │    Revenue          │
    │   Portal    │◀─────┤   Engagement     │─────▶│   Recognition       │
    └─────────────┘      └──────────────────┘      └─────────────────────┘
```


### 9.3 Security and Permissions Matrix

```
                    ┌─────────────────────────────────────────────────────────┐
                    │                     Role Permissions                   │
                    ├─────────────┬─────────────┬───────────────────────────┤
                    │   DocType   │   System    │      Other ERPNext       │
                    │   Actions   │Administrator│         Users            │
                    ├─────────────┼─────────────┼───────────────────────────┤
                    │Create Engage│      ✓      │            ✗             │
                    │Read Engage  │      ✓      │     ✓ (as needed)        │
                    │Write Engage │      ✓      │            ✗             │
                    │Delete Engage│      ✓      │            ✗             │
                    │View Reports │      ✓      │     ✓ (as needed)        │
                    │System Config│      ✓      │            ✗             │
                    │Billing Ops  │      ✓      │            ✗             │
                    └─────────────┴─────────────┴───────────────────────────┘
```

### 9.4 Error Handling and Logging

#### 9.5.1 Exception Handling Strategy
```python
# Billing Process Error Handling
try:
    engagements = get_eligible_engagements()
    for engagement in engagements:
        try:
            validate_engagement(engagement)
            sales_order = create_sales_order(engagement)
            update_engagement_totals(engagement, sales_order)
            log_success(engagement, sales_order)
        except ValidationError as e:
            log_error(engagement, "Validation Failed", str(e))
            send_alert_to_admin(engagement, e)
        except DuplicateError as e:
            log_warning(engagement, "Duplicate SO Detected", str(e))
        except Exception as e:
            log_critical(engagement, "Unexpected Error", str(e))
            escalate_to_admin(engagement, e)
except SystemError as e:
    log_critical("System", "Scheduler Failure", str(e))
    send_emergency_alert(e)
```

## 10. Permissions and Security Matrix

### 10.1 Role-Based Access Control

```
                    ┌─────────────────────────────────────────────────────────┐
                    │                     Role Permissions                   │
                    ├─────────────┬─────────────┬───────────────────────────┤
                    │   DocType   │   System    │      Other ERPNext       │
                    │   Actions   │Administrator│         Users            │
                    ├─────────────┼─────────────┼───────────────────────────┤
                    │Create Engage│      ✓      │            ✗             │
                    │Read Engage  │      ✓      │     ✓ (as needed)        │
                    │Write Engage │      ✓      │            ✗             │
                    │Delete Engage│      ✓      │            ✗             │
                    │View Reports │      ✓      │     ✓ (as needed)        │
                    │System Config│      ✓      │            ✗             │
                    │Billing Ops  │      ✓      │            ✗             │
                    └─────────────┴─────────────┴───────────────────────────┘
```

### 10.2 DocType-Level Permissions

#### 10.2.1 Engagement Record Permissions
- **Create**: System Administrators only
- **Read**: System Administrators (full access), Other users (as needed based on customer permissions)
- **Write**: System Administrators only
- **Delete**: System Administrators only (with business justification)
- **Submit/Cancel**: System Administrators only
- **Submit**: Direct activation without approval process

#### 10.2.2 Field-Level Security
```
Field Restrictions by Role:
┌─────────────────────┬─────────────────────────────────────────┐
│ Field Name          │ Restriction Rules                       │
├─────────────────────┼─────────────────────────────────────────┤
│ retainer_amount     │ Read-only for billing managers         │
│ total_billed_amount │ Read-only for all users (system calc)  │
│ customer            │ Restricted by user permissions         │
│ billing_manager     │ Changeable by PM and above only        │
│ workflow_state      │ Read-only (workflow controlled)        │
└─────────────────────┴─────────────────────────────────────────┘
```

### 10.3 Data Access Controls

#### 10.3.1 Customer-Based Restrictions
- Users can only access engagements for customers they have permission to view
- Customer permissions inherited from ERPNext Customer master
- Territory-based access control for geographical restrictions
- Customer group permissions for organizational access control

#### 10.3.2 Engagement Ownership Rules
- System Administrators create, configure, and manage all engagement records
- System Administrators handle all billing operations and configuration changes
- Other ERPNext users have read-only access as needed for their specific operational requirements
- All engagement modifications, billing operations, and system configurations are controlled by System Administrators

### 10.4 API Security Framework

#### 10.4.1 Authentication Requirements
- All API endpoints require valid ERPNext session authentication
- API key authentication for automated system integrations
- Rate limiting: 100 requests per minute per user
- IP whitelisting for sensitive operations

#### 10.4.2 Authorization Validation
```python
# Example API Security Implementation
@frappe.whitelist()
def get_engagement_data(engagement_id):
    # Validate user permissions
    if not frappe.has_permission("Engagement Record", "read", engagement_id):
        frappe.throw(_("Insufficient permissions to access this engagement"))
    
    # Additional customer-level validation
    engagement = frappe.get_doc("Engagement Record", engagement_id)
    if not frappe.has_permission("Customer", "read", engagement.customer):
        frappe.throw(_("No access to customer data"))
    
    return engagement
```

### 10.5 Audit Trail and Logging

#### 10.5.1 Activity Logging Requirements
- All engagement modifications logged with user, timestamp, and changes
- Billing process activities automatically logged with system details
- Login/logout activities for engagement-related pages
- Failed permission attempts logged for security monitoring
- Workflow state transition activities with complete audit trail

#### 10.5.2 Data Retention Policies
- Engagement activity logs retained for 7 years (financial audit requirements)
- Billing transaction logs permanently retained
- User access logs retained for 2 years
- System error logs retained for 1 year
- Automated log archival and compression after retention periods

---

## 11. Recent Enhancements (V2.1)

### 11.1 Half Yearly Billing Frequency Support

#### 11.1.1 Business Requirement
**Enhancement**: Addition of "Half Yearly" billing frequency to support clients with 6-month billing cycles.

**Business Justification**:
- Addresses client requirements for semi-annual billing arrangements
- Provides more flexible billing options beyond quarterly and annual cycles  
- Supports diverse contract structures in professional services industry
- Enables better cash flow management for both provider and client

#### 11.1.2 Functional Specifications

**Billing Frequency Options Updated**:
- **Monthly**: Generates Sales Orders every month
- **Quarterly**: Generates Sales Orders every 3 months  
- **Half Yearly**: Generates Sales Orders every 6 months *(NEW)*
- **Annually**: Generates Sales Orders every 12 months

**Half Yearly Billing Logic**:
```
Billing Period Calculation:
- Start Date: 2025-01-01
- End Date: 2025-12-31  
- Half Yearly Periods: 2 periods (Jan-Jun, Jul-Dec)
- Contract Value: Monthly Amount × 2 periods

Next Billing Date Calculation:
- Current Billing Date: 2025-01-15
- Next Half Yearly Billing: 2025-07-15 (+6 months)
- Subsequent Billing: 2026-01-15 (+6 months)
```

#### 11.1.3 Technical Implementation

**DocType Updates**:
1. **Engagement Record** - `billing_frequency` field options updated
2. **Engagement Line Item** - Line-level half yearly billing support
3. **Quotation.js** - Dialog billing frequency options updated

**Backend Logic Enhancements**:
```python
# Total Contract Value Calculation
elif self.billing_frequency == "Half Yearly":
    half_years = max(1, ((end_date.year - start_date.year) * 2 + 
                        (end_date.month - start_date.month) / 6))
    self.total_contract_value = total_monthly_amount * half_years

# Billing Date Updates  
elif self.billing_frequency == "Half Yearly":
    if is_deleted:
        new_billing_date = add_months(self.next_billing_date, -6)
    else:
        new_billing_date = add_months(self.next_billing_date, 6)
```

**Frontend Integration**:
- Quotation creation dialog includes Half Yearly option
- Engagement form displays Half Yearly in billing frequency dropdown
- Contract value calculations updated for 6-month intervals

#### 11.1.4 User Experience Impact

**Benefits for Users**:
- **Sales Teams**: More billing frequency options to match client requirements
- **Finance Teams**: Simplified semi-annual billing management  
- **Clients**: Flexible billing arrangements aligned with their fiscal cycles
- **System Administrators**: Consistent automation for all billing frequencies

**Process Changes**:
- No changes to existing workflows or user permissions
- Seamless integration with existing Monthly, Quarterly, and Annual cycles
- Automatic calculation updates for contract values and billing dates

#### 11.1.5 Testing and Validation

**Test Scenarios**:
1. **Contract Value Calculation**: Verify 6-month period calculations
2. **Billing Date Progression**: Test 6-month interval advancement  
3. **Sales Order Generation**: Validate automated SO creation for half yearly cycles
4. **Quotation Integration**: Test engagement creation with Half Yearly frequency
5. **UI Consistency**: Verify dropdown options display correctly across all forms

**Success Criteria**:
- ✅ Half Yearly option available in all billing frequency dropdowns
- ✅ Contract value calculations accurate for 6-month periods
- ✅ Billing date advancement works correctly (+/-6 months)
- ✅ Sales Order generation follows half yearly schedule
- ✅ No impact on existing Monthly/Quarterly/Annual functionality

---

## Document Control

**Document Version**: 2.1  
**Created Date**: September 2, 2025  
**Last Modified**: September 10, 2025  
**Document Owner**: Product Management Team  
**Review Cycle**: Quarterly  
**Next Review Date**: December 2, 2025  

**Review Matrix**:
- Technical Lead: Required for system architecture changes
- Product Manager: Required for feature specifications
- Operations Manager: Required for workflow changes

**Distribution List**:
- Development Team (for implementation)
- QA Team (for testing specifications)
- Operations Team (for deployment planning)
- Customer Success Team (for user training materials)

**File Location**: `/home/frappe/frappe-bench/apps/hybrowlabs_customization/hybrowlabs_customization/docs/PRDs/engagement-management-billing-system-prd.md`

---

*This document serves as the comprehensive technical specification for the Hybrowlabs Engagement Management and Automated Billing System. All implementation decisions should reference this PRD to ensure alignment with business objectives and functional requirements.*