# AIPT - Intellectual Property Management System
## Comprehensive Documentation

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Architecture](#architecture)
3. [Core Modules](#core-modules)
4. [Database Schema](#database-schema)
5. [API Documentation](#api-documentation)
6. [User Interface](#user-interface)
7. [Security & Authentication](#security--authentication)
8. [Configuration](#configuration)
9. [Deployment](#deployment)
10. [Troubleshooting](#troubleshooting)

---

## System Overview

### Project Description
AIPT (Advanced Intellectual Property Tracking) is a comprehensive Laravel-based system designed for managing intellectual property assets including trademarks, patents, litigation cases, and related financial transactions. The system provides a modular architecture with role-based access control and advanced workflow management.

### Key Features
- **Multi-Module Architecture**: Trademarks, Patents, Litigation, HR, Accounting, TeamWatch, and Translation modules
- **Role-Based Access Control**: Sophisticated permission system with hierarchical approvals
- **Financial Management**: Multi-currency transaction processing with approval workflows
- **Document Management**: File uploads, attachments, and document tracking
- **Notification System**: Real-time notifications and deadline management
- **Reporting & Analytics**: Comprehensive reporting with Excel export capabilities
- **Multi-language Support**: Arabic text support with proper encoding

### Technology Stack
- **Backend**: Laravel 9.x, PHP 8.0+
- **Frontend**: AdminLTE 3, Bootstrap 4, jQuery
- **Database**: MySQL/MariaDB
- **Modules**: nwidart/laravel-modules
- **Permissions**: spatie/laravel-permission
- **Export**: maatwebsite/excel, barryvdh/laravel-dompdf
- **Additional**: OpenAI integration, Pusher for real-time features

---

## Architecture

### System Architecture Diagram

```mermaid
graph TB
    subgraph "Frontend Layer"
        A[AdminLTE Dashboard] --> B[Module Views]
        B --> C[Trademark Management]
        B --> D[Patent Management]
        B --> E[Litigation Management]
        B --> F[HR Management]
        B --> G[Accounting Module]
    end

    subgraph "Controller Layer"
        H[Core Controllers] --> I[TradeMarksController]
        H --> J[AccTransactionController]
        H --> K[UsersController]
        H --> L[Module Controllers]
    end

    subgraph "Model Layer"
        M[Core Models] --> N[User]
        M --> O[TradeMarkTicket]
        M --> P[AccTransaction]
        M --> Q[Module Entities]
    end

    subgraph "Database Layer"
        R[(MySQL Database)] --> S[Core Tables]
        R --> T[Module Tables]
        R --> U[Audit Tables]
    end

    A --> H
    H --> M
    M --> R
```

### Module Structure
The system follows a modular architecture with the following structure:

```
AIPT/
├── app/                    # Core application files
├── Modules/               # Modular components
│   ├── Accounting/        # Financial management
│   ├── HR/               # Human resources
│   ├── Litigation/       # Legal case management
│   ├── Patent/           # Patent management
│   ├── TeamWatch/        # Team monitoring
│   ├── TradeMarks/       # Trademark management
│   └── Translation/      # Translation services
├── resources/views/       # Blade templates
├── database/migrations/   # Database schema
└── routes/               # Application routes
```

---

## Core Modules

### 1. Trademark Management Module

#### Overview
Manages trademark applications, registrations, and related processes with deadline tracking and notification system.

#### Key Features
- **Trademark Registration**: Complete trademark application workflow
- **Deadline Management**: Automated deadline tracking with notifications
- **Document Management**: File uploads and document organization
- **Status Tracking**: Real-time status updates and history
- **Reporting**: Comprehensive reports with filtering options

#### Models
- `TradeMarkTicket`: Core trademark entity
- `TrademarkTicketHistory`: Audit trail and status changes
- `TrademarkChangeLog`: Change tracking for compliance

#### Controllers
- `TradeMarksController`: Main trademark operations
- `TrademarksDashboardController`: Analytics and reporting

#### Key Methods
```php
// TradeMarksController
public function index()                    // List all trademarks
public function create()                   // Show creation form
public function store(Request $request)    // Create new trademark
public function show($id)                  // Display trademark details
public function update(Request $request, $id) // Update trademark
public function report(Request $request)   // Generate reports
public function excel(Request $request)    // Export to Excel
```

### 2. Accounting Module

#### Overview
Comprehensive financial management system with multi-currency support, invoice management, and approval workflows.

#### Key Features
- **Transaction Management**: Multi-currency financial transactions
- **Invoice System**: Complete invoice lifecycle management
- **Payment Processing**: Payment tracking and reconciliation
- **Financial Reporting**: Advanced financial reports and analytics
- **Approval Workflows**: Role-based approval system

#### Models
- `AccTransaction`: Core financial transaction entity
- `Invoice`: Invoice management
- `InvoicePayment`: Payment tracking
- `Statement`: Financial statements
- `Client`: Client management for accounting

#### Controllers
- `AccTransactionController`: Transaction management
- `InvoiceController`: Invoice operations
- `FinancialReportController`: Financial reporting

#### Key Methods
```php
// AccTransactionController
public function index($related, $id)      // List transactions
public function create($id)               // Create transaction form
public function store($id, $id_type)      // Store transaction
public function MyTransactions()          // User's transactions
public function generateReport()          // Generate reports
```

### 3. HR Module

#### Overview
Complete human resources management system with employee records, attendance, payroll, and performance management.

#### Key Features
- **Employee Management**: Complete employee lifecycle
- **Attendance Tracking**: Time and attendance management
- **Leave Management**: Leave requests and approvals
- **Payroll System**: Salary and compensation management
- **Performance Management**: Employee performance tracking
- **Training Management**: Training programs and enrollment

#### Models
- `Employee`: Employee records
- `Attendance`: Time tracking
- `Leave`: Leave management
- `Payroll`: Salary processing
- `Performance`: Performance reviews
- `Training`: Training programs

#### Controllers
- `EmployeeController`: Employee management
- `AttendanceController`: Time tracking
- `LeaveController`: Leave management
- `PayrollController`: Salary processing

### 4. Patent Module

#### Overview
Patent application and management system with annual fee tracking and deadline management.

#### Key Features
- **Patent Applications**: Complete patent filing workflow
- **Annual Fee Management**: Automated fee tracking and notifications
- **Deadline Tracking**: Critical date management
- **Document Management**: Patent document organization
- **Status Monitoring**: Real-time patent status updates

#### Models
- `PatentTicket`: Core patent entity
- `AnnualFeeDeadline`: Fee tracking
- `PatentTransaction`: Financial transactions
- `FeeNotification`: Notification system

### 5. Litigation Module

#### Overview
Legal case management system for tracking litigation processes and court proceedings.

#### Key Features
- **Case Management**: Complete case lifecycle
- **Court Proceedings**: Hearing and deadline tracking
- **Document Management**: Legal document organization
- **Client Management**: Litigation client tracking
- **Reporting**: Case progress and outcome reports

#### Models
- `LiCases`: Core case entity
- `LiCourtHearing`: Court proceedings
- `LiDocument`: Legal documents
- `LiClient`: Litigation clients

---

## Database Schema

### Core Tables

#### Users Table
```sql
CREATE TABLE users (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    username VARCHAR(255) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    gender VARCHAR(255),
    department_id BIGINT UNSIGNED,
    manger_id BIGINT UNSIGNED,
    role_id BIGINT UNSIGNED,
    img_path VARCHAR(255),
    status BOOLEAN,
    login_status BOOLEAN,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    deleted_at TIMESTAMP
);
```

#### Trade Mark Tickets Table
```sql
CREATE TABLE trade_mark_tickets (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    TKT_Type VARCHAR(255),
    client_id BIGINT UNSIGNED,
    added_by BIGINT UNSIGNED,
    associate_id BIGINT UNSIGNED,
    methode_id BIGINT UNSIGNED,
    assigned_to BIGINT UNSIGNED,
    procedure_id BIGINT UNSIGNED,
    country_id BIGINT UNSIGNED,
    applicant_id BIGINT UNSIGNED,
    clientref VARCHAR(255) DEFAULT 'n/a',
    aiptref TEXT,
    filing_date VARCHAR(255),
    filing_no VARCHAR(255),
    class VARCHAR(255),
    register_no VARCHAR(255),
    trademark_name VARCHAR(255) NOT NULL,
    img_paths VARCHAR(255),
    folder_path VARCHAR(255),
    related_TKT BIGINT UNSIGNED,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    deleted_at TIMESTAMP
);
```

#### Accounting Transactions Table
```sql
CREATE TABLE acc_transactions (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    reference_no VARCHAR(255),
    stages VARCHAR(255),
    role_ranks JSON,
    department_id BIGINT UNSIGNED,
    country VARCHAR(255),
    deadline DATE,
    bill_deadline DATE,
    type VARCHAR(255),
    id_type BIGINT UNSIGNED,
    procedure VARCHAR(255),
    value DECIMAL(15,2),
    value_usd DECIMAL(15,2),
    description TEXT,
    exchangeRate DECIMAL(10,4),
    currency VARCHAR(255),
    currency_code VARCHAR(10),
    related_table VARCHAR(255),
    related_id BIGINT UNSIGNED,
    has_bills BOOLEAN DEFAULT FALSE,
    created_by BIGINT UNSIGNED,
    aiptref VARCHAR(255),
    InvoiceNo VARCHAR(255),
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);
```

### Module Tables

#### Accounting Module Tables
- `invoices`: Invoice management
- `invoice_items`: Invoice line items
- `invoice_payments`: Payment records
- `statements`: Financial statements
- `clients`: Accounting clients
- `services`: Service catalog
- `sections`: Service categories

#### HR Module Tables
- `employees`: Employee records
- `attendance`: Time tracking
- `leaves`: Leave management
- `payrolls`: Salary processing
- `performances`: Performance reviews
- `trainings`: Training programs
- `benefits`: Employee benefits

---

## API Documentation

### Authentication
The system uses Laravel's built-in authentication with custom middleware for role-based access control.

### Core Endpoints

#### Trademark Management
```
GET    /trademarkstkts                    # List trademarks
POST   /trademarkstkts                    # Create trademark
GET    /trademarkstkts/{id}               # Show trademark
PUT    /trademarkstkts/{id}               # Update trademark
DELETE /trademarkstkts/{id}               # Delete trademark
GET    /trademarkstkts/report             # Generate report
POST   /trademarkstkts/excel              # Export to Excel
```

#### Accounting Transactions
```
GET    /acc-transactions/index/{table}/{id}  # List transactions
POST   /acc-transactions/{id}/{id_type}      # Create transaction
GET    /acc-transactions/edit/{id}           # Edit transaction
PUT    /acc-transactions/update/{id}         # Update transaction
GET    /acc-transactions/my-acc-transactions # User transactions
```

#### User Management
```
GET    /users/index                       # List users
POST   /users/store                       # Create user
GET    /users/show/{id}                   # Show user
PUT    /users/update/{id}                 # Update user
DELETE /users/delete/{id}                 # Delete user
```

### Module-Specific Endpoints

#### Accounting Module
```
GET    /accounting/                       # Dashboard
GET    /accounting/clients                # List clients
POST   /accounting/clients                # Create client
GET    /accounting/invoices               # List invoices
POST   /accounting/invoices               # Create invoice
GET    /accounting/reports                # Financial reports
```

#### HR Module
```
GET    /hr/                               # HR Dashboard
GET    /hr/employees                      # List employees
POST   /hr/employees                      # Create employee
GET    /hr/attendance                     # Attendance records
POST   /hr/leaves                         # Create leave request
```

---

## User Interface

### Layout Structure
The system uses AdminLTE 3 as the base template with the following structure:

```
layouts/
├── master.blade.php          # Main layout
├── app.blade.php            # Application layout
├── navbar.blade.php         # Navigation bar
├── sidebar.blade.php        # Sidebar navigation
└── footer.blade.php         # Footer
```

### Key Views

#### Trademark Views
- `trademarkstkts.blade.php`: Main trademark listing
- `tickets/add.blade.php`: Create trademark form
- `tickets/edit.blade.php`: Edit trademark form
- `tickets/show.blade.php`: Trademark details
- `trademarkstkts-report.blade.php`: Reporting interface

#### Accounting Views
- `acc_transactions/index.blade.php`: Transaction listing
- `acc_transactions/create.blade.php`: Create transaction
- `acc_transactions/edit.blade.php`: Edit transaction
- `acc_transactions/related-transactions.blade.php`: Related transactions

#### User Management Views
- `users/index.blade.php`: User listing
- `users/add.blade.php`: Create user
- `users/edit.blade.php`: Edit user
- `users/show.blade.php`: User details

### Responsive Design
The interface is fully responsive using Bootstrap 4 grid system and AdminLTE components.

---

## Security & Authentication

### Authentication System
- **Custom Authentication**: Custom login controller with username/password
- **Session Management**: Laravel session-based authentication
- **Password Security**: Bcrypt hashing for passwords

### Authorization
- **Role-Based Access Control**: Using spatie/laravel-permission
- **Permission System**: Granular permissions for different modules
- **Middleware Protection**: Route-level security with custom middleware

### Security Features
- **CSRF Protection**: All forms protected with CSRF tokens
- **Input Validation**: Comprehensive validation rules
- **SQL Injection Prevention**: Eloquent ORM with parameterized queries
- **XSS Protection**: Output escaping in Blade templates

### Permission Structure
```php
// Example permissions
'trademark-list'
'trademark-create'
'trademark-edit'
'trademark-delete'
'accounting-invoices-create'
'accounting-payments-create'
'hr-employees-manage'
```

---

## Configuration

### Environment Configuration
Key environment variables in `.env`:

```env
APP_NAME=AIPT
APP_ENV=production
APP_DEBUG=false
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=aipt_db
DB_USERNAME=root
DB_PASSWORD=

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-password
MAIL_ENCRYPTION=tls

PUSHER_APP_ID=your-pusher-id
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=your-pusher-secret
PUSHER_APP_CLUSTER=your-pusher-cluster
```

### Module Configuration
Each module has its own configuration file:

```php
// config/modules.php
'namespace' => 'Modules',
'modules' => base_path('Modules'),
'cache' => [
    'enabled' => false,
    'key' => 'laravel-modules',
    'lifetime' => 60,
],
```

### Service Providers
Key service providers registered:

```php
// config/app.php
'providers' => [
    Yajra\DataTables\DataTablesServiceProvider::class,
    Barryvdh\DomPDF\ServiceProvider::class,
    Spatie\Permission\PermissionServiceProvider::class,
    // Module service providers
    Modules\Accounting\Providers\AccountingServiceProvider::class,
    Modules\HR\Providers\HRServiceProvider::class,
    // ... other providers
],
```

---

## Deployment

### System Requirements
- **PHP**: 8.0 or higher
- **Laravel**: 9.x
- **Database**: MySQL 5.7+ or MariaDB 10.3+
- **Web Server**: Apache 2.4+ or Nginx 1.18+
- **Extensions**: BCMath, Ctype, Fileinfo, JSON, Mbstring, OpenSSL, PDO, Tokenizer, XML

### Installation Steps

1. **Clone Repository**
```bash
git clone <repository-url>
cd AIPT
```

2. **Install Dependencies**
```bash
composer install
npm install
```

3. **Environment Setup**
```bash
cp .env.example .env
php artisan key:generate
```

4. **Database Setup**
```bash
php artisan migrate
php artisan db:seed
```

5. **Module Installation**
```bash
php artisan module:enable Accounting
php artisan module:enable HR
php artisan module:enable Litigation
php artisan module:enable Patent
php artisan module:enable TeamWatch
php artisan module:enable TradeMarks
php artisan module:enable Translation
```

6. **Asset Compilation**
```bash
npm run dev
# or for production
npm run production
```

7. **Permissions Setup**
```bash
php artisan permission:create-role admin
php artisan permission:create-role manager
php artisan permission:create-role employee
```

### Production Deployment

1. **Optimize Application**
```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize
```

2. **Set Permissions**
```bash
chmod -R 755 storage
chmod -R 755 bootstrap/cache
```

3. **Configure Web Server**
Set document root to `public` directory and configure virtual host.

---

## Troubleshooting

### Common Issues

#### 1. Module Not Loading
**Problem**: Module routes not accessible
**Solution**: 
```bash
php artisan module:enable <module-name>
php artisan config:cache
```

#### 2. Permission Errors
**Problem**: Access denied errors
**Solution**: 
```bash
php artisan permission:create-permission <permission-name>
php artisan permission:give-permission-to-role <role> <permission>
```

#### 3. Database Connection Issues
**Problem**: Database connection failed
**Solution**: Check `.env` file database credentials and ensure database server is running.

#### 4. File Upload Issues
**Problem**: File uploads not working
**Solution**: Check file permissions and `upload_max_filesize` in PHP configuration.

#### 5. Excel Export Issues
**Problem**: Arabic text not displaying correctly in Excel
**Solution**: Ensure proper UTF-8 encoding and use PhpSpreadsheet normalization.

### Debug Mode
Enable debug mode in `.env`:
```env
APP_DEBUG=true
LOG_LEVEL=debug
```

### Log Files
Check Laravel logs in `storage/logs/laravel.log` for detailed error information.

---

## Support & Maintenance

### Regular Maintenance Tasks
1. **Database Backups**: Regular database backups
2. **Log Rotation**: Clean up old log files
3. **Cache Clearing**: Clear application caches
4. **Module Updates**: Keep modules updated
5. **Security Updates**: Regular security patches

### Monitoring
- Monitor application logs for errors
- Check database performance
- Monitor disk space usage
- Track user activity and system usage

### Backup Strategy
```bash
# Database backup
mysqldump -u username -p database_name > backup.sql

# File backup
tar -czf backup_files.tar.gz storage/app/public
```

---

## Conclusion

The AIPT system is a comprehensive intellectual property management solution with robust architecture, extensive functionality, and modular design. This documentation provides a complete overview of the system's capabilities, technical implementation, and operational procedures.

For additional support or questions, please refer to the system logs or contact the development team.

---

*Last Updated: [Current Date]*
*Version: 1.0*
*Documentation Maintained by: Development Team*
