# Notice Functions Documentation

**File**: `/controllers/noticefunctions.php`  
**Purpose**: Utility functions for calculating business notifications and alerts across the system  
**Last Updated**: December 20, 2024  
**Total Functions**: 20+  
**Lines of Code**: ~693

---

## 📋 Overview

The Notice Functions file provides centralized utility functions for calculating various business notifications used throughout the ERP system. These functions analyze data patterns, track business metrics, and generate alerts for critical business conditions requiring attention.

### Primary Functions
- [x] Notification count calculations
- [x] Product sales analysis and inventory monitoring
- [x] Customer and supplier check tracking
- [x] Workshop order delay calculations
- [x] Insurance bill status monitoring  
- [x] Premium payment reminders
- [x] Product request management
- [x] Category hierarchy navigation

---

## 🗄️ Database Tables

### Core Data Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **product** | Product master | productid, productName, productCatId |
| **storedetail** | Inventory levels | productid, storedetailquantity |
| **sellbilldetail** | Sales history | sellbilldetailproductid, sellbilldetaildate |
| **datedchecked** | Check management | datedcheckedid, checkvalue, done, addtype |
| **kempiala** | Promissory notes | kempialaid, kempialadate |
| **productrequest** | Product requests | productrequestid, status, seen, storeid |
| **otherrequest** | General requests | otherrequestid, requestto, requesttoid |

---

## 🔑 Key Functions

### 1. **calcNotice()** - Main Notification Calculator
**Location**: Lines 107-173  
**Purpose**: Calculate total notification count based on user group permissions

**Function Signature**:
```php
function calcNotice()
```

**Process Flow**:
1. Load user group permissions
2. Calculate counts for each notification type:
   - Product inventory alerts
   - Non-selling products  
   - Promissory notes due
   - Client checks due
   - Supplier checks due
3. Apply user group filters to determine visible notifications
4. Return total notification count

**User Group Permission Logic**:
```php
if ($Usergroup->productno == 0) {
    $sum += $productcount; // Include product notifications
}
if ($Usergroup->kempilano == 0) {
    $sum += $allkempilacount; // Include promissory note notifications
}
// ... additional permission checks
```

---

### 2. **getProductRequestNotice()** - Product Request Alerts
**Location**: Lines 175-216  
**Purpose**: Calculate product request notification counts based on user role

**Process Flow**:
1. **Admin Users** (`storeId == 0`): See all requests across stores
   - New requests: `status = 0`
   - Accepted requests: `status in (2, 3)`  
   - Refused requests: `status = 1`
2. **Store Users**: See requests relevant to their store
   - Incoming requests: Other stores requesting from them
   - Response notifications: Status updates on their requests

---

### 3. **getOtherRequestsNotice()** - General Request Notifications
**Location**: Lines 298-373  
**Purpose**: Calculate general business request notifications

**Request Target Types**:
- **Branch Requests** (`requestTo = 0`): Requests to specific branches
- **User Group Requests** (`requestTo = 1`): Requests to user groups
- **Individual User Requests** (`requestTo = 2`): Personal requests

---

### 4. **getToWorkshopOrderNotice()** - Workshop Delay Alerts
**Location**: Lines 375-425  
**Purpose**: Calculate workshop order delay notifications

**Delay Categories**:
1. **Delivery Delays**: Orders not delivered to workshop on time
2. **Workshop Processing Delays**: Orders exceeding workshop timeout  
3. **Return Delays**: Completed orders not returned to branch

**Permission Logic**:
```php
if ($_SESSION['userid'] == 1) {
    $showOnlyToQyeryString = ""; // Admin sees all
} else {
    $showOnlyToQyeryString = " and ( branchId = " . $_SESSION['branchId'] . 
                           " or driverId = " . $_SESSION['userid'] . 
                           " or driverIdBack = " . $_SESSION['userid'] . " ) ";
}
```

---

### 5. **showallproductx2()** - Low Stock Product Analysis
**Location**: Lines 549-568  
**Purpose**: Identify products requiring restocking attention

**Features**:
- Product category path generation
- Hierarchical category display
- Stock level analysis

