2025-10-08
admin
Diperbarui 2025-10-11

Solusi Error 'moment' Undefined: Sistem Lab dengan Python & Format Tanggal ID

Mengalami error 'moment' undefined di sistem lab? Artikel ini memberikan solusi lengkap dengan contoh kode untuk mengganti moment.js dengan Python datetime dan menampilkan format tanggal Indonesia yang benar.
Solusi Error 'moment' Undefined: Sistem Lab dengan Python & Format Tanggal ID

🔧 Panduan Mengatasi Error Sistem Lab Management

❌ Error yang Anda Alami

Error: 'moment' is undefined

Penyebab: Template menggunakan moment.js yang tidak tersedia di server-side rendering.

✅ Solusi yang Sudah Diterapkan:

  1. Hapus dependency moment.js dari template
  2. Ganti dengan Python datetime di backend
  3. Update template functions dengan format tanggal Indonesia

File yang sudah diperbaiki:

  • app.py: Ditambah @app.context_processor untuk fungsi tanggal
  • base.html: Hapus moment.js, ganti dengan JavaScript native
  • dashboard.html: Ganti moment() dengan format_indonesian_date()

🚀 Cara Menjalankan Setelah Perbaikan

1. Update File Python

Pastikan file app.py Anda memiliki kode berikut:

# Di bagian import, tambahkan:
import locale

# Set Indonesian locale for date formatting
try:
    locale.setlocale(locale.LC_TIME, 'id_ID.UTF-8')
except locale.Error:
    try:
        locale.setlocale(locale.LC_TIME, 'Indonesian_Indonesia.1252')
    except locale.Error:
        # Fallback to default locale
        pass

# Setelah app = Flask(__name__), tambahkan:
@app.context_processor
def inject_datetime():
    """Inject datetime functions into templates"""
    def format_datetime(dt_str, fmt='%d/%m/%Y %H:%M'):
        """Format datetime string"""
        try:
            if isinstance(dt_str, str):
                dt = datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
            else:
                dt = dt_str
            return dt.strftime(fmt)
        except:
            return dt_str
    
    def format_date(dt_str, fmt='%d/%m/%Y'):
        """Format date string"""
        try:
            if isinstance(dt_str, str):
                dt = datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
            else:
                dt = dt_str
            return dt.strftime(fmt)
        except:
            return dt_str
    
    # Indonesian day and month names
    day_names = {
        0: 'Senin', 1: 'Selasa', 2: 'Rabu', 3: 'Kamis',
        4: 'Jumat', 5: 'Sabtu', 6: 'Minggu'
    }
    
    month_names = {
        1: 'Januari', 2: 'Februari', 3: 'Maret', 4: 'April',
        5: 'Mei', 6: 'Juni', 7: 'Juli', 8: 'Agustus',
        9: 'September', 10: 'Oktober', 11: 'November', 12: 'Desember'
    }
    
    def format_indonesian_date(dt=None):
        """Format date in Indonesian"""
        if dt is None:
            dt = datetime.now()
        
        day_name = day_names[dt.weekday()]
        month_name = month_names[dt.month]
        
        return f"{day_name}, {dt.day} {month_name} {dt.year}"
    
    return dict(
        now=datetime.now(),
        format_datetime=format_datetime,
        format_date=format_date,
        format_indonesian_date=format_indonesian_date
    )

2. Tambahkan API Endpoints yang Hilang

Tambahkan di app.py:

# API Endpoints for AJAX calls
@app.route('/api/notifications/count')
@login_required
def api_notifications_count():
    """Get unread notification count for current user"""
    try:
        conn = get_db_connection()
        count = conn.execute(
            'SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND read_status = 0',
            (session['user_id'],)
        ).fetchone()['count']
        conn.close()
        
        return jsonify({'count': count})
    except Exception as e:
        return jsonify({'count': 0, 'error': str(e)})

