# FTZ ICRS Files Implementation

## Overview
This document describes the dual implementation of FTZ ICRS Files in the M1 ERP system.

**Implementation Date:** 2026-01-01

## Two Ways to Access FTZ Files

### 1. Dedicated FTZ Files Module
**Access:** FTZ ICRS → ICRS Files (menu)  
**URL:** `/ftz/files`

A specialized file management system specifically designed for FTZ compliance documents with:
- Dedicated upload interface with FTZ-specific categories
- Statistics dashboard (total files, size, categories, locations)
- Advanced filtering by category, location, and search
- File categories: Admission, Removal, Production, Compliance, General
- Location-based organization
- Direct download and delete capabilities

**Database Table:** `ftz_files`
- Stores file metadata separately from general file manager
- Includes FTZ-specific fields (category, location_id)
- Optimized for compliance document tracking

### 2. General File Manager Integration
**Access:** Files → FTZ Files (folder in sidebar)  
**URL:** `/file-manager?context=ftz`

FTZ Files also appear in the general file manager alongside other department folders (Accounting Files, HR Files, etc.).

**Database Table:** `file_folders` (entity_type = 'ftz')
- Integrates with existing folder structure
- Shares file manager features (comments, tags, versioning, sharing)
- Unified file search across all modules

## Technical Implementation

### Migrations
- **1011_add_ftz_icrs_files.sql** - Creates dedicated FTZ files system
  - `ftz_files` table with file metadata
  - Permissions: `ftz.view_files`, `ftz.upload_files`, `ftz.delete_files`
  - Menu item: "ICRS Files" under FTZ ICRS section
  
- **1012_add_ftz_to_file_manager.sql** - Integrates FTZ into general file manager
  - Adds 'ftz' to `file_folders.entity_type` ENUM
  - Creates "FTZ Files" folder (folder_id: 28)
  - Permission: `file_manager.access_ftz`

### Controllers
- **FtzFilesController.php** - Dedicated FTZ file management
  - `index()` - List files with statistics and filters
  - `upload()` - Handle file uploads (max 50MB, MIME validation)
  - `download($id)` - Download files
  - `delete($id)` - Delete files (removes DB record and physical file)

- **FileManagerController.php** - General file manager (no changes needed)
  - Automatically recognizes 'ftz' context
  - Uses PermissionChecker for access control

### Models
- **FtzFile.php** - Dedicated FTZ file operations
  - CRUD operations for `ftz_files` table
  - Category management
  - Statistics and reporting
  - File filtering by location

- **FileManager.php** - Updated to include FTZ
  - Added 'ftz' to `getContextRootFolder()` mapping
  - Added 'ftz' to `canAccessContext()` permission mapping
  - Added 'ftz' to `getAvailableContexts()` label mapping

### Permission System
- **PermissionChecker.php** - Updated with FTZ entity type
  - Added `'ftz' => 'ftz.view_files'` to `$entityTypePermissions`
  - Automatically enforces access control for FTZ context

### Views
- **views/ftz/files/index.php** - Dedicated FTZ files interface
  - Statistics cards
  - Filter form (category, location, search)
  - File listing table with icons
  - Upload modal
  - Delete confirmation with AJAX

### Routes
```php
// Dedicated FTZ Files
$router->get('/ftz/files', 'FtzFilesController@index');
$router->post('/ftz/files/upload', 'FtzFilesController@upload');
$router->get('/ftz/files/download/([0-9]+)', 'FtzFilesController@download');
$router->post('/ftz/files/delete/([0-9]+)', 'FtzFilesController@delete');

// General file manager (no new routes needed - uses existing)
$router->get('/file-manager', 'FileManagerController@index');
```

## File Storage

### Dedicated FTZ System
- **Directory:** `uploads/ftz_files/`
- **Permissions:** 777 (created automatically by controller)
- **Naming:** `ftz_{uniqid}_{timestamp}.{ext}`
- **File Types:** PDF, Word, Excel, CSV, Text, Images (JPEG, PNG, GIF)
- **Max Size:** 50MB per file

### General File Manager
- **Directory:** `uploads/files/` (standard file manager path)
- Files uploaded through file manager context=ftz use existing file manager upload handling

## Permissions

### FTZ-Specific Permissions
| Permission | Description | Module |
|-----------|-------------|---------|
| `ftz.view_files` | View FTZ ICRS Files | FTZ |
| `ftz.upload_files` | Upload FTZ ICRS Files | FTZ |
| `ftz.delete_files` | Delete FTZ ICRS Files | FTZ |
| `file_manager.access_ftz` | Access FTZ Files in File Manager | Files |

