add dwh_spota_daily dag (spota api -> postgres dwh), ganti spota_antrean_daily
raw : topik/draft TA, KK, jadwal ujian, angkatan, nama dosen dari API SPOTA
(tanpa nama/email/HP/foto mahasiswa) + raw.spota_riwayat_pembimbing (kumulatif:
hari pertama pembimbing 1/2 terlihat terisi)
staging : NIM/NIP dinormalisasi, kode semester -> periode, KK per topik, jadwal
mart : spota_topik (keputusan, KK, pembimbing, masa tunggu, tahap ujian eDOXID/SPOTA),
spota_mhs_judul (mahasiswa aktif belum lulus + status judul)
Jadwal 20:00 UTC (03:00 WIB), setelah dwh_tugas_akhir_daily karena memakai
mart.dim_mahasiswa, mart.dim_dosen, mart.fact_ujian_ta. spota_antrean_daily (MySQL dashboard)
dihapus. Env: SPOTA_API_SECRET (sudah ada di docker-compose).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d01fd5e94d
commit
02a9e6f848
@@ -0,0 +1,183 @@
|
||||
"""ETL SPOTA ke DWH PostgreSQL: API legacy SPOTA (steven/API) -> raw -> staging -> mart.
|
||||
|
||||
Sumber hanya dibaca lewat endpoint Robot (GET, secret di header X-API-Key). Yang disalin hanya kolom
|
||||
yang dibutuhkan analitik. TIDAK ikut: nama & email & foto mahasiswa, nomor HP (getListMahasiswa
|
||||
ditarik tanpa withHP), email/HP/foto dosen. Nama mahasiswa dan dosen di mart diambil dari
|
||||
mart.dim_mahasiswa / mart.dim_dosen (dwh_tugas_akhir_daily).
|
||||
|
||||
Raw dibangun ulang penuh tiap run, kecuali raw.spota_riwayat_pembimbing yang kumulatif
|
||||
(lihat dwh_spota_sql.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import date, datetime
|
||||
|
||||
import requests
|
||||
from psycopg2.extras import execute_values
|
||||
|
||||
from scripts.dwh_config import connect_dwh
|
||||
from scripts.dwh_edoxid_etl import _ensure_log_table, _log_counts
|
||||
from scripts.dwh_spota_sql import MART_SQL, RIWAYAT_SQL, STAGING_SQL
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_API_URL = "https://spota.untan.ac.id/steven/API"
|
||||
|
||||
STAGING_TABLES = ["spota_topik", "spota_jadwal", "spota_dosen"]
|
||||
MART_TABLES = ["spota_topik", "spota_mhs_judul"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- API
|
||||
|
||||
def _spota_get(endpoint: str, params: dict | None = None) -> list:
|
||||
"""Isi `data` dari satu endpoint. Secret lewat header X-API-Key; query ?secret= hanya cadangan
|
||||
(ikut tercatat di log server). API menjawab HTTP 200 juga untuk secret salah, jadi sukses
|
||||
ditandai adanya `data` berupa list."""
|
||||
secret = os.environ.get("SPOTA_API_SECRET", "")
|
||||
if not secret:
|
||||
raise RuntimeError("SPOTA_API_SECRET belum di-set.")
|
||||
url = os.environ.get("SPOTA_API_URL", DEFAULT_API_URL).rstrip("/") + "/" + endpoint
|
||||
galat = None
|
||||
for pakai_query in (False, True):
|
||||
q = dict(params or {})
|
||||
if pakai_query:
|
||||
q["secret"] = secret
|
||||
r = requests.get(url, params=q, headers={"Accept": "application/json", "X-API-Key": secret}, timeout=180)
|
||||
try:
|
||||
j = r.json()
|
||||
except ValueError:
|
||||
galat = f"respons bukan JSON (HTTP {r.status_code})"
|
||||
continue
|
||||
if isinstance(j, dict) and isinstance(j.get("data"), list):
|
||||
return j["data"]
|
||||
galat = f"ditolak API: {(j.get('message') or j.get('msg') or 'tanpa pesan') if isinstance(j, dict) else j!r}"
|
||||
raise RuntimeError(f"SPOTA {endpoint}: {galat}")
|
||||
|
||||
|
||||
def _teks(v):
|
||||
s = "" if v is None else str(v).replace("\x00", "").strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _int(v):
|
||||
try:
|
||||
return int(str(v).strip())
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _tanggal(v) -> date | None:
|
||||
try:
|
||||
return datetime.strptime(str(v)[:10], "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _waktu(v) -> datetime | None:
|
||||
for fmt, n in (("%Y-%m-%d %H:%M:%S", 19), ("%Y-%m-%d %H:%M", 16), ("%Y-%m-%d", 10)):
|
||||
try:
|
||||
return datetime.strptime(str(v)[:n], fmt)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _extract() -> list:
|
||||
"""(tabel raw, [(kolom, tipe postgres)], baris) dari 4 endpoint SPOTA."""
|
||||
ta = _spota_get("getListTugasAkhir.php", {"withoutKep": 1})
|
||||
data = _spota_get("getListDataTAMahasiswa.php")
|
||||
mhs = _spota_get("getListMahasiswa.php") # tanpa withHP: nomor HP tidak ikut
|
||||
dosen = _spota_get("getListDosen.php")
|
||||
return [
|
||||
(
|
||||
"spota_tugas_akhir",
|
||||
[
|
||||
("id", "bigint"), ("id_praoutline", "bigint"), ("nim", "text"), ("judul", "text"),
|
||||
("keputusan", "text"), ("tanggal_keputusan", "date"), ("semester", "text"), ("tahun", "text"),
|
||||
("pemb1", "text"), ("pemb2", "text"), ("peng1", "text"), ("peng2", "text"), ("sidang", "int"),
|
||||
],
|
||||
[
|
||||
(
|
||||
_int(t.get("id")), _int(t.get("idPraoutline")), _teks(t.get("nim")), _teks(t.get("judul")),
|
||||
_teks(t.get("keputusan")), _tanggal(t.get("tanggalKeputusan")), _teks(t.get("semester")),
|
||||
_teks(t.get("tahun")), _teks(t.get("pemb1")), _teks(t.get("pemb2")), _teks(t.get("peng1")),
|
||||
_teks(t.get("peng2")), _int(t.get("sidang")),
|
||||
)
|
||||
for t in ta if isinstance(t, dict)
|
||||
],
|
||||
),
|
||||
(
|
||||
"spota_data_ta",
|
||||
[("id", "bigint"), ("nim", "text"), ("kelompok_keahlian", "text")],
|
||||
[(_int(d.get("id")), _teks(d.get("nim")), _teks(d.get("kelompokKeahlian"))) for d in data if isinstance(d, dict)],
|
||||
),
|
||||
(
|
||||
"spota_jadwal",
|
||||
[("id_ta", "bigint"), ("nim", "text"), ("jenis", "text"), ("waktu", "timestamp"), ("ruangan", "text")],
|
||||
[
|
||||
(_int(d.get("id")), _teks(d.get("nim")), _teks(j.get("jenis")), _waktu(j.get("waktu")), _teks(j.get("ruangan")))
|
||||
for d in data if isinstance(d, dict)
|
||||
for j in (d.get("jadwal") or []) if isinstance(j, dict)
|
||||
],
|
||||
),
|
||||
(
|
||||
"spota_mahasiswa",
|
||||
[("nim", "text"), ("angkatan", "int")],
|
||||
[(_teks(m.get("nim")), _int(m.get("angkatan"))) for m in mhs if isinstance(m, dict)],
|
||||
),
|
||||
(
|
||||
"spota_dosen",
|
||||
[("nip", "text"), ("nama", "text")],
|
||||
[(_teks(d.get("nip")), _teks(d.get("nama"))) for d in dosen if isinstance(d, dict)],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ tasks
|
||||
|
||||
def run_load_raw_spota() -> dict:
|
||||
extracted = _extract()
|
||||
dwh = connect_dwh()
|
||||
try:
|
||||
with dwh, dwh.cursor() as cur:
|
||||
_ensure_log_table(cur)
|
||||
for name, columns, rows in extracted:
|
||||
ddl = ", ".join(f"{col} {typ}" for col, typ in columns)
|
||||
cur.execute(f"DROP TABLE IF EXISTS raw.{name}")
|
||||
cur.execute(f"CREATE TABLE raw.{name} ({ddl}, _loaded_at timestamptz NOT NULL DEFAULT now())")
|
||||
if rows:
|
||||
col_list = ", ".join(col for col, _ in columns)
|
||||
execute_values(cur, f"INSERT INTO raw.{name} ({col_list}) VALUES %s", rows, page_size=1000)
|
||||
cur.execute(RIWAYAT_SQL)
|
||||
counts = _log_counts(cur, "raw", [name for name, _, _ in extracted] + ["spota_riwayat_pembimbing"])
|
||||
finally:
|
||||
dwh.close()
|
||||
logger.info("Raw SPOTA selesai: %s", counts)
|
||||
return counts
|
||||
|
||||
|
||||
def run_build_staging_spota() -> dict:
|
||||
dwh = connect_dwh()
|
||||
try:
|
||||
with dwh, dwh.cursor() as cur:
|
||||
cur.execute(STAGING_SQL)
|
||||
counts = _log_counts(cur, "staging", STAGING_TABLES)
|
||||
finally:
|
||||
dwh.close()
|
||||
logger.info("Staging SPOTA selesai: %s", counts)
|
||||
return counts
|
||||
|
||||
|
||||
def run_build_mart_spota() -> dict:
|
||||
dwh = connect_dwh()
|
||||
try:
|
||||
with dwh, dwh.cursor() as cur:
|
||||
cur.execute(MART_SQL)
|
||||
counts = _log_counts(cur, "mart", MART_TABLES)
|
||||
finally:
|
||||
dwh.close()
|
||||
logger.info("Mart SPOTA selesai: %s", counts)
|
||||
return counts
|
||||
Reference in New Issue
Block a user