# BARMM Workflow Integration System - Technical Documentation

## Project Overview

**Project Name:** BARMM Workflow Integration System  
**Version:** 1.1  
**Framework:** Laravel 9.x  
**PHP Version:** ^8.0.2  
**Project Type:** Workflow Management System for Government Services

### Description

The BARMM Workflow Integration System is a comprehensive government workflow engine designed to manage and track service applications across multiple government offices and departments in the Bangsamoro Autonomous Region in Muslim Mindanao (BARMM). The system facilitates application processing, decision tracking, payment management, document handling, and inter-departmental forwarding of applications.

---

## Table of Contents

1. [System Architecture](#system-architecture)
2. [Key Features](#key-features)
3. [Installation & Setup](#installation--setup)
4. [Database Schema](#database-schema)
5. [Application Structure](#application-structure)
6. [Core Components](#core-components)
7. [API Integration](#api-integration)
8. [Workflow Process](#workflow-process)
9. [User Roles & Permissions](#user-roles--permissions)
10. [Security Features](#security-features)
11. [Development Guidelines](#development-guidelines)

---

## System Architecture

### Technology Stack

#### Backend

- **Framework:** Laravel 9.19+
- **PHP:** ^8.0.2
- **Database:** MySQL/MariaDB
- **Session Management:** Database/File-based sessions
- **Authentication:** Laravel Sanctum, SSO Integration

#### Frontend

- **CSS Framework:** Tailwind CSS
- **JavaScript:** Native JavaScript with Vite bundler
- **DataTables:** Yajra DataTables for data presentation
- **Charts:** ECharts for dashboard analytics

#### Key Dependencies

```json
{
  "guzzlehttp/guzzle": "^7.2",
  "larabug/larabug": "^3.0",
  "laravel/sanctum": "^3.0",
  "maatwebsite/excel": "^3.1",
  "pusher/pusher-php-server": "^7.2",
  "yajra/laravel-datatables-oracle": "10.0"
}
```

### System Architecture Overview

```
┌─────────────────────────────────────────────────────────┐
│                    Client Layer                          │
│  (Citizens, Government Employees, Service Providers)     │
└─────────────────────┬───────────────────────────────────┘
                      │
                      │ HTTPS/SSO
                      │
┌─────────────────────▼───────────────────────────────────┐
│              Application Layer (Laravel)                 │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐        │
│  │Controllers │  │ Middleware │  │  Routes    │        │
│  └─────┬──────┘  └─────┬──────┘  └─────┬──────┘        │
│        │               │               │                 │
│  ┌─────▼───────────────▼───────────────▼──────┐        │
│  │         Business Logic Layer                │        │
│  │  (Application, Dashboard, ServiceModelApi)  │        │
│  └─────────────────┬───────────────────────────┘        │
└────────────────────┼─────────────────────────────────────┘
                     │
┌────────────────────▼─────────────────────────────────────┐
│                  Data Layer                               │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │  WfRequest   │  │WfRequestData │  │WfRequestNote │  │
│  │  (Applications)│  │  (Decisions) │  │    (Logs)    │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└──────────────────────────────────────────────────────────┘
                     │
┌────────────────────▼─────────────────────────────────────┐
│            External Integration Layer                     │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │Service Model │  │Payment Gateway│ │Pusher Events │  │
│  │     API      │  │               │  │              │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└──────────────────────────────────────────────────────────┘
```

---

## Key Features

### 1. Application Management

- **Multi-desk Workflow:** Applications flow through multiple government desks/departments
- **Status Tracking:** Real-time status updates (New, In Progress, Completed, Rejected, Cancelled)
- **Application Types:** Support for 50+ government services
- **Bulk Operations:** Bulk decision-making for multiple applications

### 2. Decision Management

- **Hierarchical Decisions:** Multi-step decision workflows per service
- **Decision Routing:** Automatic forwarding based on decision outcomes
- **Decision History:** Complete audit trail of all decisions
- **Approval Data:** Capture and store approval-specific data (certificates, permits, etc.)

### 3. Payment Integration

- **Payment Requests:** Automated payment request generation
- **Payment Tracking:** Track receivable and received payments
- **Re-payment Support:** Handle payment re-submission scenarios
- **Multiple Payment Types:** Support for various payment categories

### 4. Document Management

- **Document Requests:** Request additional documents from citizens
- **Document Uploads:** Support for PDF and image uploads
- **Draft Printing:** Generate draft documents for review
- **Certificate Generation:** Automated certificate creation

### 5. Dashboard & Analytics

- **Summary Statistics:** Real-time application counts by status
- **Rating System:** 5-star rating system for service feedback
- **Payment Analytics:** Financial summaries and reports
- **Service Performance:** Service-wise performance metrics

### 6. Geographic Hierarchy

- **Multi-level Geography:** Ministry → Region → Province → Municipality → Barangay
- **Office Management:** Track applications by office layers
- **Designation-based Access:** Role-based access per designation

### 7. Export & Reporting

- **Excel Export:** Export application master lists
- **Filtered Reports:** Generate reports with date range and status filters
- **Service-specific Reports:** PWD assessments, Business Permits, etc.

---

## Installation & Setup

### Prerequisites

```bash
- PHP >= 8.0.2
- Composer >= 2.x
- MySQL >= 5.7 or MariaDB >= 10.3
- Node.js >= 16.x & npm >= 8.x
- Apache/Nginx web server
```

### Installation Steps

1. **Clone the Repository**

```bash
git clone https://github.com/orange-bd/barmm-workflow-int.git
cd barmm-workflow-int
```

2. **Install PHP Dependencies**

```bash
composer install
```

3. **Install Node Dependencies**

```bash
npm install
```

4. **Environment Configuration**

```bash
cp .env.example .env
php artisan key:generate
```

5. **Configure Environment Variables**

```env
APP_NAME="Workflow Engine"
APP_ENV=production
APP_KEY=base64:... # Generated by artisan key:generate
APP_URL=https://your-domain.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=barmm_workflow
DB_USERNAME=your_username
DB_PASSWORD=your_password

SERVICE_MODEL_DOMAIN=https://service-model-api.com
SERVICE_MODEL_API_KEY=your_api_key

PUSHER_APP_ID=your_pusher_id
PUSHER_APP_KEY=your_pusher_key
PUSHER_APP_SECRET=your_pusher_secret
PUSHER_APP_CLUSTER=ap1
```

6. **Database Migration**

```bash
php artisan migrate
```

7. **Build Frontend Assets**

```bash
npm run build
# For development
npm run dev
```

8. **Set Permissions**

```bash
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
```

9. **Configure Web Server**

- Point document root to `/public` directory
- Enable `.htaccess` for Apache or configure nginx

10. **Start Application**

```bash
php artisan serve # Development only
# For production, configure Apache/Nginx
```

---

## Database Schema

### Core Tables

#### 1. `wf_requests` (Main Application Table)

Primary table storing all workflow applications.

```sql
Fields:
- id: VARCHAR (UUID) - Primary Key
- title: VARCHAR - Service name
- client: VARCHAR - Client name
- ministry: BIGINT - Ministry ID
- region: BIGINT - Region ID
- province: BIGINT - Province ID
- municipality: BIGINT - Municipality ID
- barangay: BIGINT - Barangay ID
- stack_holder_id: BIGINT - Current office holding the application
- stack_holder_dep_id: BIGINT - Current office layer/department
- current_state_id: BIGINT - Current desk/designation ID
- client_app_id: INT - Service ID from service model
- client_app_tracking_id: VARCHAR - Unique tracking number
- client_app_status: VARCHAR - Current status code (e.g., "1-1")
- client_app_status_details: VARCHAR - Status description
- client_user_name: VARCHAR - Applicant name
- client_user_mobile: VARCHAR - Applicant mobile
- client_user_email: VARCHAR - Applicant email
- client_app_date: DATE - Application date
- client_app_exp_date: DATE - Expected delivery date
- callback_url: TEXT - Callback URL for external system
- api_key: VARCHAR - Unique API key
- status: TINYINT - Internal status (1=Running, 2=Resolved, 3=Resolved Open)
- rating_points: DECIMAL - User rating (1-5)
- comments: TEXT - User feedback
- is_anonymouse: BOOLEAN - Anonymous feedback flag
- rating_date: DATETIME - Rating timestamp
- is_read: BOOLEAN - Read/unread flag
- action_by_state_id: BIGINT - Last action taker designation
- certificate_data_infos: JSON - Certificate data
- wf_assesment: JSON - Assessment data (for PWD services)
- current_desk_decision_id: BIGINT - Current decision desk ID
- version: INT - Application version
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
```

#### 2. `wf_request_data` (Decision Data Table)

Stores decision workflows and desk lists for each application.

```sql
Fields:
- id: VARCHAR (UUID) - Primary Key
- request_id: VARCHAR - Foreign key to wf_requests
- data: LONGTEXT (JSON) - Decision list structure
- data_type: VARCHAR - Type (e.g., "Decision")
- desk_list: JSON - Available desk list for forwarding
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
```

#### 3. `wf_request_note_logs` (Action Logs Table)

Complete audit trail of all actions on applications.

```sql
Fields:
- id: VARCHAR (UUID) - Primary Key
- request_id: VARCHAR - Foreign key to wf_requests
- client: VARCHAR - Client identifier
- stack_holder_id: BIGINT - Office ID
- stack_holder_dep_id: BIGINT - Office layer ID
- current_state_id: BIGINT - Designation ID
- ministry: BIGINT
- region: BIGINT
- province: BIGINT
- municipality: BIGINT
- barangay: BIGINT
- client_app_status: VARCHAR - Status at time of action
- client_app_status_details: VARCHAR - Status description
- action_type: ENUM('Decision', 'Forward') - Action type
- note: TEXT - Internal note
- cnote: TEXT - Citizen-facing note
- file: VARCHAR - Attached file path
- version: INT - Version number
- user_info: JSON - User who performed action
- attachment: VARCHAR - Attachment path
- decision_reason: TEXT - Reason for decision
- approval_data: JSON - Approval data captured
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
```

#### 4. `wf_request_meta_data` (Metadata Table)

Stores additional metadata like payment info, document requests, approval data.

```sql
Fields:
- id: VARCHAR (UUID) - Primary Key
- request_id: VARCHAR - Foreign key to wf_requests
- data: LONGTEXT (JSON) - Metadata content
- type: VARCHAR - Metadata type (e.g., 'approval_data', 'Payment', 'Document')
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
```

#### 5. `users` (Employee Users)

```sql
Fields:
- id: BIGINT - Primary Key
- name: VARCHAR
- email: VARCHAR UNIQUE
- password: VARCHAR
- remember_token: VARCHAR
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
```

#### 6. `logs` (System Logs)

```sql
Fields:
- id: BIGINT - Primary Key
- user_id: VARCHAR
- activity: TEXT - Activity description
- ip: VARCHAR - IP address
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
```

### Database Relationships

```
wf_requests (1) ──────────> (Many) wf_request_data
      │
      │
      ├────────────> (Many) wf_request_note_logs
      │
      └────────────> (Many) wf_request_meta_data
```

---

## Application Structure

### Directory Structure

```
barmm-workflow-int/
├── app/
│   ├── Classes/                  # Business Logic Classes
│   │   ├── Application.php       # Core application logic
│   │   ├── Dashboard.php         # Dashboard analytics logic
│   │   ├── ServiceModelApi.php   # External API integration
│   │   ├── UserInfo.php          # User information handling
│   │   └── DecisionDeskUpdate.php
│   ├── Console/
│   │   └── Kernel.php            # Scheduled tasks
│   ├── Exceptions/
│   │   └── Handler.php           # Exception handling
│   ├── Exports/
│   │   └── ApplicationExport.php # Excel export logic
│   ├── Http/
│   │   ├── Controllers/          # Request handlers
│   │   │   ├── ApplicationController.php
│   │   │   ├── DashboardController.php
│   │   │   ├── WfRequestController.php
│   │   │   ├── WfRequestDataController.php
│   │   │   ├── UserManagementController.php
│   │   │   └── DownloadController.php
│   │   ├── Middleware/           # HTTP middleware
│   │   │   └── XSS.php           # XSS protection
│   │   └── Resources/            # API resources
│   ├── Listeners/
│   │   └── LoginListener.php     # Login event listener
│   ├── Models/                   # Eloquent models
│   │   ├── WfRequest.php
│   │   ├── WfRequestData.php
│   │   ├── WfRequestMetaData.php
│   │   ├── WfRequestNoteLog.php
│   │   ├── User.php
│   │   └── Log.php
│   ├── Providers/                # Service providers
│   │   ├── AppServiceProvider.php
│   │   ├── AuthServiceProvider.php
│   │   ├── EventServiceProvider.php
│   │   └── RouteServiceProvider.php
│   └── Utility/                  # Helper utilities
│       ├── Helper.php            # General helpers
│       └── Status.php            # Status constants
├── bootstrap/
│   └── app.php                   # Application bootstrap
├── config/                       # Configuration files
│   ├── app.php
│   ├── database.php
│   ├── services.php
│   └── ...
├── database/
│   ├── migrations/               # Database migrations
│   ├── seeders/                  # Database seeders
│   └── factories/                # Model factories
├── public/                       # Public web root
│   ├── index.php                 # Entry point
│   ├── css/
│   ├── js/
│   └── images/
├── resources/
│   ├── css/                      # CSS source files
│   ├── js/                       # JavaScript source files
│   ├── views/                    # Blade templates
│   └── lang/                     # Language files
├── routes/
│   ├── web.php                   # Web routes
│   ├── api.php                   # API routes
│   └── console.php               # Console commands
├── storage/
│   ├── app/                      # Application storage
│   ├── framework/                # Framework cache
│   └── logs/                     # Log files
├── tests/                        # Test suites
├── composer.json                 # PHP dependencies
├── package.json                  # Node dependencies
├── vite.config.js               # Vite configuration
└── .env                         # Environment variables
```

---

## Core Components

### 1. Application Class (`app/Classes/Application.php`)

The Application class is the core business logic handler for all workflow operations.

#### Key Methods

**deskWiseApplicationSummary()**

```php
/**
 * Generate summary statistics for current desk
 * Returns: Array with counts of total, new, completed, overdue, rejected applications
 */
public static function deskWiseApplicationSummary()
```

**deskWiseApplicationList($request)**

```php
/**
 * Retrieve paginated application list for DataTables
 * Parameters: $request (filters: type, date range, service, status)
 * Returns: DataTables JSON response
 */
public static function deskWiseApplicationList($request)
```

**insertApplication($applicationData)**

```php
/**
 * Insert new application and initialize decision workflow
 * Parameters: $applicationData (array of application fields)
 */
public static function insertApplication($applicationData)
```

**insertApplicationNoteLog($request, $actionType)**

```php
/**
 * Process and log application decisions/forwards
 * Handles: Decision making, desk forwarding, payment/document requests
 * Parameters: $request (form data), $actionType ('Decision' or 'Forward')
 * Returns: Array with decision log, notification response, pusher data
 */
public static function insertApplicationNoteLog($request, $actionType)
```

**getVisitedDeskList($requestId)**

```php
/**
 * Retrieve list of all desks that processed this application
 * Returns: Collection of desk information with user details
 */
public static function getVisitedDeskList($requestId)
```

### 2. Dashboard Class (`app/Classes/Dashboard.php`)

Handles dashboard analytics and reporting.

#### Key Methods

**deskWiseApplicationSummary($request)**

```php
/**
 * Generate dashboard summary with optional filters
 * Supports: Date range, service type, status filters
 * Returns: Array with application statistics
 */
public static function deskWiseApplicationSummary($request)
```

**ratingSummaryList($request)**

```php
/**
 * Generate service-wise rating summaries
 * Returns: HTML formatted rating list with star ratings
 */
public static function ratingSummaryList($request)
```

**serviceRating($request)**

```php
/**
 * Generate rating distribution chart data
 * Returns: Chart data with Very Good, Good, Average, Bad, Very Bad counts
 */
public static function serviceRating($request)
```

**peymentSummary($request)**

```php
/**
 * Generate payment summary with receivable/received amounts
 * Returns: HTML table with payment details per service
 */
public static function peymentSummary($request)
```

### 3. ServiceModelApi Class (`app/Classes/ServiceModelApi.php`)

Handles all external API integrations with the Service Model system.

#### Key Methods

**apiLogin($userId, $password)**

```php
/**
 * Authenticate employee via SSO
 * Returns: JSON with employee data and service desk assignments
 */
public static function apiLogin($userId, $password)
```

**getDecisionList($serviceId, $officeLayerId, $officeId)**

```php
/**
 * Fetch decision workflow for specific service and office
 * Returns: Decision tree structure with available decisions per desk
 */
public static function getDecisionList($serviceId, $officeLayerId, $officeId)
```

**notifyApplicationDecision($apiKey, $stepId, $decisionId, ...)**

```php
/**
 * Notify external system of decision made
 * Parameters: Various decision and approval data
 * Returns: API response
 */
public static function notifyApplicationDecision(...)
```

**sendPaymentRequest($apiKey, $amount, $paymentType, ...)**

```php
/**
 * Send payment request to citizen
 * Returns: Payment request response with transaction details
 */
public static function sendPaymentRequest(...)
```

### 4. Controllers

#### WfRequestController

```php
/**
 * Main controller for application listing and management
 * Routes: GET /wf-request, /wf-request/{id}
 */
public function index(Request $request) // List applications with DataTables
public function exportApplication(Request $request) // Export to Excel
```

#### ApplicationController

```php
/**
 * Handles legacy application operations and decisions
 * Routes: POST /application, /application-send, /bulk-decision-set
 */
public function index() // Show application details
public function send(Request $request) // Process decision
public function bulkDecisionSet(Request $request) // Bulk operations
```

#### DashboardController

```php
/**
 * Dashboard and analytics controller
 * Routes: GET /dashboard, POST /top-data, /rating, /service-rating
 */
public function index() // Dashboard view
public function topbar_data(Request $request) // Summary statistics
public function rating(Request $request) // Rating summaries
public function service_rating(Request $request) // Service ratings
```

#### UserManagementController

```php
/**
 * User authentication and profile management
 * Routes: GET /, POST /employee-login, /change-password
 */
public function ssoLogin() // SSO redirect
public function employeeLogin(Request $request) // Process SSO login
public function changePassword(Request $request) // Change password
public function forgetPassword(Request $request) // Forgot password
```

---

## API Integration

### External Service Model API

The system integrates with an external Service Model API for:

- Employee authentication (SSO)
- Service definitions and workflows
- Decision routing
- Payment processing
- Document management
- Notifications to citizens

### API Endpoints Used

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/api/employee/login` | POST | Employee SSO authentication |
| `/api/employee/logout` | GET | Logout session |
| `/api/employee/info` | GET | Fetch employee details |
| `/api/employee/servicelist-desk` | POST | Get decision workflows |
| `/api/employee/application/application-step-update` | POST | Notify decision update |
| `/api/employee/application/payment-request` | POST | Send payment request |
| `/api/employee/application/document-request` | POST | Request documents |
| `/api/employee/application/forward-desk-update` | POST | Notify desk forward |
| `/api/employee/dashboard/payment-short-workflow` | POST | Payment summaries |

### API Authentication

All API calls use Bearer token authentication:

```php
$headers = [
    'Authorization: Bearer ' . $token,
    'Content-Type: application/json',
];
```

### API Response Handling

Standard response format:

```json
{
    "status": "success|failed",
    "data": { ... },
    "message": "Optional message"
}
```

---

## Workflow Process

### Application Lifecycle

```
1. SUBMISSION (External System)
   ↓
2. RECEIVED (First Desk)
   ├─> Decision: Proceed
   │   ├─> Forward to Next Desk
   │   ├─> Request Payment
   │   ├─> Request Document
   │   └─> Approve/Reject
   │
3. PROCESSING (Multiple Desks)
   ├─> Each desk makes decision
   ├─> Can return to previous desk
   └─> Can send to specific desk
   │
4. RESOLUTION
   ├─> Approved → Certificate Generation
   ├─> Rejected → Citizen Notified
   └─> Returned → Resubmission Required
   │
5. COMPLETION
   └─> Rating & Feedback (Optional)
```

### Decision Flow Example

```
Service: Business Permit Application

Desk 1: Receiving Desk (BPLO Staff)
  Decisions:
    - Receive → Forward to Assessment
    - Reject → Incomplete Documents
    - Return → Request Additional Info

Desk 2: Assessment Desk (Assessor)
  Decisions:
    - Assess → Request Payment
    - Return → Clarification Needed
    
Desk 3: Payment Desk (Cashier)
  Decisions:
    - Payment Received → Forward to Approval
    
Desk 4: Approval Desk (BPLO Head)
  Decisions:
    - Approve → Generate Permit
    - Disapprove → Reject Application
    
Desk 5: Release Desk (Records Officer)
  Decisions:
    - Input Permit Number → Complete
    - Print Certificate
```

### Status Constants

```php
// Application Status (wf_requests.status)
const APPLICATION_DEFAULT_STATUS = 1;      // Running
const RESOLVED_APPLICATION_STATUS = 2;     // Completed
const RESOLVED_OPEN_APPLICATION_STATUS = 3; // Resolved but open for actions

// Action Types
const DECISION_STATUS = "Decision";  // Decision made
const FORWARD_STATUS = "Forward";    // Forwarded to another desk
const COMPLETE_STATUS = "Complete";  // Application completed

// Application Type Filters
const NEW_APPLICATION_STATUS = "new_application";
const COMPLETED_APPLICATION_STATUS = "completed_application";
const OVERDATE_APPLICATION_STATUS = "overdate_application";
const REJECTED_APPLICATION_STATUS = "rejected_application";
const SEND_APPLICATION_STATUS = "sent_application";
```

---

## User Roles & Permissions

### Role Structure

The system uses a designation-based access control where permissions are determined by:

1. **Office Layer ID** - Level in government hierarchy (Ministry, Region, Province, Municipality, Barangay)
2. **Office ID** - Specific office/department
3. **Designation ID** - Position/role within the office

### Access Control Logic

```php
// User session structure
Session::get('user') = [
    'id' => designation_assignment_id,
    'name' => employee_name,
    'office_id' => office_id,
    'office_layer_id' => office_layer_id,
    'designation_id' => designation_id,
    'designation_name' => designation_name,
    'ministry_id' => ministry_id,
    'region_id' => region_id,
    'province_id' => province_id,
    'municipality_id' => municipality_id,
    'barangay_id' => barangay_id,
    'geo_data' => [...] // Multiple designation assignments
];
```

### Permission Checks

Applications are filtered by:

```sql
WHERE stack_holder_id = user.office_id
  AND current_state_id = user.designation_id
  AND stack_holder_dep_id = user.office_layer_id
  AND ministry = user.ministry_id
  AND region = user.region_id
  AND province = user.province_id
  AND municipality = user.municipality_id
```

### Special Designations

```php
// Designations with Excel download permission
const ALLOW_DESINATION_FOR_EXCEL_DOWNLOAD = [35, 36];
const ALLOW_DESINATION_FOR_EXCEL_DOWNLOAD_COMPLETE = [34];

// SDF (Special Development Fund) Desk IDs
const SDF_ENGA_DESK = 49;
const SDF_PLANA_DESK = 51;
const SDF_ENGB_DESK = 50;
const SDF_PLANB_DESK = 52;
```

---

## Security Features

### 1. XSS Protection

- Custom XSS middleware (`app/Http/Middleware/XSS.php`)
- All routes wrapped in XSS protection group
- Input sanitization on form submissions

### 2. Authentication

- SSO (Single Sign-On) integration
- Session-based authentication
- Sanctum API tokens for API routes
- Password encryption (bcrypt)

### 3. Authorization

- Session-based user verification: `session.user` middleware
- Designation-based access control
- Geographic hierarchy permissions

### 4. Data Protection

- CSRF protection on all POST requests
- API key encryption with Laravel Crypt
- Sensitive data stored as JSON in encrypted format
- File upload validation (PDF/Image only, size limits)

### 5. Audit Trail

- Complete action logging in `wf_request_note_logs`
- User information captured on every action
- IP tracking in system logs
- Version control on applications

### 6. Rate Limiting

- API rate limiting via Laravel throttle
- Session timeout configuration
- Concurrent request handling

---

## Development Guidelines

### Coding Standards

#### 1. Naming Conventions

```php
// Classes: PascalCase
class ApplicationController extends Controller {}

// Methods: camelCase
public function deskWiseApplicationList() {}

// Variables: snake_case
$application_data = [];
$user_info = Session::get('user');

// Constants: UPPER_SNAKE_CASE
const APPLICATION_DEFAULT_STATUS = 1;
```

#### 2. Database Conventions

```sql
-- Tables: snake_case, plural
wf_requests
wf_request_note_logs

-- Columns: snake_case
client_app_tracking_id
stack_holder_id

-- Foreign Keys: {table}_id
request_id
user_id
```

#### 3. Route Naming

```php
// Resource routes
Route::resource('wf-request', WfRequestController::class);

// Named routes
Route::get('/dashboard', [DashboardController::class, 'index'])
    ->name('dashboard.index');
```

### Adding a New Service

#### Step 1: Define Service in Service Model API

The service must first be created in the external Service Model system.

#### Step 2: Configure Decision Workflow

Decision workflows are fetched from Service Model API:

```php
$decisionList = ServiceModelApi::getDecisionList(
    $serviceId, 
    $officeLayerId, 
    $officeId
);
```

#### Step 3: Add Status Constants (if needed)

In `app/Utility/Status.php`:

```php
const NEW_SERVICE_ID = 60;
const NEW_SERVICE_DESK_LIST = [60, 61, 62];
```

#### Step 4: Handle Special Service Logic

In `app/Classes/Application.php`:

```php
// In insertApplicationNoteLog method
if (in_array($applcationData->client_app_id, Status::NEW_SERVICE_LIST)) {
    // Special handling logic
}
```

### Adding a New Decision Type

#### Step 1: Define in Service Model API

Decision types are configured externally.

#### Step 2: Handle in Application Logic

In `Application::insertApplicationNoteLog()`:

```php
if ($decisionItemValue->id == Status::DECISION_NEW_TYPE_ID) {
    // Process new decision type
    // Example: Generate special certificate
    $certificateData = $this->generateNewCertificate($request);
    
    // Store metadata
    $applicationOtherData = [
        "id" => uniqid(),
        "request_id" => $request->id,
        "data" => json_encode($certificateData),
        "type" => "new_certificate_type"
    ];
    Application::insertApplicationMetaData($applicationOtherData);
    
    // Notify external system
    ServiceModelApi::notifyNewDecision($apiKey, $certificateData);
}
```

### Database Migration Example

```php
// Create new migration
php artisan make:migration add_new_field_to_wf_requests_table

// In migration file
public function up()
{
    Schema::table('wf_requests', function (Blueprint $table) {
        $table->string('new_field')->nullable()->after('existing_field');
        $table->index('new_field'); // Add index if needed
    });
}

public function down()
{
    Schema::table('wf_requests', function (Blueprint $table) {
        $table->dropColumn('new_field');
    });
}
```

### Testing Guidelines

#### Unit Testing

```php
// tests/Unit/ApplicationTest.php
public function test_application_summary_returns_array()
{
    $summary = Application::deskWiseApplicationSummary();
    $this->assertIsArray($summary);
    $this->assertArrayHasKey('total_desk_application', $summary);
}
```

#### Feature Testing

```php
// tests/Feature/WfRequestTest.php
public function test_authenticated_user_can_view_applications()
{
    $user = User::factory()->create();
    $response = $this->actingAs($user)->get('/wf-request');
    $response->assertStatus(200);
}
```

### Performance Optimization

#### 1. Database Queries

```php
// Use eager loading
$applications = WfRequest::with(['noteLogs', 'metaData'])->get();

// Use select to limit fields
$applications = WfRequest::select(['id', 'title', 'status'])->get();

// Use indexes on frequently queried fields
// Already indexed: api_key, client_app_tracking_id, stack_holder_id, current_state_id
```

#### 2. Caching

```php
// Cache decision lists
$decisionList = Cache::remember(
    "decision_list_{$serviceId}_{$officeId}", 
    3600, 
    function() use ($serviceId, $officeId) {
        return ServiceModelApi::getDecisionList($serviceId, $officeId);
    }
);
```

#### 3. Queue Jobs

```php
// For heavy operations like notifications
// Create job: php artisan make:job SendApplicationNotification

class SendApplicationNotification implements ShouldQueue
{
    public function handle()
    {
        ServiceModelApi::notifyApplicationDecision(...);
    }
}

// Dispatch
SendApplicationNotification::dispatch($applicationData);
```

### Error Handling

```php
// In controllers
try {
    $result = Application::deskWiseApplicationList($request);
    return response()->json(['status' => 'success', 'data' => $result]);
} catch (\Throwable $th) {
    Log::error('Application list error: ' . $th->getMessage());
    return response()->json([
        'status' => 'error', 
        'message' => 'Failed to fetch applications'
    ], 500);
}

// In classes
try {
    // Business logic
} catch (\Exception $ex) {
    throw $ex; // Re-throw to controller
}
```

---

## Deployment Checklist

### Pre-Deployment

- [ ] Run tests: `php artisan test`
- [ ] Check for debug statements and remove
- [ ] Update `.env` with production values
- [ ] Set `APP_ENV=production`
- [ ] Set `APP_DEBUG=false`
- [ ] Configure proper database credentials
- [ ] Set up SSL certificate
- [ ] Configure proper `APP_URL`

### Deployment Steps

```bash
# 1. Pull latest code
git pull origin main

# 2. Install/update dependencies
composer install --optimize-autoloader --no-dev
npm ci --production

# 3. Clear and cache
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 4. Run migrations
php artisan migrate --force

# 5. Build assets
npm run build

# 6. Set permissions
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache

# 7. Restart services
sudo systemctl restart php8.0-fpm
sudo systemctl restart nginx
```

### Post-Deployment

- [ ] Verify application is accessible
- [ ] Test login functionality
- [ ] Check application listing
- [ ] Test decision making
- [ ] Verify API integrations
- [ ] Check logs for errors: `tail -f storage/logs/laravel.log`
- [ ] Monitor performance

---

## Troubleshooting

### Common Issues

#### 1. Session Not Working

```bash
# Check session driver in .env
SESSION_DRIVER=database

# Run session table migration
php artisan session:table
php artisan migrate

# Clear sessions
php artisan session:flush
```

#### 2. API Integration Failures

```php
// Check API credentials in .env
SERVICE_MODEL_DOMAIN=https://correct-domain.com
SERVICE_MODEL_API_KEY=correct_key

// Check logs
tail -f storage/logs/laravel.log

// Test API connection
$response = ServiceModelApi::testConnection();
```

#### 3. Permission Denied Errors

```bash
# Fix storage permissions
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache

# Fix SELinux (if applicable)
sudo chcon -R -t httpd_sys_rw_content_t storage bootstrap/cache
```

#### 4. DataTables Not Loading

```php
// Check route in blade template
<script>
    var dataTableUrl = "{{ route('wf-request.index') }}";
    // Ensure route exists
</script>

// Check XSS token
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
```

#### 5. Excel Export Fails

```php
// Check memory limit in php.ini
memory_limit = 512M

// Check Excel package
composer require maatwebsite/excel

// Clear config cache
php artisan config:clear
```

---

## API Reference

### Internal API Endpoints

#### Update Rating

```http
POST /api/updateRating
Content-Type: application/json

{
    "id": "api_key_here",
    "rating_points": 5,
    "comments": "Excellent service",
    "is_anonymouse": 0
}

Response: WfRequest object with updated rating
```

#### Update Read Status

```http
POST /api/updateRead
Content-Type: application/json

{
    "id": "api_key_here"
}

Response: WfRequest object with is_read = 0
```

#### Update Cancel Status

```http
POST /api/updateCancelStatus
Content-Type: application/json

{
    "id": "api_key_here"
}

Response: WfRequest object with status "Cancelled"
```

#### Update Assessment Data

```http
POST /api/update-assessment
Content-Type: application/json

{
    "id": "api_key_here",
    "wf_assesment": {
        "total_score": 75.5,
        "vulnerability": "Yellow"
    },
    "certificate_data_infos": {
        "first_name": "John",
        "last_name": "Doe"
    }
}

Response: WfRequest object with updated assessment
```

---

## Glossary

| Term | Definition |
|------|------------|
| **Application** | A service request submitted by a citizen |
| **Workflow** | The series of steps an application goes through |
| **Desk** | A specific position/designation that processes applications |
| **Decision** | An action taken on an application (approve, reject, forward, etc.) |
| **Stack Holder** | The current office/desk holding the application |
| **Designation** | A position/role within an office |
| **Office Layer** | Level in the government hierarchy (Ministry, Region, Province, etc.) |
| **API Key** | Unique identifier for each application from external system |
| **Tracking ID** | User-facing application reference number |
| **Service Model** | External system that defines services and workflows |
| **SSO** | Single Sign-On authentication system |
| **Certificate Data** | Data collected for certificate generation |
| **Approval Data** | Additional data captured during approval process |
| **Forward** | Sending application to another desk |
| **Resolved** | Application completed (approved or rejected) |
| **Overdue** | Application past expected delivery date |

---

## Support & Maintenance

### Log Files

```bash
# Application logs
storage/logs/laravel.log
storage/logs/laravel-YYYY-MM-DD.log

# Web server logs
/var/log/nginx/error.log
/var/log/apache2/error.log

# PHP logs
/var/log/php8.0-fpm.log
```

### Monitoring

```bash
# Check application status
php artisan about

# Check queue status
php artisan queue:work --once

# Monitor logs in real-time
tail -f storage/logs/laravel.log
```

### Backup Strategy

```bash
# Database backup
mysqldump -u username -p barmm_workflow > backup_$(date +%Y%m%d).sql

# Application backup
tar -czf app_backup_$(date +%Y%m%d).tar.gz \
    --exclude='storage/logs' \
    --exclude='node_modules' \
    --exclude='vendor' \
    /path/to/barmm-workflow-int

# Automated backup script (crontab)
0 2 * * * /path/to/backup.sh
```

---

## Changelog

### Version 1.1 (Current)

- Enhanced geographic hierarchy support (Ministry, Region, Province, Municipality, Barangay)
- PWD assessment scoring system
- Excel export for master lists
- Improved dashboard analytics
- Payment summary enhancements
- Document request workflow
- Rating and feedback system improvements

### Version 1.0

- Initial release
- Basic workflow management
- Application tracking
- Decision routing
- SSO integration
- Dashboard reports

---

## License

This project is proprietary software developed for BARMM government use.

---

## Contributors

- Development Team: Orange BD
- Client: Bangsamoro Autonomous Region in Muslim Mindanao (BARMM)

---

## Contact

For technical support or inquiries:

- Repository: <https://github.com/orange-bd/barmm-workflow-int>
- Email: <support@orange-bd.com>

---

**Document Version:** 1.0  
**Last Updated:** October 24, 2025  
**Generated by:** GitHub Copilot