### Permission Grants
- All FTZ permissions granted to **Admin role** by default
- Other roles must be explicitly granted permissions

## File Categories

The dedicated FTZ system includes predefined categories:
- **ADMISSION** - Admission Documents
- **REMOVAL** - Removal/Export Documents  
- **PRODUCTION** - Production Notifications
- **COMPLIANCE** - Compliance Reports
- **GENERAL** - General Documents

## Usage Scenarios

### When to Use Dedicated FTZ Files Module
- Uploading FTZ-specific compliance documents
- Filtering by FTZ categories (Admission, Removal, etc.)
- Viewing FTZ statistics and summaries
- Quick access to FTZ documents by location
- Direct FTZ workflow (upload → categorize → organize by location)

### When to Use General File Manager
- Integrating FTZ files with other departmental files
- Using advanced file manager features (comments, tags, versioning)
- Sharing FTZ files with other users/departments
- Searching across all company files including FTZ
- Organizing FTZ files in folder hierarchies

## Database Schema

### ftz_files Table
```sql
CREATE TABLE ftz_files (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    file_name VARCHAR(255) NOT NULL,
    original_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_size INT NOT NULL,
    file_type VARCHAR(100) NOT NULL,
    category VARCHAR(100) DEFAULT 'GENERAL',
    description TEXT,
    uploaded_by INT UNSIGNED NOT NULL,
    location_id INT UNSIGNED DEFAULT NULL,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (uploaded_by) REFERENCES users(id),
    FOREIGN KEY (location_id) REFERENCES locations(id)
);
```

### file_folders Table (FTZ Integration)
```sql
-- entity_type ENUM updated to include 'ftz'
ALTER TABLE file_folders 
MODIFY COLUMN entity_type ENUM(..., 'ftz') DEFAULT 'system';

-- FTZ Files folder created
INSERT INTO file_folders (name, entity_type, path, access_level)
VALUES ('FTZ Files', 'ftz', '/FTZ Files', 'public');
```

## Future Enhancements

### Potential Features
1. **Unified View** - Show both dedicated and file manager FTZ files in one interface
2. **Sync Option** - Copy files between dedicated FTZ system and file manager
3. **Advanced Search** - Search across both systems simultaneously
4. **Audit Trail** - Track file access and modifications for compliance
5. **Auto-categorization** - AI-based document categorization
6. **Retention Policies** - Automatic archival/deletion based on compliance rules
7. **E-signature Integration** - Digital signing for compliance documents
8. **OCR & Indexing** - Full-text search within PDF documents

## Testing

### Manual Testing Checklist
- [ ] Access dedicated FTZ Files at `/ftz/files`
- [ ] Upload file with each category
- [ ] Filter by category, location, search
- [ ] Download file
- [ ] Delete file (verify physical file removed)
- [ ] Access file manager at `/file-manager?context=ftz`
- [ ] Verify FTZ Files folder appears in sidebar
- [ ] Upload file through general file manager to FTZ context
- [ ] Verify permissions work for non-admin users
- [ ] Test file size limit (50MB)
- [ ] Test invalid file types are rejected

## Troubleshooting

### Common Issues

**FTZ Files folder not visible in file manager**
- Verify migration 1012 ran successfully
- Check `file_folders` table for entity_type='ftz'
- Ensure user has `file_manager.access_ftz` permission

**Upload directory permission errors**
- Run: `chmod 777 uploads/ftz_files/`
- Verify web server can write to directory

**Files not appearing after upload**
- Check database insert succeeded in `ftz_files` table
- Verify physical file exists in `uploads/ftz_files/`
- Check user has `ftz.view_files` permission

**Permission denied errors**
- Verify user's role has required permissions
- Check `role_permissions` table
- Ensure PermissionChecker includes 'ftz' mapping

## Support

For issues or questions:
1. Check error logs: `debug/file_manager.log`
2. Verify permissions: Check `permissions` and `role_permissions` tables
3. Test with admin account first
4. Review WARP.md for system architecture

## Related Documentation
- `WARP.md` - System architecture and conventions
- `docs/File Manager/FILE_MANAGER_IMPLEMENTATION.md` - General file manager
- `OPPORTUNITIES_ENHANCEMENTS.md` - CRM file attachments example
