# KPI Analysis Dashboard

A comprehensive web application for analyzing Key Performance Indicators (KPIs) with AI-powered insights, Nextcloud integration, and professional PDF reporting.

## ✅ Status: FULLY FUNCTIONAL & COMPLETE

**Implementation Complete - All Requirements Met!**
- ✅ **No dummy data** - Database starts empty, all data from uploads
- ✅ **Empty state handling** - Dashboard shows appropriate messages when no data
- ✅ **Core function working** - Upload Excel files and perform automatic analysis
- ✅ Login and dashboard are separate pages
- ✅ Dashboard is protected and requires authentication  
- ✅ Fallback authentication working correctly
- ✅ Proper redirects in place

**Quick Start:** See [QUICK_START_GUIDE.md](QUICK_START_GUIDE.md) for setup instructions.  
**Implementation Details:** See [IMPLEMENTATION_SUMMARY.md](IMPLEMENTATION_SUMMARY.md) for complete details.

## Features

### 📊 **Core Functionality**
- **Excel File Processing**: Upload and parse KPI Excel files with multiple sheets
- **Multi-perspective Analysis**: Financial, Customer, Internal Process, and Learning & Growth perspectives
- **AI-Powered Insights**: OpenAI integration for intelligent recommendations
- **Interactive Dashboard**: Real-time charts and data visualization
- **PDF Report Generation**: Professional reports with embedded charts
- **Nextcloud Integration**: OAuth authentication and file synchronization
- **🔐 LDAP Group-Based Authentication**: Enterprise-grade authentication with group membership verification

### 🎯 **Key Capabilities**
- **Comparative Analysis**: Track performance trends across time periods
- **Pattern Recognition**: Identify performance patterns and anomalies
- **Actionable Recommendations**: AI-generated improvement suggestions
- **Professional Visualization**: Interactive charts using Plotly
- **Enterprise Ready**: Secure authentication and role-based access

## Technology Stack

- **Backend**: FastAPI (Python)
- **Frontend**: HTML5, CSS3, JavaScript, Bootstrap 5
- **Database**: SQLite (development) / PostgreSQL (production)
- **Authentication**: LDAP/Active Directory + Nextcloud OAuth
- **AI Integration**: OpenAI API
- **Data Processing**: Pandas, OpenPyXL
- **Visualization**: Plotly, Chart.js, Matplotlib
- **PDF Generation**: ReportLab

## Installation

### Prerequisites
- Python 3.8+
- Nextcloud server (optional, for cloud integration)
- OpenAI API key (optional, for AI features)

### Quick Start

1. **Clone the repository**
   ```bash
   git clone <repository-url>
   cd kpi_analysis
   ```

2. **Install dependencies**
   ```bash
   pip install -r requirements.txt
   ```

3. **Configure environment**
   ```bash
   cp config/.env.template .env
   # Edit .env with your configuration
   ```

4. **Run the application**
   ```bash
   python main.py
   ```

5. **Access the dashboard**
   Open your browser to `http://localhost:8000`

## Configuration

### Environment Variables

Create a `.env` file based on `.env.template`:

```env
# Application Settings
DEBUG=true
SECRET_KEY=your-super-secret-key

# Nextcloud Configuration
NEXTCLOUD_BASE_URL=https://nc.mapan.co.id
NEXTCLOUD_OAUTH_CLIENT_ID=your-oauth-client-id
NEXTCLOUD_OAUTH_CLIENT_SECRET=your-oauth-client-secret
NEXTCLOUD_KPI_FOLDER=/KPI_Files

# OpenAI Configuration
OPENAI_API_KEY=your-openai-api-key
OPENAI_MODEL=gpt-4

# LDAP Configuration
LDAP_SERVER=ldap.your-company.com
LDAP_BASE_DN=DC=your-company,DC=com
LDAP_BIND_DN=CN=service-account,OU=Service Accounts,DC=your-company,DC=com
LDAP_BIND_PASSWORD=your-password
```

### Nextcloud Setup

1. **Create OAuth App in Nextcloud**
   - Go to Settings > Security > OAuth 2.0 client ids
   - Add new client
   - Set redirect URI: `http://localhost:8000/auth/nextcloud/callback`
   - Copy client ID and secret to `.env`

2. **Configure KPI Folder**
   - Create `/KPI_Files` folder in Nextcloud
   - Upload Excel files to this folder

### OpenAI Setup

1. **Get API Key**
   - Visit https://platform.openai.com/api-keys
   - Create new API key
   - Add to `.env` file

### LDAP Authentication Setup

1. **Create KPI Users Group**
   - In Active Directory: Create security group "KPI_Users"
   - In OpenLDAP: Create group entry for authorized users
   - Add users who need access to the system

2. **Configure LDAP Settings**
   - Update `.env` file with LDAP server details
   - Set group DN for authorized access
   - Configure service account credentials