@app.route('/api/notifications')
@login_required
def api_notifications():
    """Get notifications for current user"""
    try:
        conn = get_db_connection()
        notifications = conn.execute('''
            SELECT * FROM notifications 
            WHERE user_id = ? 
            ORDER BY created_at DESC 
            LIMIT 10
        ''', (session['user_id'],)).fetchall()
        conn.close()
        
        # Convert to dict for JSON response
        notifications_list = []
        for notif in notifications:
            notifications_list.append({
                'id': notif['id'],
                'title': notif['title'],
                'message': notif['message'],
                'type': notif['type'],
                'read_status': bool(notif['read_status']),
                'created_at': notif['created_at']
            })
        
        return jsonify({'notifications': notifications_list})
    except Exception as e:
        return jsonify({'notifications': [], 'error': str(e)})

@app.route('/api/whatsapp/status')
@login_required
def api_whatsapp_status():
    """Get WhatsApp API status"""
    try:
        status = whatsapp_service.get_api_status()
        return jsonify(status)
    except Exception as e:
        return jsonify({
            'enabled': False,
            'connected': False,
            'message': f'Error: {str(e)}'
        })

3. Restart Aplikasi

# Stop aplikasi dengan Ctrl+C

# Jalankan ulang
python run.py

# Atau dengan debug mode
python run.py --debug

🔍 Troubleshooting Error Lainnya

1. Error: Template not found

Penyebab: File template tidak ada di folder templates/

Solusi:

# Pastikan struktur folder benar
mkdir -p templates/admin
ls templates/  # Harus ada: base.html, login.html, dashboard.html, dll

2. Error: No such table

Penyebab: Database belum diinisialisasi

Solusi:

python run.py --reset-db  # HATI-HATI: Menghapus semua data
# Atau
python run.py --init-db --samples

3. Error: WhatsApp API connection failed

Penyebab: WhatsApp API server tidak berjalan

Solusi:

# Test koneksi WhatsApp
python run.py --test-wa

# Atau disable notifikasi sementara di config.py:
WHATSAPP_API_ENABLED = False

4. Error: Port already in use

Penyebab: Port 5000 sudah digunakan

Solusi:

# Gunakan port lain
python run.py --port 8080

# Atau kill process yang menggunakan port 5000
sudo lsof -ti:5000 | xargs kill -9

5. Error: Import Error / Module not found

Penyebab: Dependencies tidak terinstall

Solusi:

# Install ulang dependencies
pip install -r requirements.txt

# Atau install satu per satu
pip install flask werkzeug requests python-dateutil

🔧 Debugging Mode

Enable Debug Mode

python run.py --debug

Manfaat Debug Mode:

  • Auto-reload saat file berubah
  • Detail error messages
  • Stack trace yang jelas
  • Flask debug toolbar

Cek Log Aplikasi

# Lihat log real-time
tail -f lab_management.log

# Cari error tertentu
grep -i error lab_management.log

📊 Monitoring Sistem

Cek Status Komponen

# Status database
python -c "
import sqlite3
conn = sqlite3.connect('lab_management.db')
tables = conn.execute('SELECT name FROM sqlite_master WHERE type=\"table\"').fetchall()
print('Tables:', [t[0] for t in tables])
conn.close()
"

# Status WhatsApp API
curl -s http://localhost:5000/api/whatsapp/status | python -m json.tool

Performance Monitoring

# Tambahkan di app.py untuk monitoring
import time
import logging

@app.before_request
def before_request():
    g.start_time = time.time()

@app.after_request
def after_request(response):
    duration = time.time() - g.start_time
    if duration > 1:  # Log slow requests
        logging.warning(f"Slow request: {request.path} took {duration:.2f}s")
    return response

🚀 Production Deployment

1. Environment Setup

# Set production environment
export FLASK_ENV=production
export SECRET_KEY="your-super-secret-production-key"
export WHATSAPP_API_URL="https://your-whatsapp-api.com"

2. Use Production WSGI Server

# Install gunicorn
pip install gunicorn

# Run with gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 app:app

# Atau dengan waitress
pip install waitress
waitress-serve --host=0.0.0.0 --port=5000 app:app

3. Database Migration

# Untuk production, gunakan PostgreSQL/MySQL
# Update config.py:
import os

class ProductionConfig(Config):
    # PostgreSQL example
    DATABASE = os.environ.get('DATABASE_URL') or \
        'postgresql://username:password@localhost/labmanagement'
    
    # MySQL example  
    # DATABASE = 'mysql://username:password@localhost/labmanagement'

4. Reverse Proxy (Nginx)