---

### 6. **productnotsell()** - Non-Selling Product Detection
**Location**: Lines 585-613  
**Purpose**: Identify products with no sales in past 7 days

**Date Logic**:
```php
$today = date("Y-m-d");
$todayfor7days = date("Y-m-d", strtotime($today . ' - 7 day'));
$allsell = $SellbilldetailEX->queryproductnotsell($todayfor7days, $today);
```

---

### 7. **checkforclient() / checkforsupplier()** - Check Due Monitoring
**Location**: Lines 615-639  
**Purpose**: Monitor checks becoming due within 7 days

---

### 8. **dateTimeDiff2()** - Workshop Time Calculation
**Location**: Lines 664-671  
**Purpose**: Calculate time differences for workshop delay detection

---

### 9. **getInsuranceBillNotifNotice()** - Insurance Alert Counter
**Location**: Lines 673-681  
**Purpose**: Count insurance bills requiring attention

---

### 10. **getPremiumToday()** - Daily Premium Alerts  
**Location**: Lines 683-692  
**Purpose**: Count premium payments due today for current user

---

## 🔄 Workflows

### Notification Calculation Workflow
```
┌─────────────────────────────────────────────────────────────┐
│         START: Calculate Total Notifications               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load User Permissions                                   │
│     ├─→ Get user group from session                        │
│     ├─→ Load permission settings                           │
│     └─→ Determine which notifications user can see         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Calculate Individual Notification Counts              │
│     ├─→ showallproductx2() - Low stock products           │
│     ├─→ productnotsell() - Non-selling products           │
│     ├─→ showallkempila() - Due promissory notes           │
│     ├─→ checkforclient() - Client checks due              │
│     ├─→ checkforsupplier() - Supplier checks due          │
│     ├─→ getProductRequestNotice() - Product requests      │
│     ├─→ getOtherRequestsNotice() - General requests       │
│     ├─→ getToWorkshopOrderNotice() - Workshop delays      │
│     ├─→ getInsuranceBillNotifNotice() - Insurance bills   │
│     └─→ getPremiumToday() - Premium payments due          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Apply Permission Filters                               │
│     ├─→ Check user group permission for each type         │
│     ├─→ Include/exclude counts based on permissions       │
│     └─→ Sum only allowed notification types               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Return Total Badge Count                               │
│     └─→ Display notification badge in system header       │
└─────────────────────────────────────────────────────────────┘
```

---

## 🧮 Calculation Methods

### Time Difference Calculation
```php
function dateTimeDiff2($dateTime1, $dateTime2) {
    $dateTime1 = new DateTime($dateTime1);
    $dateTime2 = new DateTime($dateTime2);
    $diff = $dateTime2->diff($dateTime1);
    $hours = $diff->h + ($diff->days * 24);
    return $hours;
}
```

### Product Path Generation
```php
function getProductPath_recursive1($parentid, $categories, $level) {
    global $productCatExt;
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);
    
    if (count($catData) > 0 && $level < 2) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;
        return getProductPath_recursive1($newParentId, $categories, ($level + 1));
    }
    return substr($categories, 0, strlen($categories) - 1);
}
```

---

## 🔒 Security & Performance

### Role-Based Access Control
```php
// Store-level filtering for non-admin users
if ($storeId == 0 || empty($storeId)) {
    // Admin user - see all requests
    $newRequests = $productRequestExt->getRequestsWithString('and p.status = 0', ' and p.seen = 0', 0);
} else {
    // Store user - see only relevant requests
    $string2 = 'and p.status = 0 and p.storeid = ' . $storeId . ' ';
    $otherNewRequests = $productRequestExt->getRequestsWithString($string2, ' and p.seen = 0', 0);
}
```

### Performance Considerations
- **Multiple Database Queries**: Each notification type requires separate queries
- **Date Range Calculations**: 7-day lookbacks on transaction tables
- **Recursive Functions**: Category hierarchy traversal
- **Permission Checks**: Filter results based on user access levels

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide  
- [noticesController.md](noticesController.md) - Main notices controller
- [productController.md](productController.md) - Product management

---

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