# Partner Controller Documentation

**File**: `/controllers/partnerController.php`  
**Purpose**: Business partnership management system with profit sharing and financial tracking  
**Last Updated**: December 20, 2024  
**Total Functions**: 8  
**Lines of Code**: ~735

---

## 📋 Overview

The Partner Controller is a sophisticated business partnership management system that handles partner registration, profit tracking, and financial management. It provides:
- Partner registration and profile management
- Partner money investment tracking
- Profit percentage allocation
- Financial transaction history
- Partner withdrawal management
- Accounting tree integration
- Daily entry generation for financial records
- Multi-currency support

### Primary Functions
- [x] Partner registration and management
- [x] Investment amount tracking
- [x] Profit percentage calculation
- [x] Financial transaction recording
- [x] Partner withdrawal processing
- [x] Accounting integration
- [x] Daily entry automation
- [x] Partnership history tracking
- [x] Soft delete functionality
- [x] Bulk operations support

### Related Controllers
- [partnerTransferBetweenController.php](partnerTransferBetweenController.md) - Inter-partner transfers
- [partnerwithdrawalController.php](#) - Partner withdrawals
- [dailyentry.php](dailyentry.md) - Accounting entries
- [saveController.php](saveController.md) - Cash management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **partner** | Partner master data | partnerid, partnername, partnermoney, partnerpercentage, treeId, conditions, userid, partnerdate |
| **partnerwithdrawal** | Partner financial transactions | partnerwithdrawalid, partnerid, partnerwithdrawalvalue, partenrwithdrawaltype, partnerafter, dailyentryid |
| **savedaily** | Cash flow tracking | savedailyid, saveid, savedailysavebefore, savedailychangeamount, savedailychangetype, savedailysaveafter |

### Financial Tables (Referenced)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Cash registers/safes | saveid, savename, savecurrentvalue, treeId |
| **dailyentry** | Accounting journal entries | dailyentryid, entryComment, totalcreditor, totalDebtor |
| **dailyentrycreditor** | Credit entries | dailyentrycreditorid, dailyentryid, accountstreeid, value |
| **dailyentrydebtor** | Debit entries | dailyentrydebtoryid, dailyentryid, accountstreeid, value |
| **accountstree** | Chart of accounts | accountstreeid, accountname, parentid, accountlevel, accounttype |

### System Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | System users | userid, username, employeename |
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **add() / Partner Registration** - Core Registration Logic
**Location**: Line 271  
**Purpose**: Register new business partner with initial investment and accounting integration

**Function Signature**:
```php
function add()
// Triggered when: do=add
$partnerName = $_POST['partnername'];
$partnerMoney = $_POST['partnermoney'];
$partnerPercentage = $_POST['partnerpercentage'];
```

**Process Flow**:
1. Initialize transaction for data integrity
2. Create accounting tree element for partner
3. Insert partner master record
4. Create initial withdrawal/deposit record
5. Update cash register (save) balance
6. Generate daily accounting entry
7. Link withdrawal to accounting entry
8. Commit transaction

**Accounting Integration**:
```php
// Create partner account in chart of accounts
$treeId = addTreeElement($partnerName, 128, 4, 0, 1, '', 0, 0);

// Generate daily entry for partner investment
$did = addPartnerDailyEntry($partnerName, $partnerMoney, $idTreeSave, $treeId);
```

**Error Handling**:
- Database transaction rollback on failure
- Automatic tree element cleanup
- Cash register balance restoration

---

### 2. **show() / Partner List Display** - Partner Overview
**Location**: Line 374  
**Purpose**: Display all partners with calculated financial summaries

**Function Signature**:
```php
function show()
// Returns: Array of partner objects with financial totals
```

**Process Flow**:
1. Load all partner records
2. For each partner:
   - Query all withdrawal transactions
   - Calculate total deposits (type=0)
   - Calculate total withdrawals (type=1)
   - Compute net balance
3. Assign calculated totals to partner objects

**Financial Calculations**:
```php
foreach ($partnerwithdrawalData as $mypartnerwithdrawalData) {
    if ($mypartnerwithdrawalData->partenrwithdrawaltype == 0) {
        $totalone += $mypartnerwithdrawalData->partnerwithdrawalvalue; // Deposits
    } else {
        $totaltwo += $mypartnerwithdrawalData->partnerwithdrawalvalue; // Withdrawals
    }
}
$partner->totalall = $totalone - $totaltwo; // Net balance
```

---

### 3. **edit() / Partner Edit Form** - Load Edit Data
**Location**: Line 511  
**Purpose**: Load partner data for editing form

**Function Signature**:
```php
function edit()
// Returns: Partner object for form population
```

**URL Parameter**: `partnerid` - Partner ID to edit

---

### 4. **update() / Partner Update Logic** - Complex Update Process
**Location**: Line 525  
**Purpose**: Update partner information with financial reconciliation

**Function Signature**:
```php
function update()
// Processes: partnername, partnermoney, partnerpercentage, conditions
```

**Process Flow**:
1. **Phase 1 - Remove Old Balance**:
   - Load existing partner data
   - Reverse cash register impact
   - Mark old withdrawal records as deleted
   - Reverse all daily entries
   - Commit intermediate transaction

2. **Phase 2 - Apply New Balance**:
   - Update cash register with new amount
   - Create new withdrawal record
   - Generate new daily entry
   - Update partner master record
   - Link new records together

**Critical Feature - Two-Phase Update**:
```php
// Phase 1: Remove old impact
$dataSave->savecurrentvalue -= $myPartner->partnermoney;
$myPartnerwithdrawalEx->updateConditionsOnlyByPartner(1, $partnerId);

// Phase 2: Apply new values
$dataSave->savecurrentvalue += $partnerMoney;
$did = addPartnerDailyEntry($myPartner->partnername, $partnerMoney, $idTreeSave, $myPartner->treeId);
```

---

### 5. **tempdelete() / Soft Delete** - Temporary Deletion
**Location**: Line 400  
**Purpose**: Mark partner as deleted without removing data

**Function Signature**:
```php
function tempdelete($partnerId)
// Sets conditions=1 (soft delete)
```

**Features**:
- Preserves all financial data
- Maintains audit trail
- Reversible operation
- Updates status only

---

### 6. **returndelete() / Restore Partner** - Undelete Operation
**Location**: Line 431  
**Purpose**: Restore previously deleted partner

**Function Signature**:
```php
function returndelete($partnerId)
// Sets conditions=0 (active)
```

**Process Flow**:
1. Validate partner exists and is deleted
2. Set conditions to active (0)
3. Restore partner visibility
4. No financial impact (data preserved)

---

### 7. **executeOperation() / Bulk Operations** - Batch Processing
**Location**: Line 639  
**Purpose**: Perform bulk operations on multiple partners

**Function Signature**:
```php
function executeOperation()
// Processes: operation type, selected partner IDs
```

**Supported Operations**:
- Operation 1: Bulk temporary delete
- Operation 2: Bulk restore/undelete

**Features**:
- Progress tracking with error reporting
- Individual operation validation
- Success/failure status for each partner

---

### 8. **addPartnerDailyEntry() / Accounting Integration** - Financial Recording
**Location**: Line 709  
**Purpose**: Generate proper accounting entries for partner transactions

**Function Signature**:
```php
function addPartnerDailyEntry($partnerName, $partnerMoney, $idTreeSave, $treeId)
// Returns: Daily entry ID for linking
```

**Accounting Logic**:
```php
// Debit: Cash/Save account (money coming in)
$dailyEntryDebtor->value = $partnerMoney;
$dailyEntryDebtor->accountstreeid = $idTreeSave;

// Credit: Partner account (liability to partner)
$dailyEntryCreditor->value = $partnerMoney;
$dailyEntryCreditor->accountstreeid = $treeId;
```

---

## 🔄 Workflows

### Workflow 1: New Partner Registration
```
┌─────────────────────────────────────────────────────────────┐
│              START: Partner Registration Form              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Validate Input Data                                     │
│     - Partner name required                                 │
│     - Investment amount validation                          │
│     - Profit percentage (0-100%)                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Initialize Database Transaction                         │
│     - Start transaction for data integrity                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Accounting Infrastructure                        │
│     - Add partner to chart of accounts                     │
│     - Generate unique tree ID                              │
│     - Set account hierarchy (Parent: Partners)             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Register Partner                                        │
│     - Insert partner master record                         │
│     - Set initial status (active)                          │
│     - Link to accounting tree                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Record Initial Investment                               │
│     - Create withdrawal record (type=0, deposit)           │
│     - Update cash register balance                         │
│     - Generate cash flow tracking entry                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Generate Accounting Entries                            │
│     - Debit: Cash account                                  │
│     - Credit: Partner account                              │
│     - Link withdrawal to journal entry                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  7. Finalize Transaction                                    │
│     - Commit all changes                                   │
│     - Update withdrawal with journal ID                    │
│     - Return success status                                │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Partner Update Process
```
┌─────────────────────────────────────────────────────────────┐
│               START: Partner Update Request                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  PHASE 1: Remove Old Financial Impact                      │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  1. Load Current Partner Data                       │   │
│  │     - Get existing investment amount                │   │
│  │     - Load associated transactions                  │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  2. Reverse Cash Register Impact                    │   │
│  │     - Subtract old investment amount                │   │
│  │     - Create reversal cash flow entry              │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  3. Mark Historical Records as Deleted             │   │
│  │     - Set withdrawal records conditions=1          │   │
│  │     - Reverse all daily entries                    │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  4. Commit Phase 1 Changes                         │   │
│  └─────────────────────────────────────────────────────┘   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  PHASE 2: Apply New Financial Impact                       │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  1. Update Cash Register                            │   │
│  │     - Add new investment amount                     │   │
│  │     - Create new cash flow entry                   │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  2. Create New Transaction Records                  │   │
│  │     - New withdrawal record                        │   │
│  │     - Handle positive/negative amounts             │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  3. Update Partner Master Record                   │   │
│  │     - New name, money, percentage                  │   │
│  │     - Maintain accounting tree link                │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  4. Generate New Accounting Entries                │   │
│  │     - Create daily entry                           │   │
│  │     - Link to withdrawal record                    │   │
│  └─────────────────────────────────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  5. Finalize Update                                │   │
│  │     - Commit phase 2 changes                       │   │
│  │     - Return success status                        │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default display | Partner registration form |
| `do=add` | `add()` | Process new partner registration |
| `do=show` | `show()` | Display all partners with totals |
| `do=edit` | `edit()` | Load partner edit form |
| `do=update` | `update()` | Process partner updates |
| `do=tempdelete` | `tempdelete()` | Soft delete partner |
| `do=returndelete` | `returndelete()` | Restore deleted partner |
| `do=executeOperation` | `executeOperation()` | Bulk operations |

### Required Parameters by Action

**Registration** (`do=add`):
- `partnername` - Partner full name
- `partnermoney` - Initial investment amount
- `partnerpercentage` - Profit sharing percentage (0-100)
- `comment` - Optional registration notes

**Edit/Update** (`do=edit`, `do=update`):
- `partnerid` - Partner ID to modify
- All registration fields for updates

**Delete Operations**:
- `partnerid` - Partner ID to delete/restore
- `action` - Daily entry ID for linking

**Bulk Operations** (`do=executeOperation`):
- `operation` - Operation type (1=delete, 2=restore)
- `choosedItem[]` - Array of partner IDs

---

## 🧮 Calculation Methods

### Partner Financial Summary
```php
// Calculate total deposits and withdrawals
foreach ($partnerwithdrawalData as $transaction) {
    if ($transaction->partenrwithdrawaltype == 0) {
        $totalone += $transaction->partnerwithdrawalvalue; // Deposits
    } else {
        $totaltwo += $transaction->partnerwithdrawalvalue; // Withdrawals
    }
}
$partner->totalall = $totalone - $totaltwo; // Net partner balance
```

### Cash Register Impact
```php
// Adding partner investment
$dataSave->savecurrentvalue += $partnerMoney;

// Removing partner investment (update scenario)
$dataSave->savecurrentvalue -= $oldPartnerMoney;
```

### Accounting Entry Generation
```php
// Standard partner investment entry
$dailyEntryDebtor->value = $partnerMoney;        // Cash account (debit)
$dailyEntryCreditor->value = $partnerMoney;      // Partner account (credit)
```

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
// Required for all operations except success/error pages
```

### Input Sanitization
- All POST data filtered through framework
- Numeric values cast to appropriate types
- SQL injection prevention through DAO layer
- XSS protection in templates

### Transaction Integrity
```php
$mytransactions = new Transaction();
try {
    // Multiple database operations
    $mytransactions->commit();
} catch (Exception $ex) {
    $mytransactions->rollback();
}
```

### Data Access Control
- User ID tracking for all operations
- Session-based save account restrictions
- Soft delete preserves audit trail

---

## 📊 Performance Considerations

### Database Optimization
1. **Required Indexes**:
   - `partner(userid, conditions)` - For user filtering
   - `partnerwithdrawal(partnerid, conditions)` - For transaction queries
   - `savedaily(saveid, savedailydate)` - For cash flow tracking

2. **Query Optimization**:
   - Use of conditions field for soft delete filtering
   - Efficient withdrawal aggregation queries
   - Transaction batching for updates

3. **Memory Management**:
   - Large partner lists may need pagination
   - Transaction history can grow large over time

### Known Performance Issues
```sql
-- This query can be slow for partners with many transactions
SELECT * FROM partnerwithdrawal 
WHERE partnerid = ? AND conditions = 0;

-- Solution: Add composite index
CREATE INDEX idx_partner_transactions ON partnerwithdrawal(partnerid, conditions);
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Transaction Rollback Errors**
**Issue**: Partner registration fails but partial data remains  
**Cause**: Exception after tree element creation

**Debug**:
```php
// Check for orphaned tree elements
SELECT * FROM accountstree 
WHERE accountname LIKE 'Partner%' 
AND accountstreeid NOT IN (SELECT treeId FROM partner);
```

### 2. **Cash Register Sync Issues**
**Issue**: Save balance doesn't match partner totals  
**Cause**: Failed update transactions

**Fix**:
```sql
-- Verify cash register balance
SELECT savecurrentvalue FROM save WHERE saveid = [SAVE_ID];

-- Check total partner investments
SELECT SUM(partnermoney) FROM partner WHERE conditions = 0;
```

### 3. **Accounting Entry Mismatches**
**Issue**: Daily entries don't balance  
**Cause**: Incomplete entry generation

**Debug**:
```sql
-- Find unbalanced entries
SELECT dailyentryid, totalcreditor, totalDebtor 
FROM dailyentry 
WHERE totalcreditor != totalDebtor;
```

### 4. **Update Process Failures**
**Issue**: Partner update partially completes  
**Cause**: Two-phase update interruption

**Fix**:
```php
// Check for partners with inconsistent states
SELECT * FROM partner p
LEFT JOIN partnerwithdrawal pw ON p.partnerid = pw.partnerid 
WHERE pw.partnerid IS NULL OR pw.conditions = 1;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Partner Registration
```
1. Access registration form (empty do)
2. Enter partner details with valid investment amount
3. Submit form (do=add)
4. Verify partner appears in list (do=show)
5. Check cash register balance increased
6. Confirm accounting entries created
```

### Test Case 2: Partner Update Process
```
1. Select existing partner for edit
2. Modify investment amount significantly
3. Submit update
4. Verify cash register balance adjusted correctly
5. Confirm new withdrawal records created
6. Check old records marked as deleted
```

### Test Case 3: Soft Delete and Restore
```
1. Delete active partner (tempdelete)
2. Verify partner hidden from main list
3. Confirm financial data preserved
4. Restore partner (returndelete)
5. Verify partner visible again
```

### Test Case 4: Bulk Operations
```
1. Select multiple partners
2. Choose bulk delete operation
3. Verify all selected partners marked as deleted
4. Test bulk restore operation
5. Confirm selective operation success/failure reporting
```

### Debug Mode Enable
```php
// Add transaction logging
error_log("Partner transaction started: " . $partnerId);
error_log("Save balance before: " . $saveValuebefore);
error_log("Save balance after: " . $saveValueafter);
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [partnerTransferBetweenController.md](partnerTransferBetweenController.md) - Inter-partner transfers
- [partnerwithdrawalController.php](#) - Partner withdrawal management
- [dailyentry.md](dailyentry.md) - Accounting entry system
- [saveController.md](saveController.md) - Cash register management

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major business logic changes occur