ecocyclehub-api / README.md
elvandry13's picture
refactor: edit readme
e257c55
|
Raw History Blame Contribute Delete
11.8 kB
---
title: Ecocyclehub Api
emoji: ♻️
colorFrom: indigo
colorTo: green
sdk: docker
app_port: 7860
pinned: false
license: mit
short_description: API EcoCycle Hub Dicoding Capstone Project
---
# EcoCycle Hub API
EcoCycle Hub API adalah backend REST API berbasis Django REST Framework untuk aplikasi pengelolaan sampah daur ulang. API ini mendukung autentikasi JWT, manajemen user berbasis role, kategori sampah, transaksi setoran sampah, saldo, poin, leaderboard, level gamification, dan dashboard untuk customer, officer, serta admin.
Repository ini disiapkan untuk berjalan sebagai **Hugging Face Docker Space**. Konfigurasi Space berada pada YAML front matter di bagian paling atas file ini.
## Fitur Utama
- Autentikasi menggunakan JWT access token dan refresh token.
- Registrasi user dengan role default `customer`.
- Role dan permission untuk `customer`, `officer`, `admin`, dan `superadmin`.
- CRUD kategori sampah beserta harga dan poin per kilogram.
- Pembuatan transaksi setoran sampah dengan banyak item kategori.
- Verifikasi dan penolakan transaksi oleh role yang berwenang.
- Perhitungan otomatis total berat, total harga, dan total poin transaksi.
- Saldo dan poin user yang terhubung dengan transaksi terverifikasi.
- Leaderboard dan level gamification.
- Dashboard API untuk customer, officer, dan admin.
- Dokumentasi OpenAPI/Swagger melalui `drf-spectacular`.
## Tech Stack
- Python 3.12
- Django 6.0
- Django REST Framework
- Simple JWT
- PostgreSQL
- Gunicorn
- WhiteNoise
- Docker
## Struktur Project
```text
.
+-- apps/
| +-- auths/ # register, login, refresh token, logout
| +-- balances/ # saldo user
| +-- categories/ # kategori sampah
| +-- dashboards/ # dashboard customer, officer, admin
| +-- gamification/ # leaderboard dan level
| +-- permissions/ # role dan permission
| +-- points/ # poin user
| +-- transactions/ # transaksi setoran sampah
| +-- users/ # custom user model
+-- common/ # helper response, pagination, exception
+-- core/ # settings, urls, asgi, wsgi
+-- Dockerfile
+-- gunicorn.conf.py
+-- manage.py
+-- requirements.txt
+-- README.md
```
## Environment Variables
Buat file `.env` untuk local development berdasarkan `.env.example`.
```env
DEBUG=True
SECRET_KEY=change-me
JWT_SECRET_KEY=change-me-too
DB_NAME=ecocyclehub
DB_USER=postgres
DB_PASSWORD=postgres
DB_HOST=localhost
DB_PORT=5432
```
Untuk production atau Hugging Face Spaces, set `DEBUG=False` dan gunakan secret yang kuat.
## Menjalankan Secara Lokal
1. Buat virtual environment.
```bash
python -m venv .venv
source .venv/bin/activate
```
Pada Windows PowerShell:
```powershell
.\.venv\Scripts\Activate.ps1
```
2. Install dependency.
```bash
pip install -r requirements.txt
```
3. Siapkan database PostgreSQL, lalu isi file `.env`.
4. Jalankan migrasi.
```bash
python manage.py migrate
```
5. Buat superuser jika diperlukan.
```bash
python manage.py createsuperuser
```
6. Jalankan development server.
```bash
python manage.py runserver
```
7. Buka dokumentasi API.
```text
http://127.0.0.1:8000/api/docs/
```
## Menjalankan Dengan Docker
Build image:
```bash
docker build -t ecocyclehub-api .
```
Run container:
```bash
docker run --env-file .env -p 7860:7860 ecocyclehub-api
```
Aplikasi akan berjalan di:
```text
http://localhost:7860/api/docs/
```
## Deployment ke Hugging Face Spaces
Project ini memakai Docker Space. Pastikan konfigurasi berikut tetap berada di bagian paling atas `README.md`:
```yaml
---
title: Ecocyclehub Api
emoji: ♻️
colorFrom: indigo
colorTo: green
sdk: docker
app_port: 7860
pinned: false
license: mit
short_description: API EcoCycle Hub Dicoding Capstone Project
---
```
Ketentuan penting untuk Hugging Face Docker Space:
- `sdk: docker` wajib ada agar Hugging Face membangun project memakai `Dockerfile`.
- `app_port: 7860` disamakan dengan `EXPOSE 7860` dan command Gunicorn di `Dockerfile`.
- Aplikasi harus bind ke `0.0.0.0:7860`; project ini sudah menjalankan `gunicorn core.wsgi:application --bind 0.0.0.0:7860`.
- Environment variables production perlu diisi melalui menu **Settings > Variables and secrets** di Space, bukan ditulis langsung di repository.
- Database PostgreSQL harus tersedia dari luar container karena Hugging Face Space tidak menyediakan PostgreSQL otomatis.
- Domain Space yang sudah diizinkan pada `ALLOWED_HOSTS` dan `CSRF_TRUSTED_ORIGINS` adalah:
```text
ecocyclehub-capstone-dicoding-ecocyclehub-api.hf.space
https://ecocyclehub-capstone-dicoding-ecocyclehub-api.hf.space
```
Jika nama Space berubah, update `ALLOWED_HOSTS` dan `CSRF_TRUSTED_ORIGINS` di `core/settings.py`.
### Variables and Secrets di Hugging Face
Tambahkan variable berikut di Hugging Face Spaces:
| Name | Contoh | Keterangan |
| --- | --- | --- |
| `DEBUG` | `False` | Matikan debug untuk deployment |
| `SECRET_KEY` | `your-django-secret-key` | Secret key Django |
| `JWT_SECRET_KEY` | `your-jwt-secret-key` | Signing key JWT |
| `DB_NAME` | `ecocyclehub` | Nama database PostgreSQL |
| `DB_USER` | `postgres` | User database |
| `DB_PASSWORD` | `secret` | Password database |
| `DB_HOST` | `your-db-host` | Host database |
| `DB_PORT` | `5432` | Port database |
## Dokumentasi API
Setelah aplikasi berjalan, buka:
```text
/api/docs/
```
Schema OpenAPI tersedia di:
```text
/api/schema/
```
Root path `/` otomatis redirect ke `/api/docs/`.
## Endpoint Utama
| Method | Endpoint | Deskripsi |
| --- | --- | --- |
| `POST` | `/api/auth/register/` | Registrasi user customer |
| `POST` | `/api/auth/login/` | Login dan mendapatkan token |
| `POST` | `/api/auth/refresh/` | Refresh access token |
| `POST` | `/api/auth/logout/` | Logout dan blacklist refresh token |
| `GET` | `/api/users/` | List user |
| `POST` | `/api/users/` | Buat user |
| `GET` | `/api/users/<uuid>/` | Detail user |
| `GET` | `/api/categories/` | List kategori |
| `POST` | `/api/categories/` | Buat kategori |
| `PUT/PATCH/DELETE` | `/api/categories/<uuid>/` | Update atau hapus kategori |
| `GET` | `/api/transactions/` | List transaksi milik user |
| `POST` | `/api/transactions/` | Buat transaksi |
| `POST` | `/api/transactions/<uuid>/verify/` | Verifikasi transaksi |
| `POST` | `/api/transactions/<uuid>/reject/` | Tolak transaksi |
| `GET` | `/api/transactions/all/` | Manajemen semua transaksi |
| `GET` | `/api/transactions/all/<uuid>/` | Detail transaksi untuk manajemen |
| `GET` | `/api/dashboard/customers/` | Dashboard customer |
| `GET` | `/api/dashboard/officer/` | Dashboard officer |
| `GET` | `/api/dashboard/admin/` | Dashboard admin |
| `GET` | `/api/gamification/leaderboard/` | Leaderboard |
| `GET/POST` | `/api/gamification/levels/` | List atau buat level |
| `GET/PUT/PATCH/DELETE` | `/api/gamification/levels/<uuid>/` | Detail, update, atau hapus level |
## Permission Matrix
Permission dicek melalui role user. User dengan `is_superuser=True` otomatis memiliki akses ke semua permission melalui `has_permission`.
| Permission Key | Customer | Officer | Admin | Superuser |
| --- | --- | --- | --- | --- |
| `view_categories` | Yes | Yes | Yes | Yes |
| `add_categories` | No | No | Yes | Yes |
| `edit_categories` | No | No | Yes | Yes |
| `delete_categories` | No | No | Yes | Yes |
| `create_transaction` | Yes | Yes | Yes | Yes |
| `view_transaction` | Yes | Yes | Yes | Yes |
| `view_all_transaction` | No | Yes | Yes | Yes |
| `verify_transaction` | No | Yes | Yes | Yes |
| `reject_transaction` | No | Yes | Yes | Yes |
| `view_customer_dashboard` | Yes | No | No | Yes |
| `view_officer_dashboard` | No | Yes | No | Yes |
| `view_admin_dashboard` | No | No | Yes | Yes |
| `view_leaderboard` | Yes | Yes | Yes | Yes |
| `view_level` | No | No | Yes | Yes |
| `add_level` | No | No | Yes | Yes |
| `edit_level` | No | No | Yes | Yes |
| `delete_level` | No | No | Yes | Yes |
| `view_user` | No | Yes | Yes | Yes |
| `add_user` | No | No | Yes | Yes |
| `edit_user` | No | No | Yes | Yes |
| `delete_user` | No | No | Yes | Yes |
Ringkasan akses per role:
- `customer`: membuat dan melihat transaksi milik sendiri, melihat kategori, leaderboard, dan dashboard customer.
- `officer`: melihat user, melihat semua transaksi, membuat transaksi, memverifikasi atau menolak transaksi, melihat kategori, leaderboard, dan dashboard officer.
- `admin`: mengelola user, kategori, transaksi, level gamification, leaderboard, dan dashboard admin.
- `superuser`: melewati seluruh pengecekan permission karena `is_superuser=True`.
## Transaction Status Flow
Status transaksi tersedia pada model `Transaction`:
| Status | Deskripsi |
| --- | --- |
| `pending` | Status awal setelah transaksi dibuat oleh customer, officer, atau admin yang memiliki permission `create_transaction`. |
| `verified` | Status akhir ketika transaksi disetujui oleh officer atau admin yang memiliki permission `verify_transaction`. |
| `rejected` | Status akhir ketika transaksi ditolak oleh officer atau admin yang memiliki permission `reject_transaction`. |
Alur transisi:
```text
pending
+-- verify --> verified
+-- reject --> rejected
verified --> tidak bisa diverifikasi ulang atau ditolak
rejected --> tidak bisa diverifikasi atau ditolak ulang
```
Efek setiap transisi:
- Saat transaksi dibuat, sistem menghitung `total_weight`, `total_price`, dan `total_points` dari item kategori yang dikirim.
- Saat transaksi menjadi `verified`, sistem mengisi `handled_by`, `verified_by`, dan `verified_at`, lalu menambahkan `total_price` ke saldo user serta `total_points` ke poin user.
- Saat transaksi menjadi `rejected`, sistem mengisi `handled_by`, `rejected_by`, dan `rejected_at`. Saldo dan poin user tidak bertambah.
- Endpoint manajemen transaksi mendukung filter status melalui query string, contoh: `/api/transactions/all/?status=pending`.
## Contoh Request
Login:
```bash
curl -X POST http://127.0.0.1:8000/api/auth/login/ \
-H "Content-Type: application/json" \
-d '{"email":"user@mail.com","password":"your-password"}'
```
Mengakses endpoint yang membutuhkan autentikasi:
```bash
curl http://127.0.0.1:8000/api/categories/ \
-H "Authorization: Bearer <access_token>"
```
Membuat transaksi:
```bash
curl -X POST http://127.0.0.1:8000/api/transactions/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access_token>" \
-d '{
"items": [
{
"category_id": "category-uuid",
"weight": 2.5
}
]
}'
```
## Data Seed
Migrasi project akan membuat data awal berikut:
- Role: `customer`, `officer`, `admin`, `superadmin`.
- Kategori sampah awal seperti `Kertas`, `Plastik PET`, `Kaleng Aluminium`, `Besi`, `Kaca`, dan lainnya.
- Level gamification mulai dari `Seedling` sampai `Zero Waste Champion`.
- User seed:
| Name | Email | Role | Catatan |
| --- | --- | --- | --- |
| Customer | `customer@mail.com` | `customer` | Password tidak diset |
| Officer | `officer@mail.com` | `officer` | Password tidak diset |
| Admin | `admin@mail.com` | `admin` | Password tidak diset |
User seed dibuat tanpa password login. Gunakan endpoint register atau `createsuperuser` untuk membuat akun yang bisa digunakan.
## Menjalankan Test
```bash
python manage.py test
```
## Catatan Production
- Jangan commit file `.env`.
- Gunakan secret berbeda untuk `SECRET_KEY` dan `JWT_SECRET_KEY`.
- Pastikan database PostgreSQL mendukung koneksi SSL karena konfigurasi database menggunakan `sslmode=require`.
- Setelah mengganti domain Hugging Face Space, sesuaikan `ALLOWED_HOSTS` dan `CSRF_TRUSTED_ORIGINS`.
- Static files dikumpulkan saat build Docker melalui `python manage.py collectstatic --noinput`.
## Lisensi
Project ini menggunakan lisensi MIT.