# /etc/nginx/sites-available/lab-management
server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Static files
    location /static {
        alias /path/to/your/app/static;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

📱 Mobile Optimization

PWA Setup (Optional)

<!-- Tambahkan di base.html -->
<link rel="manifest" href="/static/manifest.json">
<meta name="theme-color" content="#3B82F6">

<!-- Service Worker -->
<script>
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/static/sw.js');
}
</script>

🔐 Security Checklist

Production Security

  • [ ] Ganti SECRET_KEY dengan value yang kuat
  • [ ] Enable HTTPS
  • [ ] Set secure cookies
  • [ ] Implement rate limiting
  • [ ] Add CSRF protection
  • [ ] Validate all inputs
  • [ ] Use environment variables untuk sensitive data
  • [ ] Regular backup database
  • [ ] Monitor logs untuk suspicious activity

Example Security Headers

@app.after_request
def after_request(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
    return response

📝 Common Issues & Quick Fixes

Issue 1: "Internal Server Error" setelah login

Kemungkinan penyebab: Session configuration

Quick Fix:

# Tambahkan di config.py
import os
from datetime import timedelta

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key-change-me'
    PERMANENT_SESSION_LIFETIME = timedelta(hours=24)
    SESSION_COOKIE_SECURE = False  # Set True untuk HTTPS
    SESSION_COOKIE_HTTPONLY = True

Issue 2: Database locked error

Quick Fix:

# Di models.py, update get_db_connection():
def get_db_connection():
    conn = sqlite3.connect(Config.DATABASE, timeout=30)
    conn.row_factory = sqlite3.Row
    conn.execute('PRAGMA journal_mode=WAL')  # Better concurrency
    return conn

Issue 3: WhatsApp notifications tidak terkirim

Debugging steps:

# 1. Test WhatsApp API manually
curl -X POST http://localhost:5000/api/send-message \
  -H "Content-Type: application/json" \
  -d '{"phone": "6281234567890", "message": "Test message"}'

# 2. Cek format nomor telepon
python -c "
from utils.whatsapp_service import WhatsAppService
ws = WhatsAppService()
print(ws.format_phone_number('081234567890'))  # Should be: 6281234567890
"

# 3. Test notification service
python run.py --test-wa

Issue 4: Booking form validation errors

Common causes:

  • Waktu booking di masa lalu
  • Durasi > 8 jam
  • Lab tidak tersedia

Debug validation:

// Tambahkan di booking.html untuk debug
function debugValidation() {
    console.log('Lab ID:', document.getElementById('lab_id').value);
    console.log('Start time:', document.getElementById('start_time').value);
    console.log('End time:', document.getElementById('end_time').value);
    console.log('Now:', new Date().toISOString());
}

🔄 Update & Maintenance

Regular Maintenance Tasks

Daily

# Backup database
cp lab_management.db lab_management_backup_$(date +%Y%m%d).db

# Check logs for errors
tail -100 lab_management.log | grep -i error

# Monitor disk space
df -h

Weekly

# Clean old backups (keep last 30 days)
find . -name "lab_management_backup_*.db" -mtime +30 -delete

# Vacuum database
python -c "
import sqlite3
conn = sqlite3.connect('lab_management.db')
conn.execute('VACUUM')
conn.close()
print('Database vacuumed')
"

# Check system performance
python -c "
import psutil
print(f'CPU: {psutil.cpu_percent()}%')
print(f'Memory: {psutil.virtual_memory().percent}%')
print(f'Disk: {psutil.disk_usage(\"/\").percent}%')
"

Monthly

  • Review user activity logs
  • Update dependencies: pip install -r requirements.txt --upgrade
  • Performance analysis dari reports
  • Backup configuration files

Update Procedure

# 1. Backup current system
tar -czf backup_$(date +%Y%m%d).tar.gz *.py templates/ static/ lab_management.db

# 2. Pull updates (if using git)
git pull origin main

# 3. Update dependencies
pip install -r requirements.txt --upgrade

# 4. Test in development
python run.py --debug

# 5. Restart production service
sudo systemctl restart lab-management

📊 Performance Optimization

Database Optimization

-- Add indexes for better performance
CREATE INDEX IF NOT EXISTS idx_bookings_user_date ON bookings(user_id, created_at);
CREATE INDEX IF NOT EXISTS idx_bookings_lab_time ON bookings(lab_id, start_time, end_time);
CREATE INDEX IF NOT EXISTS idx_notifications_unread ON notifications(user_id, read_status);

Caching (Redis - Optional)

# Install: pip install redis flask-caching
from flask_caching import Cache

cache = Cache(app, config={'CACHE_TYPE': 'redis'})

@app.route('/api/labs')
@cache.cached(timeout=300)  # Cache for 5 minutes
def get_labs():
    # Expensive database query
    pass

Asset Optimization

<!-- Di base.html, gunakan CDN untuk assets -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

🧪 Testing

Manual Testing Checklist

User Authentication

  • [ ] Login dengan valid credentials
  • [ ] Login dengan invalid credentials
  • [ ] Logout functionality
  • [ ] Session persistence
  • [ ] Password change

Booking Flow

  • [ ] Create new booking
  • [ ] View booking list
  • [ ] Edit booking (if allowed)
  • [ ] Cancel booking
  • [ ] Admin approve/reject

Admin Functions

  • [ ] View all bookings
  • [ ] User management
  • [ ] Reports generation
  • [ ] System settings

Notifications

  • [ ] WhatsApp notifications
  • [ ] In-app notifications
  • [ ] Email notifications (if enabled)

Automated Testing (Future)

# test_app.py
import unittest
from app import app

class LabManagementTestCase(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
        self.app.testing = True

    def test_login_page(self):
        result = self.app.get('/')
        self.assertEqual(result.status_code, 302)  # Redirect to login

    def test_invalid_login(self):
        result = self.app.post('/login', data={
            'username': 'invalid',
            'password': 'invalid'
        })
        self.assertIn('Invalid username or password', result.data.decode())

if __name__ == '__main__':
    unittest.main()

🆘 Emergency Procedures

System Down

  1. Check processes: ps aux | grep python
  2. Check logs: tail -50 lab_management.log
  3. Restart service: python run.py
  4. Check database: sqlite3 lab_management.db ".tables"

Data Recovery

# Restore from backup
cp lab_management_backup_YYYYMMDD.db lab_management.db

# Partial recovery from logs
grep "INSERT\|UPDATE" lab_management.log > recovery_queries.sql

Network Issues

# Check network connectivity
ping google.com

# Check port availability
netstat -tulpn | grep :5000

# Test WhatsApp API
curl -s http://localhost:5000/api/whatsapp/status

📞 Support Contacts

Technical Issues

Escalation Process

  1. Level 1: User manual / FAQ
  2. Level 2: Lab technician
  3. Level 3: System administrator
  4. Level 4: Development team

📚 Additional Resources

Documentation

Monitoring Tools

  • System: htop, iotop, netstat
  • Logs: tail, grep, awk
  • Database: sqlite3, .explain, .schema
  • Web: Browser DevTools, Network tab

Backup Solutions

  • Local: cp, rsync, tar
  • Remote: scp, rsync over ssh
  • Cloud: rclone, AWS S3, Google Drive

✅ Post-Deployment Checklist

Immediate (First Hour)

  • [ ] Application starts without errors
  • [ ] Login functionality works
  • [ ] Database connections successful
  • [ ] Basic CRUD operations functional
  • [ ] WhatsApp notifications working (if enabled)

Short-term (First Day)

  • [ ] All user roles can access appropriate features
  • [ ] Booking workflow complete
  • [ ] Admin functions operational
  • [ ] Reports generate correctly
  • [ ] No memory leaks or performance issues

Long-term (First Week)

  • [ ] System stable under normal load
  • [ ] User feedback collected and addressed
  • [ ] Performance metrics within acceptable range
  • [ ] Backup and recovery procedures tested
  • [ ] Security measures validated

🎯 Remember: Selalu backup database sebelum melakukan perubahan besar!

Jika masih mengalami issues, silakan hubungi support dengan informasi berikut:

  • Error message lengkap
  • Steps untuk reproduce error
  • Browser dan OS yang digunakan
  • Screenshot jika memungkinkan

Happy coding! 🚀

blog teknologi artificial-intelligence admin

Artikel Terkait