Files
api_antrean/README.md
meninjar 6d71e408bc README
2025-11-03 06:43:31 +00:00

589 lines
14 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 🚀 API Service - Sistem Manajemen Pasien
> **Sistem manajemen pasien modern dengan arsitektur bersih untuk pengelolaan data kesehatan dan integrasi layanan kesehatan**
## 📑 Daftar Isi
- [✨ Fitur Utama](#-fitur-utama)
- [🏗️ Arsitektur](#-arsitektur)
- [⚡ Quick Start](#-quick-start)
- [🔐 Autentikasi](#-autentikasi)
- [📊 API Endpoints](#-api-endpoints)
- [🛠️ Development](#-development)
- [🚀 Deployment](#-deployment)
- [📚 Dokumentasi](#-dokumentasi)
- [🚨 Troubleshooting](#-troubleshooting)
***
## ✨ Fitur Utama
### Core Features
- **🔒 JWT Authentication** - Sistem autentikasi dengan Keycloak integration
- **👥 Patient Management** - CRUD lengkap untuk data pasien
- **🔍 Dynamic Filtering** - Filter dan pencarian data pasien secara dinamis
- **📊 Advanced Search** - Pencarian dengan multiple fields dan operators
- **🏥 BPJS Integration** - Integrasi dengan layanan kesehatan BPJS
- **🩺 SATUSEHAT Integration** - Integrasi dengan platform kesehatan SATUSEHAT
- **📖 API Documentation** - Swagger/OpenAPI yang interaktif
### Developer Experience
- **🔥 Hot Reload** - Development dengan auto-restart
- **🐳 Docker Ready** - Deployment yang mudah
- **⚡ Code Generator** - Tools untuk generate handler dan model
- **🧪 Testing Suite** - Unit dan integration tests
- **📊 Health Monitoring** - Monitoring kesehatan aplikasi
- **🗄️ Multi Database** - Support PostgreSQL, MySQL, dan MongoDB
***
## 🏗️ Arsitektur
### Clean Architecture Layers
```
┌─────────────────────────────────────┐
│ Presentation Layer │ ← handlers/, routes/
├─────────────────────────────────────┤
│ Application Layer │ ← middleware/, services/
├─────────────────────────────────────┤
│ Domain Layer │ ← models/, validation/
├─────────────────────────────────────┤
│ Infrastructure Layer │ ← database/, external APIs
└─────────────────────────────────────┘
```
### Struktur Project
```
api-service/
├── 📁 cmd/ # Entry points aplikasi
│ ├── api/main.go # API server
│ └── logging/main.go # Logging service
├── 📁 internal/ # Core business logic
│ ├── config/ # Configuration management
│ ├── database/ # Database connections
│ ├── handlers/ # HTTP controllers
│ │ ├── auth/ # Authentication handlers
│ │ ├── healthcheck/ # Health check handlers
│ │ └── pasien/ # Pasien handlers
│ ├── middleware/ # Auth & validation middleware
│ ├── models/ # Data structures
│ │ ├── auth/ # Auth models
│ │ └── pasien/ # Pasien models
│ ├── routes/ # API routing
│ ├── services/ # Business logic services
│ │ └── auth/ # Auth services
│ ├── utils/ # Utility functions
│ │ ├── filters/ # Dynamic filtering
│ │ └── validation/ # Data validation
│ └── server/ # HTTP server setup
├── 📁 docs/ # Documentation
├── 📁 examples/ # Example files
├── 📁 scripts/ # Automation scripts
└── 📁 tools/ # Development tools
```
***
## ⚡ Quick Start
### 1⃣ Setup Environment (2 menit)
```bash
# Clone repository
git clone <repository-url>
cd api-service
# Setup environment
cp example.env .env
```
### 2⃣ Pilih Method Setup
**🐳 Docker (Recommended)**
```bash
make docker-run
```
**🔧 Manual Setup**
```bash
# Install dependencies
go mod download
# Start server
go run cmd/api/main.go
```
### 3⃣ Update Swagger Documentation
```bash
swag init -g cmd/api/main.go -o docs/
```
### 4⃣ Verify Installation
| Service | URL | Status |
| :-- | :-- | :-- |
| **API** | http://localhost:8080/api/v1 | ✅ |
| **Swagger** | http://localhost:8080/swagger/index.html | 📖 |
| **Health Check** | http://localhost:8080/api/sistem/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"
}'
```
**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/pasien \
-H "Authorization: Bearer <your-token>"
```
### Demo Accounts
| Username | Password | Role | Akses |
| :-- | :-- | :-- | :-- |
| `admin` | `password` | Admin | Semua endpoint |
| `dokter` | `password` | Dokter | Akses terbatas |
| `perawat` | `password` | Perawat | Read-only |
***
## 📊 API Endpoints
### 🌍 Public Endpoints
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `POST` | `/api/v1/auth/login` | Login pengguna |
| `POST` | `/api/v1/auth/register` | Registrasi pengguna baru |
| `GET` | `/api/sistem/health` | Status kesehatan API |
| `GET` | `/api/sistem/info` | Informasi sistem |
### 🔒 Protected Endpoints
#### System Information
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/sistem/databases` | Informasi database connections |
#### Patient Management
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/pasien` | List semua pasien dengan pagination |
| `GET` | `/api/v1/pasien/dynamic` | Query pasien dengan filter dinamis |
| `GET` | `/api/v1/pasien/search` | Pencarian pasien advanced |
| `GET` | `/api/v1/pasien/id/:id` | Detail pasien by ID |
| `GET` | `/api/v1/pasien/nik/:nik` | Detail pasien by NIK |
| `POST` | `/api/v1/pasien` | Buat pasien baru |
| `PUT` | `/api/v1/pasien/id/:id` | Update data pasien |
| `DELETE` | `/api/v1/pasien/id/:id` | Hapus data pasien (soft delete) |
#### Medical Records
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/pasien/:id/medical-records` | Riwayat medis pasien |
| `POST` | `/api/v1/pasien/:id/medical-records` | Tambah rekam medis |
| `GET` | `/api/v1/pasien/:id/medical-records/:recordId` | Detail rekam medis |
#### Dynamic Query Examples
**Filter berdasarkan jenis kelamin:**
```bash
GET /api/v1/pasien/dynamic?filter[jenis_kelamin][_eq]=L
```
**Kombinasi filter:**
```bash
GET /api/v1/pasien/dynamic?filter[status][_eq]=active&filter[umur][_gt]=18
```
**Pagination dan sorting:**
```bash
GET /api/v1/pasien/dynamic?sort=-tanggal_daftar&limit=10&offset=20
```
**Advanced search:**
```bash
GET /api/v1/pasien/search?q=andi&limit=20&offset=0
```
### 🏥 External Integrations
#### BPJS Integration
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/bpjs/peserta/:no` | Data peserta BPJS |
| `GET` | `/api/v1/bpjs/rujukan/:no` | Data rujukan |
| `POST` | `/api/v1/bpjs/rujukan` | Buat rujukan baru |
#### SATUSEHAT Integration
| Method | Endpoint | Deskripsi |
| :-- | :-- | :-- |
| `GET` | `/api/v1/satusehat/patient/:id` | Data pasien SATUSEHAT |
| `POST` | `/api/v1/satusehat/patient` | Buat pasien di SATUSEHAT |
| `GET` | `/api/v1/satusehat/encounter/:id` | Data kunjungan |
| `POST` | `/api/v1/satusehat/encounter` | Buat kunjungan baru |
***
## 🛠️ Development
### Development Commands
```bash
# 🔥 Development dengan hot reload
make watch
# 🏃 Run server
make run
# 🧪 Testing
make test # Unit tests
make itest # Integration tests
# 🐳 Docker operations
make docker-run # Start all services
make docker-down # Stop all services
# 🔍 Code quality
make build # Build application
make clean # Clean build artifacts
```
### Environment Configuration
**📁 .env File:**
```bash
# Server Configuration
PORT=8080
GIN_MODE=debug
# Database Configuration
DB_CONNECTION=postgres
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=postgres
DB_DATABASE=api_service
# PostgreSQL Satudata Database
POSTGRES_SATUDATA_CONNECTION=postgres
POSTGRES_SATUDATA_HOST=localhost
POSTGRES_SATUDATA_PORT=5432
POSTGRES_SATUDATA_USERNAME=postgres
POSTGRES_SATUDATA_PASSWORD=postgres
POSTGRES_SATUDATA_DATABASE=satu_db
# MongoDB Configuration
MONGODB_MONGOHL7_CONNECTION=mongodb
MONGODB_MONGOHL7_HOST=localhost
MONGODB_MONGOHL7_PORT=27017
MONGODB_MONGOHL7_USER=admin
MONGODB_MONGOHL7_PASS=password
# MySQL Medical Database
MYSQL_MEDICAL_CONNECTION=mysql
MYSQL_MEDICAL_HOST=localhost
MYSQL_MEDICAL_PORT=3306
MYSQL_MEDICAL_USERNAME=user
MYSQL_MEDICAL_PASSWORD=password
MYSQL_MEDICAL_DATABASE=healtcare_database
# JWT Configuration
JWT_SECRET=your-super-secret-key-change-in-production
# Keycloak Configuration
KEYCLOAK_ISSUER=https://auth.rssa.top/realms/sandbox
KEYCLOAK_AUDIENCE=nuxtsim-pendaftaran
KEYCLOAK_JWKS_URL=https://auth.rssa.top/realms/sandbox/protocol/openid-connect/certs
KEYCLOAK_ENABLED=true
# BPJS Configuration
BPJS_BASEURL=https://apijkn.bpjs-kesehatan.go.id/vclaim-dev
BPJS_CONSID=52667757
BPJS_USERKEY=4cf1cbef811314fvdgrc008440bbe9ef9ba789e482
BPJS_SECRETKEY=1bV36ASDQQ3512D
# SATUSEHAT Configuration
SATUSEHAT_BASEURL=https://api-satusehat.kemkes.go.id/fhir-r4/v1
SATUSEHAT_CLIENT_ID=your-client-id
SATUSEHAT_CLIENT_SECRET=your-client-secret
```
### Code Generation
**Generate Handler untuk Pasien:**
```bash
# Config
go run tools/general/generate-handler.go --config tools/general/services-config.yaml --verbose
```
***
## 🚀 Deployment
### 🐳 Docker Deployment
**Development:**
```bash
# Start semua services
make docker-run
# Stop services
make docker-down
```
**Production:**
```bash
# Build production image
docker build -t api-service:prod .
# Run production container
docker run -d \
--name api-service \
-p 8080:8080 \
--env-file .env.prod \
api-service:prod
```
### 🔧 Manual Deployment
```bash
# Build aplikasi
make build
# Start server
./main
```
### 📋 Environment Variables untuk Production
```bash
# Server Configuration
APP_ENV=production
PORT=8080
GIN_MODE=release
# Database Configuration
DB_CONNECTION=postgres
DB_HOST=10.10.123.165
DB_PORT=5432
DB_USERNAME=stim
DB_PASSWORD=stim*RS54
DB_DATABASE=satu_db
# Security
JWT_SECRET=your-production-secret-key
KEYCLOAK_ENABLED=true
# External Services
BPJS_BASEURL=https://apijkn.bpjs-kesehatan.go.id/vclaim-rest
SATUSEHAT_BASEURL=https://api-satusehat.kemkes.go.id/fhir-r4/v1
```
***
## 📚 Dokumentasi
### 📖 Interactive API Documentation
Kunjungi **Swagger UI** di: http://localhost:8080/swagger/index.html
**Cara menggunakan:**
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
// Login dan set token
const auth = await axios.post('/api/v1/auth/login', {
username: 'admin',
password: 'password'
});
axios.defaults.headers.common['Authorization'] =
`Bearer ${auth.data.access_token}`;
// Fetch patient data
const patients = await axios.get('/api/v1/pasien');
console.log(patients.data);
// Create new patient
const newPatient = await axios.post('/api/v1/pasien', {
nama: "John Doe",
nik: "1234567890123456",
tanggal_lahir: "1990-01-01",
jenis_kelamin: "L",
alamat: "Jl. Contoh No. 123"
});
```
**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')
# Get patient data
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/pasien
# Dynamic filtering
curl -H "Authorization: Bearer $TOKEN" \
"http://localhost:8080/api/v1/pasien/dynamic?filter[jenis_kelamin][_eq]=L"
# Create new patient
curl -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"nama": "Jane Doe",
"nik": "6543210987654321",
"tanggal_lahir": "1985-05-15",
"jenis_kelamin": "P",
"alamat": "Jl. Contoh No. 456"
}' \
http://localhost:8080/api/v1/pasien
```
### 🔍 Health Monitoring
```bash
# Basic health check
curl http://localhost:8080/api/sistem/health
# Database status
curl http://localhost:8080/api/sistem/databases
# System info
curl http://localhost:8080/api/sistem/info
```
**Response:**
```json
{
"status": "healthy",
"timestamp": "2025-01-10T05:39:00Z",
"services": {
"database": "connected",
"keycloak": "accessible",
"bpjs_api": "accessible",
"satusehat_api": "accessible"
},
"version": "1.0.0"
}
```
***
## 🚨 Troubleshooting
### Masalah Umum
**❌ Database Connection Error**
```bash
# Cek status database
make docker-run
# Check logs
docker logs api-service
# Verify environment variables
cat .env | grep DB_
```
**❌ Authentication Error**
- 🔄 Pastikan Keycloak service berjalan
- ✅ Cek KEYCLOAK_ISSUER URL
- 📝 Format token harus: `Bearer <token>`
**❌ Dynamic Filter Error**
- ✅ Pastikan field name sesuai dengan database
- 🔍 Cek syntax filter: `filter[field][operator]=value`
- 📝 Operator yang didukung: `_eq`, `_neq`, `_gt`, `_lt`, `_contains`
**❌ BPJS/SATUSEHAT Integration Error**
- ✅ Verifikasi kredensial API
- 🔄 Cek koneksi ke layanan eksternal
- 📝 Pastikan format data sesuai dengan spesifikasi
### Debug Mode
```bash
# Enable debug logging
export GIN_MODE=debug
# Run dengan verbose output
make run
# Monitor dengan hot reload
make watch
```
***
## 🎯 Next Steps
### 📋 Development Roadmap
- [x] Setup environment selesai
- [x] Implementasi patient management
- [x] Setup authentication dengan Keycloak
- [ ] Integrasi BPJS dan SATUSEHAT