update fuction filter

This commit is contained in:
2025-09-10 09:16:01 +07:00
parent 79e65494df
commit e61eee5f76
7 changed files with 1458 additions and 564 deletions

678
README.md
View File

@@ -1,313 +1,523 @@
# 🚀 API Service Guide
## 📖 Introduction
This API service is designed to provide a robust backend for managing products, orders, and user authentication. It integrates with BPJS for health insurance services and offers a comprehensive set of features for developers.
# 🚀 API Service - Clean Architecture
## 🌟 Features
- User authentication with JWT
- CRUD operations for products and orders
- Integration with BPJS services
- Swagger documentation for easy API testing
- Docker support for easy deployment
> **Layanan API modern dengan arsitektur bersih untuk manajemen produk, pesanan, dan otentikasi pengguna**
## 📋 Quick Start (5 Menit)
## 📑 Daftar Isi
### 1. Setup Environment
```bash
git clone <repository-url>
cd api-service
cp .env.example .env
- [✨ Fitur Utama](#-fitur-utama)
- [🏗️ Arsitektur](#%EF%B8%8F-arsitektur)
- [⚡ Quick Start](#-quick-start)
- [🔐 Autentikasi](#-autentikasi)
- [📊 API Endpoints](#-api-endpoints)
- [🛠️ Development](#%EF%B8%8F-development)
- [🚀 Deployment](#-deployment)
- [📚 Dokumentasi](#-dokumentasi)
***
## ✨ Fitur Utama
### Core Features
- **🔒 JWT Authentication** - Sistem autentikasi yang aman
- **📦 CRUD Operations** - Operasi lengkap untuk produk dan pesanan
- **🏥 BPJS Integration** - Integrasi dengan layanan kesehatan BPJS
- **🩺 FHIR/SATUSEHAT** - Dukungan standar kesehatan internasional
- **📖 API Documentation** - Swagger/OpenAPI yang interaktif
### Developer Experience
- **🔥 Hot Reload** - Development dengan auto-restart
- **🐳 Docker Ready** - Deployment yang mudah
- **⚡ Code Generator** - Buat handler dan model otomatis
- **🧪 Testing Suite** - Unit dan integration tests
- **📊 Health Monitoring** - Monitoring kesehatan aplikasi
***
## 🏗️ Arsitektur
### Clean Architecture Layers
```
┌─────────────────────────────────────┐
│ Presentation Layer │ ← handlers/, routes/
├─────────────────────────────────────┤
│ Application Layer │ ← middleware/, validators/
├─────────────────────────────────────┤
│ Domain Layer │ ← models/, interfaces/
├─────────────────────────────────────┤
│ Infrastructure Layer │ ← database/, external APIs
└─────────────────────────────────────┘
```
### 2. Jalankan Database & API
```bash
# Opsi A: Docker (Rekomendasi)
make docker-run
# Opsi B: Manual
go mod download
go run cmd/api/main.go
```
### 3. Akses API
- **API**: http://localhost:8080/api/v1
- **Swagger**: http://localhost:8080/swagger/index.html
- **Health Check**: http://localhost:8080/api/v1/health
## 🏗️ Struktur Project
### Struktur Project
```
api-service/
├── cmd/api/main.go # Entry point
├── internal/ # Core business logic
│ ├── handlers/ # HTTP controllers
│ ├── models/ # Data structures
│ ├── middleware/ # Auth & error handling
── routes/ # API routes
├── tools/ # CLI generators
└── docs/ # API documentation
├── 📁 cmd/
│ └── api/main.go # 🚪 Entry point aplikasi
├── 📁 internal/ # 🏠 Core business logic
│ ├── handlers/ # 🎮 HTTP controllers (Presentation)
│ ├── middleware/ # 🛡️ Auth & validation (Application)
── models/ # 📊 Data structures (Domain)
│ ├── routes/ # 🛣️ API routing (Presentation)
│ ├── services/ # 💼 Business logic (Application)
│ └── repository/ # 💾 Data access (Infrastructure)
├── 📁 tools/ # 🔧 Development tools
│ ├── general/ # 🎯 General generators
│ ├── bpjs/ # 🏥 BPJS specific tools
│ └── satusehat/ # 🩺 SATUSEHAT tools
├── 📁 docs/ # 📚 Documentation
├── 📁 configs/ # ⚙️ Configuration files
└── 📁 scripts/ # 📜 Automation scripts
```
## 🔐 Authentication
### Login (Dapatkan Token)
***
## ⚡ Quick Start
### 1⃣ Setup Environment (2 menit)
```bash
# Clone repository
git clone <repository-url>
cd api-service
# Setup environment
cp .env.example .env
```
### 2⃣ Pilih Method Setup
**🐳 Docker (Recommended)**
```bash
make docker-run
```
**🔧 Manual Setup**
```bash
# Install dependencies
go mod download
# Run database migrations
make migrate-up
# Start server
go run cmd/api/main.go
```
### 3⃣ Verify Installation
| Service | URL | Status |
| :-- | :-- | :-- |
| **API** | http://localhost:8080/api/v1 | ✅ |
| **Swagger** | http://localhost:8080/swagger/index.html | 📖 |
| **Health Check** | http://localhost:8080/api/v1/health | 💚 |
***
## 🔐 Autentikasi
### Login \& Mendapatkan Token
```bash
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"password"}'
-d '{
"username": "admin",
"password": "password"
}'
```
### Gunakan Token
**Response:**
```json
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"expires_in": 3600,
"user": {
"id": "123",
"username": "admin",
"role": "admin"
}
}
```
### Menggunakan Token
```bash
curl -X GET http://localhost:8080/api/v1/products \
-H "Authorization: Bearer <your-token>"
```
### Demo Users
| Username | Password | Role |
|----------|----------|------|
| admin | password | admin |
| user | password | user |
## 🛠️ Generate Handler Baru (30 Detik)
### Demo Accounts
### Cara Cepat
```bash
# Windows
tools/generate.bat product get post put delete
| Username | Password | Role | Akses |
| :-- | :-- | :-- | :-- |
| `admin` | `password` | Admin | Semua endpoint |
| `user` | `password` | User | Read-only |
# Linux/Mac
./tools/generate.sh product get post put delete
# Atau langsung dengan Go
go run tools/general/generate-handler.go orders get post
go run tools/general/generate-handler.go orders/product get post
go run tools/general/generate-handler.go orders/order get post put delete dynamic search stats
go run tools/bpjs/generate-bpjs-handler.go reference/peserta get
# 1. Test generate satu service
go run tools/bpjs/generate-handler.go services-config-bpjs.yaml vclaim
# 2. Test generate semua service
go run tools/bpjs/generate-handler.go services-config-bpjs.yaml
go run tools/satusehat/generate-satusehat-handler.go services-config-satusehat.yaml patient
```
### Method Tersedia
- `get` - Ambil data
- `post` - Buat data baru
- `put` - Update data
- `delete` - Hapus data
### Hasil Generate
- **Handler**: `internal/handlers/product/product.go`
- **Models**: `internal/models/product/product.go`
- **Routes**: Otomatis ditambahkan ke `/api/v1/products`
***
## 📊 API Endpoints
### Public (Tanpa Auth)
- `POST /api/v1/auth/login` - Login
- `POST /api/v1/auth/register` - Register
- `GET /api/v1/health` - Health check
### 🌍 Public Endpoints
### Protected (Dengan Auth)
- `GET /api/v1/auth/me` - Profile user
- `GET /api/v1/products` - List products
- `POST /api/v1/products` - Create product
- `GET /api/v1/products/:id` - Detail product
- `PUT /api/v1/products/:id` - Update product
- `DELETE /api/v1/products/:id` - Delete product
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `POST` | `/api/v1/auth/login` | Login pengguna |
| `POST` | `/api/v1/auth/register` | Registrasi pengguna baru |
| `GET` | `/api/v1/health` | Status kesehatan API |
GET /api/v1/retribusi/dynamic
GET /api/v1/retribusi/dynamic?fields=Jenis,Pelayanan,Dinas,Tarif
GET /api/v1/retribusi/dynamic?filter[status][_eq]=active
### 🔒 Protected Endpoints
#### User Management
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/auth/me` | Profile pengguna |
| `PUT` | `/api/v1/auth/me` | Update profile |
#### Product Management
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/products` | List semua produk |
| `POST` | `/api/v1/products` | Buat produk baru |
| `GET` | `/api/v1/products/:id` | Detail produk |
| `PUT` | `/api/v1/products/:id` | Update produk |
| `DELETE` | `/api/v1/products/:id` | Hapus produk |
#### Dynamic Query (Advanced)
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/retribusi/dynamic` | Query dengan filter dinamis |
**Contoh Query:**
```bash
# Filter berdasarkan jenis
GET /api/v1/retribusi/dynamic?filter[Jenis][_eq]=RETRIBUSI PELAYANAN KESEHATAN
GET /api/v1/retribusi/dynamic?filter[status][_eq]=active&filter[Jenis][_contains]=KESEHATAN
GET /api/v1/retribusi/dynamic?filter[_or][0][Jenis][_contains]=KESEHATAN&filter[_or][1][Jenis][_contains]=PENDIDIKAN
GET /api/v1/retribusi/dynamic?filter[date_created][_gte]=2024-01-01&filter[date_created][_lte]=2024-12-31
GET /api/v1/retribusi/dynamic?filter[Jenis][_contains]=KESEHATAN&filter[Pelayanan][_contains]=RUMAH SAKIT
GET /api/v1/retribusi/dynamic?limit=10&offset=20
GET /api/v1/retribusi/dynamic?filter[status][_neq]=deleted&filter[Tarif][_gt]=100000&filter[Jenis][_contains]=KESEHATAN&sort=-date_created&limit=50
GET /api/v1/retribusi/dynamic?filter[Dinas][_eq]=DINAS KESEHATAN
GET /api/v1/retribusi/dynamic?filter[Kode_tarif][_contains]=RS
GET /api/v1/retribusi/dynamic?filter[date_created][_gte]=2024-01-15&filter[date_created][_lt]=2024-01-16
GET /api/v1/retribusi/dynamic?filter[Uraian_1][_contains]=RAWAT INAP
Available Filter Operators
_eq - Equal
_neq - Not equal
_lt - Less than
_lte - Less than or equal
_gt - Greater than
_gte - Greater than or equal
_contains - Contains (case-insensitive)
_ncontains - Not contains
_starts_with - Starts with
_ends_with - Ends with
_in - In array
_nin - Not in array
_null - Is null
_nnull - Is not null
Available Fields for Filtering
id - Record ID
status - Status (active, draft, inactive, deleted)
Jenis - Type of retribution
Pelayanan - Service type
Dinas - Department
Kelompok_obyek - Object group
Kode_tarif - Tariff code
Tarif - Tariff amount
Satuan - Unit
Tarif_overtime - Overtime tariff
Satuan_overtime - Overtime unit
Rekening_pokok - Main account
Rekening_denda - Penalty account
Uraian_1, Uraian_2, Uraian_3 - Descriptions
date_created - Creation date
date_updated - Update date
user_created - Created by user
user_updated - Updated by user
Response Format
The endpoint returns data in this format:
# Kombinasi filter
GET /api/v1/retribusi/dynamic?filter[status][_eq]=active&filter[Tarif][_gt]=100000
{
"message": "Data retribusi berhasil diambil",
"data": [
{
"id": "uuid",
"status": "active",
"Jenis": "RETRIBUSI PELAYANAN KESEHATAN",
"Pelayanan": "RAWAT INAP",
"Dinas": "DINAS KESEHATAN",
"Tarif": 150000,
"date_created": "2024-01-15T10:30:00Z"
// ... other fields
}
],
"meta": {
"limit": 10,
"offset": 0,
"total": 150,
"total_pages": 15,
"current_page": 1,
"has_next": true,
"has_prev": false
}
}
## 🧪 Development Workflow
### Perintah Penting
```bash
make watch # Jalankan dengan hot reload
make test # Unit tests
make itest # Integration tests
make all # Semua tests
make build # Build production
# Pagination dan sorting
GET /api/v1/retribusi/dynamic?sort=-date_created&limit=10&offset=20
```
### Update Swagger
### 🏥 BPJS Integration
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/bpjs/peserta/:no` | Data peserta BPJS |
| `GET` | `/api/v1/bpjs/rujukan/:no` | Data rujukan |
### 🩺 SATUSEHAT Integration
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/satusehat/patient/:id` | Data pasien |
| `POST` | `/api/v1/satusehat/encounter` | Buat encounter baru |
***
## 🛠️ Development
### Code Generation (30 detik)
**🎯 Generate CRUD Lengkap**
```bash
swag init -g cmd/api/main.go --parseDependency --parseInternal # Alternative Kedua
swag init -g cmd/api/main.go -o docs/
# Generate handler untuk entity baru
go run tools/general/generate-handler.go product get post put delete
# Generate dengan fitur advanced
go run tools/general/generate-handler.go orders get post put delete dynamic search stats
```
## 🔧 Environment Variables
**🏥 Generate BPJS Handler**
### Database
```bash
# Single service
go run tools/bpjs/generate-bpjs-handler.go reference/peserta get
# Semua service dari config
go run tools/bpjs/generate-handler.go services-config-bpjs.yaml
```
**🩺 Generate SATUSEHAT Handler**
```bash
go run tools/satusehat/generate-satusehat-handler.go services-config-satusehat.yaml patient
```
### Development Commands
```bash
# 🔥 Development dengan hot reload
make watch
# 🧪 Testing
make test # Unit tests
make itest # Integration tests
make test-all # Semua tests
# 📖 Update dokumentasi
make docs # Generate Swagger docs
# 🔍 Code quality
make lint # Linting
make format # Format code
```
### Environment Configuration
**📁 .env File:**
```bash
# Database
BLUEPRINT_DB_HOST=localhost
BLUEPRINT_DB_PORT=5432
BLUEPRINT_DB_USERNAME=postgres
BLUEPRINT_DB_PASSWORD=postgres
BLUEPRINT_DB_DATABASE=api_service
# JWT
JWT_SECRET=your-super-secret-key-change-in-production
# External APIs
BPJS_BASE_URL=https://api.bpjs-kesehatan.go.id
SATUSEHAT_BASE_URL=https://api.satusehat.kemkes.go.id
# Application
APP_ENV=development
APP_PORT=8080
LOG_LEVEL=debug
```
### JWT Secret
***
## 🚀 Deployment
### 🐳 Docker Deployment
**Development:**
```bash
JWT_SECRET=your-secret-key-change-this-in-production
# Start semua services
make docker-run
# Stop services
make docker-down
# Rebuild dan restart
make docker-rebuild
```
## 🐳 Docker Commands
**Production:**
### Development
```bash
make docker-run # Jalankan semua services
docker-compose down # Stop services
```
### Production
```bash
# Build production image
docker build -t api-service:prod .
docker run -d -p 8080:8080 --env-file .env api-service:prod
# Run production container
docker run -d \
--name api-service \
-p 8080:8080 \
--env-file .env.prod \
api-service:prod
```
## 🎯 Tips Cepat
### 1. Generate CRUD Lengkap
### 🔧 Manual Deployment
```bash
go run tools/generate-handler.go user get post put delete
# Build aplikasi
make build
# Run migrations
./scripts/migrate.sh up
# Start server
./bin/api-service
```
### 2. Test API dengan Swagger
1. Buka http://localhost:8080/swagger/index.html
2. Login untuk dapat token
3. Klik "Authorize" dan masukkan token
4. Test semua endpoint
### 3. Debug Database
- **pgAdmin**: http://localhost:5050
- **Database**: api_service
- **User/Pass**: postgres/postgres
***
## 🚨 Troubleshooting
## 📚 Dokumentasi
### Generate Handler Gagal
- Pastikan di root project
- Cek file `internal/routes/v1/routes.go` ada
- Pastikan permission write
### 📖 Interactive API Documentation
### Database Connection Error
- Cek PostgreSQL running
- Verifikasi .env configuration
- Gunakan `make docker-run` untuk setup otomatis
Kunjungi **Swagger UI** di: http://localhost:8080/swagger/index.html
### Token Invalid
- Login ulang untuk dapat token baru
- Token expire dalam 1 jam
- Pastikan format: `Bearer <token>`
**Cara menggunakan:**
## 📱 Contoh Integrasi Frontend
1. 🔑 Login melalui `/auth/login` endpoint
2. 📋 Copy token dari response
3. 🔓 Klik tombol "Authorize" di Swagger
4. 📝 Masukkan: `Bearer <your-token>`
5. ✅ Test semua endpoint yang tersedia
### 🧪 Testing Examples
**JavaScript/Axios:**
### JavaScript/Axios
```javascript
// Login
const login = await axios.post('/api/v1/auth/login', {
// Login dan set token
const auth = await axios.post('/api/v1/auth/login', {
username: 'admin',
password: 'password'
});
// Set token
axios.defaults.headers.common['Authorization'] =
`Bearer ${login.data.access_token}`;
`Bearer ${auth.data.access_token}`;
// Get data
// Fetch data
const products = await axios.get('/api/v1/products');
console.log(products.data);
```
## 🎉 Next Steps
1. ✅ Setup environment selesai
2. ✅ Generate handler pertama
3. ✅ Test dengan Swagger
4. 🔄 Tambahkan business logic
5. 🔄 Deploy ke production
**cURL Examples:**
```bash
# Login
TOKEN=$(curl -s -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"password"}' | jq -r '.access_token')
# Use token
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/products
```
### 🔍 Health Monitoring
```bash
# Basic health check
curl http://localhost:8080/api/v1/health
# Detailed system info
curl http://localhost:8080/api/v1/health/detailed
```
**Response:**
```json
{
"status": "healthy",
"timestamp": "2025-09-10T05:39:00Z",
"services": {
"database": "connected",
"bpjs_api": "accessible",
"satusehat_api": "accessible"
},
"version": "1.0.0"
}
```
***
## 🚨 Troubleshooting
### Masalah Umum
**❌ Database Connection Error**
```bash
# Cek status PostgreSQL
make db-status
# Reset database
make db-reset
# Check logs
make logs-db
```
**❌ Generate Handler Gagal**
- ✅ Pastikan berada di root project
- ✅ Cek permission write di folder `internal/`
- ✅ Verifikasi file `internal/routes/v1/routes.go` exists
**❌ Token Invalid/Expired**
- 🔄 Login ulang untuk mendapatkan token baru
- ⏰ Token expire dalam 1 jam (configurable)
- 📝 Format harus: `Bearer <token>`
**❌ Import Error saat Generate**
- 🧹 Jalankan: `go mod tidy`
- 🔄 Restart development server
- 📝 Cek format import di generated files
### Debug Mode
```bash
# Enable debug logging
export LOG_LEVEL=debug
# Run dengan verbose output
make run-debug
# Monitor performance
make monitor
```
***
## 🎯 Next Steps
### 📋 Development Roadmap
- [ ]**Setup environment selesai**
- [ ]**Generate handler pertama**
- [ ]**Test dengan Swagger**
- [ ] 🔄 **Implementasi business logic**
- [ ] 🔄 **Tambahkan unit tests**
- [ ] 🔄 **Setup CI/CD pipeline**
- [ ] 🔄 **Deploy ke production**
### 🚀 Advanced Features
- **📊 Monitoring \& Observability**
- **🔒 Enhanced Security (Rate limiting, CORS)**
- **📈 Performance Optimization**
- **🌐 Multi-language Support**
- **📱 Mobile SDK Integration**
***
**⚡ Total setup time: 5 menit | 🔧 Generate CRUD: 30 detik | 🧪 Testing: Langsung via Swagger**
> **💡 Pro Tip:** Gunakan `make help` untuk melihat semua command yang tersedia
***
---
**Total waktu setup: 5 menit** | **Generate CRUD: 30 detik** | **Testing: Langsung di Swagger**