Files
dashboard-cpsp/backend/config/settings.py
T

212 lines
7.1 KiB
Python

"""Django settings for New Dashboard (ERD-aligned DRF API)."""
from __future__ import annotations
import json
import os
from pathlib import Path
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / ".env")
def env(key: str, default: str | None = None) -> str | None:
return os.getenv(key, default)
def env_bool(key: str, default: bool = False) -> bool:
value = os.getenv(key)
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
def env_list(key: str, default: str = "") -> list[str]:
raw = os.getenv(key, default)
return [item.strip() for item in raw.split(",") if item.strip()]
def env_json_dict(key: str, default: str = "") -> dict[str, int]:
raw = os.getenv(key, default)
if not raw:
return {}
data = json.loads(raw)
return {str(k): int(v) for k, v in data.items()}
SECRET_KEY = env("SECRET_KEY", "insecure-dev-key")
DEBUG = env_bool("DEBUG", True)
ALLOWED_HOSTS = env_list("ALLOWED_HOSTS", "localhost,127.0.0.1,dashboard.local")
CSRF_TRUSTED_ORIGINS = env_list(
"CSRF_TRUSTED_ORIGINS",
"http://localhost:3001,http://127.0.0.1:3001,http://localhost,http://127.0.0.1,http://dashboard.local",
)
if DEBUG:
# Dev/LAN: allow Vite (:3001) and Docker UI (:80) from private networks.
CSRF_TRUSTED_ORIGIN_REGEXES = [
r"^http://localhost:\d+$",
r"^http://127\.0\.0\.1:\d+$",
r"^http://192\.168\.\d{1,3}\.\d{1,3}:\d+$",
r"^http://10\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$",
]
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"corsheaders",
"drf_spectacular",
"apps.accounts",
"apps.farms",
"apps.operations",
"apps.jobs",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "config.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "config.wsgi.application"
DB_ENGINE = env("DB_ENGINE", "django.db.backends.sqlite3")
if DB_ENGINE == "django.db.backends.sqlite3":
DATABASES = {
"default": {
"ENGINE": DB_ENGINE,
"NAME": env("DB_NAME", str(BASE_DIR / "db.sqlite3")),
}
}
else:
DATABASES = {
"default": {
"ENGINE": DB_ENGINE,
"NAME": env("DB_NAME", "newdashboard"),
"USER": env("DB_USER", "newdashboard"),
"PASSWORD": env("DB_PASSWORD", ""),
"HOST": env("DB_HOST", "localhost"),
"PORT": env("DB_PORT", "5432"),
}
}
AUTH_USER_MODEL = "accounts.User"
AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
LANGUAGE_CODE = "en-us"
TIME_ZONE = "Asia/Jakarta"
USE_I18N = True
USE_TZ = True
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
CORS_ALLOWED_ORIGINS = env_list(
"CORS_ALLOWED_ORIGINS",
"http://localhost:3001,http://127.0.0.1:3001,http://localhost,http://127.0.0.1,http://dashboard.local",
)
CORS_ALLOW_CREDENTIALS = env_bool("CORS_ALLOW_CREDENTIALS", True)
SESSION_COOKIE_SECURE = env_bool("SESSION_COOKIE_SECURE", False)
CSRF_COOKIE_SECURE = env_bool("CSRF_COOKIE_SECURE", False)
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = False
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"apps.accounts.authentication.ApiKeyAuthentication",
"rest_framework.authentication.SessionAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": int(env("API_PAGE_SIZE", "50") or "50"),
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}
SPECTACULAR_SETTINGS = {
"TITLE": "New Dashboard API",
"DESCRIPTION": "ERD-aligned poultry dashboard API (session + API key auth).",
"VERSION": "1.0.0",
}
BOOTSTRAP_API_KEY = env("BOOTSTRAP_API_KEY", "") or ""
BOOTSTRAP_ADMIN_USER = env("BOOTSTRAP_ADMIN_USER", "admin") or "admin"
BOOTSTRAP_ADMIN_PASSWORD = env("BOOTSTRAP_ADMIN_PASSWORD", "") or ""
BOOTSTRAP_STAFF_USER = env("BOOTSTRAP_STAFF_USER", "") or ""
BOOTSTRAP_STAFF_PASSWORD = env("BOOTSTRAP_STAFF_PASSWORD", "") or ""
KARUNG_WEB_ADMIN_BASE_URL = (
env("KARUNG_WEB_ADMIN_BASE_URL", "http://127.0.0.1:5000") or ""
).rstrip("/")
KARUNG_WEB_ADMIN_TIMEOUT_SECONDS = float(
env("KARUNG_WEB_ADMIN_TIMEOUT_SECONDS", "30") or "30"
)
KARUNG_WEB_ADMIN_SYNC_ENABLED = env_bool("KARUNG_WEB_ADMIN_SYNC_ENABLED", False)
# Dashboard publish cutoff (WIB): day D visible from this time on day D.
DASHBOARD_PUBLISH_HOUR = int(env("DASHBOARD_PUBLISH_HOUR", "17") or "17")
DASHBOARD_PUBLISH_MINUTE = int(env("DASHBOARD_PUBLISH_MINUTE", "0") or "0")
# External IoT flocks API — panel sync every 10 minutes (real-time, not gated by publish cutoff).
IOT_API_BASE_URL = (env("IOT_API_BASE_URL", "https://dashboard.cpsp.id/api/iot/flocks") or "").rstrip("/")
IOT_API_SYNC_TIMEOUT_SECONDS = float(env("IOT_API_SYNC_TIMEOUT_SECONDS", "60") or "60")
IOT_SYNC_ENABLED = env_bool("IOT_SYNC_ENABLED", True)
IOT_SYNC_LOOKBACK_MINUTES = int(env("IOT_SYNC_LOOKBACK_MINUTES", "20") or "20")
IOT_SYNC_MAX_PAGES = int(env("IOT_SYNC_MAX_PAGES", "10") or "10")
# JSON map: external IoT flock_id -> Django flock.pk, e.g. {"686df69f407b21002da8750c": 1}
IOT_FLOCK_ID_MAP = env_json_dict("IOT_FLOCK_ID_MAP")
# Chicken counting edge vision API (headcount + mortality) — not gated by publish cutoff.
CHICKEN_COUNTING_EDGE_BASE_URL = (
env("CHICKEN_COUNTING_EDGE_BASE_URL", "") or ""
).rstrip("/")
CHICKEN_COUNTING_EDGE_TIMEOUT_SECONDS = float(
env("CHICKEN_COUNTING_EDGE_TIMEOUT_SECONDS", "30") or "30"
)
CHICKEN_COUNTING_EDGE_COUNTING_SYNC_ENABLED = env_bool(
"CHICKEN_COUNTING_EDGE_COUNTING_SYNC_ENABLED", True
)
CHICKEN_COUNTING_EDGE_MORTALITY_SYNC_ENABLED = env_bool(
"CHICKEN_COUNTING_EDGE_MORTALITY_SYNC_ENABLED", True
)