loka-framework 0.1.0
LOKA — Lightweight Modular Framework built on FastAPI & Typer
License: MIT
Requires Python: >=3.10
Keywords: framework, fastapi, typer, sqlalchemy, modular, erpnext

<div align="center">

# 🐍 LOKA Framework

### Lightweight Modular Backend Framework

**FastAPI** + **Typer** + **SQLAlchemy** + **Alembic**

[![Python Version](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.100%2B-009688.svg)](https://fastapi.tiangolo.com)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)

**LOKA** dirancang untuk developer modern yang ingin membangun sistem modular seperti **ERPNext** / **Django**, tapi dengan struktur Pythonic, CLI cerdas, dan arsitektur modular dinamis.

[Instalasi](#-2-instalasi-framework) • [Quick Start](#-5-cli-commands) • [Dokumentasi](#-4-struktur-direktori) • [Fitur](#-6-fitur-otentikasi-auth-core)

---

</div>

## 🚀 1. Persiapan Awal

### 🧩 Prasyarat

Pastikan kamu sudah menginstal:

| Requirement | Version | Note |
|------------|---------|------|
| **Python** | ≥ 3.11 | ⚠️ Hindari 3.14 (warning dari pydantic.v1) |
| **pip** | Latest | Package manager |
| **venv** | - | Virtual environment |
| **Git** | - | Version control |
| **SQLite** | - | Database default bawaan |
| **Alembic** | - | Otomatis terinstal via requirements |

---

## 📦 2. Instalasi Framework

### Clone Repository

```bash
git clone https://github.com/your-org/loka-framework.git
cd Loka
```

### Buat Virtual Environment

**Windows:**
```bash
python -m venv venv
venv\Scripts\activate
```

**Mac/Linux:**
```bash
python -m venv venv
source venv/bin/activate
```

### Install Dependencies

**Cara 1: Via requirements.txt**
```bash
pip install -r requirements.txt
```

**Cara 2: Development Mode (Editable)**
```bash
pip install -e .
```

> 💡 **Rekomendasi:** Gunakan development mode untuk kemudahan debugging dan hot reload.

---

## ⚙️ 3. Konfigurasi Awal

Buka file `core/config.py` dan sesuaikan pengaturan sesuai kebutuhan:

```python
class Settings(BaseSettings):
    app_name: str = "LOKA Framework Dev"
    debug: bool = True
    secret_key: str = "mysecretkey123"
    database_url: str = "sqlite:///loka.db"
    host: str = "127.0.0.1"
    port: int = 8000
```

### Konfigurasi Database

**SQLite (Default):**
```python
database_url: str = "sqlite:///loka.db"
```

**PostgreSQL:**
```python
database_url: str = "postgresql://user:password@localhost/dbname"
```

**MySQL:**
```python
database_url: str = "mysql+pymysql://user:password@localhost/dbname"
```

---

## 🧠 4. Struktur Direktori

```
Loka/
│
├── core/                       # Core Framework Engine
│   ├── auth.py                 # JWT Auth & Password Hashing
│   ├── cli.py                  # Typer CLI (loka command)
│   ├── config.py               # Base Settings
│   ├── db.py                   # SQLAlchemy session + Base
│   ├── migrate.py              # Alembic integration
│   ├── router.py               # Auto-register routers
│   ├── response.py             # Standardized API response
│   ├── schema.py               # Shared Pydantic schemas
│   ├── dependency.py           # Dependency injectors
│   ├── logger.py               # Centralized logging
│   └── templates/              # Default HTML Templates
│
├── apps/                       # Modular Applications
│   └── auth/
│       ├── model.py            # User & Role Model
│       ├── schema.py           # Pydantic Schemas
│       └── api.py              # Login/Register Endpoint
│
├── migrations/                 # Alembic Migrations
│   ├── versions/               # Auto-generated revisions
│   ├── env.py                  # Alembic config loader
│   └── script.py.mako          # Migration template
│
├── loka.db                     # SQLite Database
├── alembic.ini                 # Alembic configuration
├── requirements.txt            # Dependencies
├── setup.py                    # Package setup
├── setup.cfg                   # Setup configuration
└── README.md                   # Documentation
```

---

## 🧰 5. CLI Commands

### 🔹 Setup Awal Framework

```bash
loka setup
```

Perintah ini akan otomatis:
- ✅ Membuat tabel database (`Base.metadata.create_all`)
- ✅ Menjalankan migrasi dengan Alembic
- ✅ Membuat akun default (Admin & User)

**Output:**
```
⚙️  Memulai proses setup LOKA Framework...
🔄 Menjalankan migrasi database...
🌱 Membuat akun default...
✅ Setup selesai!
➡️  Login dengan:
   Admin: admin@loka.dev / admin123
   User : user@loka.dev / user123
🌐 Jalankan server: loka runserver
```

### 🔹 Menjalankan Server

```bash
loka runserver
```

Server akan start di: **http://127.0.0.1:8000**  
API Docs: **http://127.0.0.1:8000/docs**

### 🔹 Membuat Aplikasi Baru

```bash
loka new-app hr
```

Otomatis membuat folder `apps/hr/` dengan struktur:
- `model.py` - SQLAlchemy models
- `schema.py` - Pydantic schemas
- `api.py` - FastAPI endpoints

### 🔹 Membuat Model Baru

```bash
loka new-model employee "name:str age:int salary:float"
```

Otomatis generate:
- Model SQLAlchemy dengan field yang sesuai
- Schema Pydantic untuk validasi
- API endpoints (CRUD operations)

### 🔹 Database Migration

**Generate Migration:**
```bash
alembic revision --autogenerate -m "init_users"
```

**Apply Migration:**
```bash
alembic upgrade head
```

**Via CLI:**
```bash
loka migrate
```

### 🔹 Generate Dummy Data

```bash
loka seed hr employee --count 10
```

Menggunakan **Faker** untuk membuat data uji ke tabel `employees`.

### Complete Command Reference

| Command | Description |
|---------|-------------|
| `loka setup` | Setup awal framework (migration + seeding) |
| `loka runserver` | Jalankan FastAPI development server |
| `loka new-app <name>` | Buat aplikasi modular baru |
| `loka new-model <name> "fields"` | Generate model + schema + API |
| `loka migrate` | Jalankan migrasi database |
| `loka seed <app> <model> --count <n>` | Generate dummy data |
| `loka --help` | Tampilkan semua command |

---

## 🧩 6. Fitur Otentikasi (Auth Core)

**File:** `core/auth.py`

### Fitur Utama

- ✅ **JWT Authentication** - Bearer Token based
- ✅ **Password Hashing** - bcrypt via passlib
- ✅ **Role-based Access** - Admin / User roles
- ✅ **Auto Session** - OAuth2PasswordBearer
- ✅ **Secure by Default** - Password max 72 bytes (bcrypt limit)

### Fungsi Penting

| Function | Deskripsi |
|----------|-----------|
| `hash_password()` | Enkripsi password dengan bcrypt |
| `verify_password()` | Validasi password saat login |
| `create_access_token()` | Membuat JWT access token |
| `get_current_user()` | Validasi token user aktif |

### Default Accounts

Setelah `loka setup`, akun berikut otomatis tersedia:

| Role | Email | Password |
|------|-------|----------|
| **Admin** | admin@loka.dev | admin123 |
| **User** | user@loka.dev | user123 |

> 🔒 Password otomatis di-hash sebelum disimpan ke database.

---

## 🧱 7. Migrasi Database (Alembic)

### Generate Migration Baru

```bash
alembic revision --autogenerate -m "create users table"
```

### Apply Migration

```bash
alembic upgrade head
```

### Troubleshooting Migration

Jika muncul error **"Target database is not up to date"**, jalankan:

```bash
loka setup
```

Alembic akan otomatis memperbaiki versi schema dan update database.

### Migration History

```bash
alembic history
```

### Rollback Migration

```bash
alembic downgrade -1  # Rollback 1 step
```

---

## 💾 8. Seeder Otomatis

**File:** `core/cli.py`

Saat menjalankan `loka setup`, dua akun default akan otomatis ditambahkan:

```python
# Admin account
{
    "email": "admin@loka.dev",
    "password": "admin123",  # Auto-hashed
    "role": "admin"
}

# User account
{
    "email": "user@loka.dev",
    "password": "user123",  # Auto-hashed
    "role": "user"
}
```

Password otomatis di-hash menggunakan bcrypt sebelum disimpan.

---

## ⚠️ 9. Troubleshooting

| Masalah | Penyebab | Solusi |
|---------|----------|--------|
| `no such table: users` | Migrasi belum dijalankan | Jalankan `loka setup` ulang |
| `no such index: ix_employees_id` | Index belum ada saat upgrade | Abaikan, Alembic auto-create |
| `ValueError: password cannot be longer than 72 bytes` | Bcrypt limit | Sudah auto-truncate di `auth.py` |
| `Core Pydantic V1 incompatible with Python 3.14` | FastAPI belum support 3.14 | Gunakan Python 3.12 atau 3.11 |
| `Target database is not up to date` | Versi Alembic tidak sync | Jalankan `loka setup` |

### Debug Mode

Untuk melihat detail error, aktifkan debug mode di `core/config.py`:

```python
debug: bool = True
```

---

## 🧩 10. Dashboard & Role System

### 🚧 Coming Soon

Roadmap fitur berikut sedang dalam pengembangan:

- 🔐 **Web Login** - HTML interface dengan Tailwind CSS
- 🧑‍💼 **Role-based Dashboard** - Admin vs User views
- ⚙️ **Module Loader Dinamis** - Auto sidebar dari `apps/`
- 🌈 **UI Template Engine** - Jinja2 integration
- 🧩 **Plugin Installer** - CLI-based seperti ERPNext

---

## 💡 11. Filosofi Desain LOKA

LOKA dibangun dengan **3 prinsip utama**:

### 1️⃣ Modular by Design
Semua aplikasi adalah modul independen (mirip "apps" di Django).

```
apps/
├── hr/          # Human Resource module
├── sales/       # Sales module
└── inventory/   # Inventory module
```

### 2️⃣ CLI-first Developer Experience
Semua perintah (buat app, model, migrasi, seed, run) dilakukan via CLI.

```bash
loka new-app finance
loka new-model transaction "amount:float date:datetime"
loka seed finance transaction --count 50
```

### 3️⃣ Extensible like ERP
Struktur core memungkinkan pembuatan:
- Dashboard modular
- Role-based menu otomatis
- Plugin system
- Dynamic routing

---

## 🧰 12. Dependency Utama

| Package | Version | Deskripsi |
|---------|---------|-----------|
| **fastapi** | Latest | Framework utama API |
| **typer** | Latest | CLI interaktif (`loka` command) |
| **sqlalchemy** | 2.0+ | ORM untuk database |
| **alembic** | Latest | Database migration manager |
| **passlib[bcrypt]** | Latest | Password hashing |
| **python-jose** | Latest | JWT token generator |
| **pydantic** | v2 | Data validation |
| **faker** | Latest | Generator data dummy |
| **jinja2** | Latest | *(coming soon)* Template HTML engine |
| **uvicorn** | Latest | ASGI server |

### Install All Dependencies

```bash
pip install -r requirements.txt
```

---

## 🧭 13. Roadmap Fitur

### ✅ Sudah Tersedia

- ✅ CLI generation: `loka new-app`, `loka new-model`
- ✅ Auth core dengan JWT + bcrypt
- ✅ Auto seeding akun default
- ✅ Database auto migration
- ✅ Modular app structure
- ✅ Type-safe dengan Pydantic v2

### 🚧 Dalam Pengembangan

- 🚧 Dashboard HTML (login, redirect role)
- 🚧 CLI plugin manager
- 🚧 RESTful API autoloader
- 🚧 WebSocket support
- 🚧 Background task queue

### 📅 Rencana Masa Depan

- 📅 Plugin marketplace (`lokapack`)
- 📅 Admin panel generator
- 📅 GraphQL support
- 📅 Docker deployment templates
- 📅 Cloud deployment scripts

---

## 💬 14. Kontribusi

Kami menerima kontribusi dari siapa saja! 🎉

### Cara Berkontribusi

1. **Fork** repository ini
2. **Buat branch** baru untuk fitur kamu:
   ```bash
   git checkout -b feature/new-module
   ```
3. **Commit** perubahan:
   ```bash
   git commit -m "Add: new feature description"
   ```
4. **Push** ke branch:
   ```bash
   git push origin feature/new-module
   ```
5. **Buat Pull Request** di GitHub

### Development Guidelines

- ✅ Follow PEP 8 style guide
- ✅ Tambahkan tests untuk fitur baru
- ✅ Update dokumentasi jika diperlukan
- ✅ Gunakan commit message yang jelas
- ✅ Test sebelum push

---

## ❤️ 15. Lisensi

```
MIT License © 2025 IMOGI Dev Team
Developed by Muhamad Abisena Putrawan & JIP
```

**LOKA** - Lightweight Open-source Komputasi Aplikasi 🇮🇩

Released under the [MIT License](LICENSE) — feel free to use, modify, and distribute.

---

## 📞 Support & Community

- 🐛 **Issues:** [GitHub Issues](https://github.com/Abisena/loka-framework/issues)
- 💬 **Discussions:** [GitHub Discussions](https://github.com/Abisena/loka-framework/discussions)
- 📧 **Email:** support@loka.dev
- 📖 **Docs:** [docs.loka.dev](https://docs.loka.dev)

---

<div align="center">

**⭐ Star us on GitHub — bantu kami berkembang!**

Made with 🐍 Python | Built with ❤️ by Indonesian Developers

</div>