3. **Test Configuration**
   - Run `GET /api/auth/test` to verify settings
   - Test login with authorized user credentials

See [LDAP_AUTHENTICATION.md](LDAP_AUTHENTICATION.md) for detailed setup instructions.

## Usage

### 1. Upload KPI Files

- **Local Upload**: Drag and drop Excel files or use the upload button
- **Nextcloud Sync**: Connect to Nextcloud and browse files in the cloud
- **Supported Formats**: `.xlsx`, `.xls` files

### 2. Excel File Structure

The application expects Excel files with the following structure:

- **KPI Sheet**: Summary with overall scores and weights
- **Achievement Sheet**: Achievement status for each KPI
- **Detail Sheets**: Individual KPI data (F2a, F2b, B1a, etc.)

### 3. Analysis Features

- **Performance Overview**: Total scores and achievement rates
- **Perspective Analysis**: Breakdown by Financial, Customer, Internal Process, Learning & Growth
- **Trend Analysis**: Performance over time
- **AI Insights**: Automated analysis and recommendations

### 4. Reports

- **PDF Generation**: Professional reports with charts and analysis
- **Interactive Charts**: Browser-based visualizations
- **Export Options**: Download reports and charts

## API Documentation

The application provides a REST API:

- **Health Check**: `GET /health`
- **File Management**: `POST /api/files/upload`, `GET /api/files/list`
- **Analysis**: `POST /api/analysis/run/{file_id}`, `GET /api/analysis/{file_id}`
- **Nextcloud**: `GET /api/nextcloud/files`, `POST /api/nextcloud/download/{file_id}`

Access interactive API docs at `http://localhost:8000/docs`

## Deployment

### Local Development

```bash
# Install dependencies
pip install -r requirements.txt

# Run with auto-reload
python main.py
```

### Production Deployment

1. **Using Gunicorn**
   ```bash
   pip install gunicorn
   gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8000
   ```

2. **Using Docker**
   ```bash
   docker build -t kpi-analysis .
   docker run -p 8000:8000 --env-file .env kpi-analysis
   ```

3. **Server Deployment**
   - Configure reverse proxy (nginx/Apache)
   - Set up SSL certificates
   - Configure environment variables
   - Set up database (PostgreSQL recommended)

### Environment-Specific Configurations

#### Development
- SQLite database
- Debug mode enabled
- Local file storage

#### Production
- PostgreSQL database
- Debug mode disabled
- Secure authentication
- File storage on cloud/storage
- SSL/HTTPS required

## Project Structure

```
kpi_analysis/
├── main.py                 # FastAPI application entry point
├── requirements.txt        # Python dependencies
├── config/                # Configuration files
│   ├── settings.py        # Application settings
│   ├── .env.template     # Environment template
│   └── __init__.py
├── app/                   # Application modules
│   ├── api/              # API routes
│   │   ├── routes.py     # FastAPI routes
│   │   └── __init__.py
│   ├── core/             # Core functionality
│   │   ├── database.py   # Database operations
│   │   └── __init__.py
│   ├── models/           # Data models
│   │   ├── kpi_models.py # KPI data structures
│   │   └── __init__.py
│   ├── services/         # Business logic
│   │   ├── nextcloud_service.py
│   │   ├── excel_parser.py
│   │   ├── analysis_engine.py
│   │   ├── pdf_generator.py
│   │   └── __init__.py
│   └── __init__.py
├── templates/            # HTML templates
│   └── dashboard.html
├── static/              # Static files
│   ├── css/
│   │   └── dashboard.css
│   ├── js/
│   │   └── dashboard.js
│   └── images/
├── data/               # Application data
├── uploads/            # Uploaded files
└── reports/           # Generated reports
```

## Troubleshooting

### Common Issues

1. **File Upload Fails**
   - Check file format (.xlsx, .xls only)
   - Verify file size (< 50MB)
   - Check permissions on upload directory

2. **Nextcloud Connection Issues**
   - Verify Nextcloud server URL
   - Check OAuth app configuration
   - Ensure user has access to KPI folder

3. **OpenAI Integration Issues**
   - Verify API key is valid
   - Check account limits
   - Monitor API usage

4. **Database Issues**
   - Check database permissions
   - Verify database URL configuration
   - Run database migrations if needed

### Logs

- Application logs: Check console output
- Database logs: SQLite file in `data/` directory
- Web server logs: Check server configuration

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Support

For support and questions:
- Create an issue in the repository
- Check the documentation
- Review the troubleshooting section

## Roadmap

### Upcoming Features
- [ ] Multi-language support
- [ ] Advanced analytics dashboard
- [ ] Email notifications
- [ ] Mobile-responsive design
- [ ] Real-time collaboration
- [ ] Advanced reporting templates
- [ ] Integration with other systems (SAP, Salesforce, etc.)

### Version History
- **v1.0.0**: Initial release with core functionality
- Core features: Excel processing, AI analysis, Nextcloud integration
- Future versions will include additional features and improvements