add spota_antrean_daily dag (spota api -> antrean penetapan pembimbing di db dashboard)
Catat harian topik yang disetujui Ketua KK tapi pembimbing 1/2 belum lengkap, plus hari pertama pembimbing terisi, ke tabel spota_antrean_pembimbing. Env baru: SPOTA_API_SECRET (wajib), SPOTA_API_URL (opsional). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
78c5008d64
commit
f7bc1e31f4
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
DAG harian: catat antrean penetapan pembimbing SPOTA ke DB dashboard akreditasi
|
||||
(dasar "median masa tunggu pembimbing" di Executive > Monitoring SPOTA).
|
||||
|
||||
Task catat_antrean_pembimbing : tarik getListTugasAkhir?withoutKep dari API legacy SPOTA,
|
||||
catat topik yang disetujui Ketua KK tapi pembimbing 1/2 belum
|
||||
lengkap, plus hari pertama pembimbing terlihat terisi, ke tabel
|
||||
spota_antrean_pembimbing (dibuat otomatis bila belum ada).
|
||||
|
||||
Environment yang wajib di-set di Coolify (service airflow-scheduler):
|
||||
DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME -> MySQL dashboard (Coolify)
|
||||
SPOTA_API_SECRET -> secret API legacy SPOTA
|
||||
Opsional: SPOTA_API_URL (default https://spota.untan.ac.id/steven/API).
|
||||
|
||||
Jadwal 18:00 UTC = 01:00 WIB. Ketelitian masa tunggu = 1 hari, jadi jangan dijarangkan.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from airflow import DAG
|
||||
from airflow.operators.python import PythonOperator
|
||||
|
||||
# Import fungsi dari folder scripts
|
||||
from scripts.spota_antrean import run
|
||||
|
||||
with DAG(
|
||||
dag_id="spota_antrean_daily",
|
||||
description="Catat antrean penetapan pembimbing SPOTA (topik disetujui KK, pembimbing belum lengkap)",
|
||||
start_date=datetime(2026, 10, 1),
|
||||
schedule_interval="0 18 * * *",
|
||||
catchup=False,
|
||||
max_active_runs=1,
|
||||
default_args={
|
||||
"owner": "dashboard-informatika",
|
||||
"retries": 3,
|
||||
"retry_delay": timedelta(minutes=20),
|
||||
},
|
||||
tags=["spota", "tugas-akhir", "dashboard"],
|
||||
) as dag:
|
||||
|
||||
PythonOperator(
|
||||
task_id="catat_antrean_pembimbing",
|
||||
python_callable=run,
|
||||
)
|
||||
@@ -63,6 +63,9 @@ services:
|
||||
- DWH_USERNAME=${DWH_USERNAME:-etl_writer}
|
||||
- DWH_PASSWORD=${DWH_PASSWORD}
|
||||
- DWH_MIN_ANGKATAN=${DWH_MIN_ANGKATAN:-2019}
|
||||
# API legacy SPOTA untuk DAG spota_antrean_daily (secret di-set di Coolify UI)
|
||||
- SPOTA_API_URL=${SPOTA_API_URL:-https://spota.untan.ac.id/steven/API}
|
||||
- SPOTA_API_SECRET=${SPOTA_API_SECRET}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Pencatat harian antrean penetapan pembimbing SPOTA (versi Airflow dari cron_spota_antrean.php).
|
||||
|
||||
Sumber : API legacy SPOTA getListTugasAkhir.php?withoutKep=1
|
||||
Target : tabel `spota_antrean_pembimbing` di database dashboard (skema di exec_schema.sql,
|
||||
dibuat otomatis bila belum ada).
|
||||
|
||||
Topik yang disetujui Ketua KK (keputusan = 1) tapi pemb1/pemb2 masih kosong dicatat; hari pertama
|
||||
pembimbing terlihat terisi disimpan (ketelitian 1 hari), sehingga halaman Monitoring SPOTA bisa
|
||||
menghitung masa tunggu yang sudah selesai.
|
||||
|
||||
Konfigurasi lewat environment variable (nama sama dengan config.php dashboard):
|
||||
DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME
|
||||
SPOTA_API_URL (default https://spota.untan.ac.id/steven/API)
|
||||
SPOTA_API_SECRET (wajib)
|
||||
|
||||
Bisa dijalankan standalone:
|
||||
python spota_antrean.py --dry-run # tarik API saja, tampilkan ringkasan, tanpa tulis DB
|
||||
python spota_antrean.py # tarik + catat ke database
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import requests
|
||||
|
||||
log = logging.getLogger("spota_antrean")
|
||||
|
||||
DEFAULT_API_URL = "https://spota.untan.ac.id/steven/API"
|
||||
TZ = timezone(timedelta(hours=7)) # WIB; image Airflow 2.7.1 memakai Python 3.8 (belum ada zoneinfo)
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS `spota_antrean_pembimbing` (
|
||||
`id_ta` INT NOT NULL,
|
||||
`nim` VARCHAR(20) NOT NULL,
|
||||
`semester` VARCHAR(30) DEFAULT NULL,
|
||||
`tahun` VARCHAR(20) DEFAULT NULL,
|
||||
`tgl_disetujui` DATE NOT NULL,
|
||||
`pertama_terlihat` DATE NOT NULL,
|
||||
`pemb1_pada` DATE DEFAULT NULL,
|
||||
`pemb2_pada` DATE DEFAULT NULL,
|
||||
`keputusan` VARCHAR(4) NOT NULL,
|
||||
`terakhir_terlihat` DATE NOT NULL,
|
||||
PRIMARY KEY (`id_ta`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- API
|
||||
|
||||
def ambil_tugas_akhir():
|
||||
"""getListTugasAkhir?withoutKep=1. 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.getenv("SPOTA_API_SECRET", "")
|
||||
if not secret:
|
||||
raise RuntimeError("SPOTA_API_SECRET belum di-set.")
|
||||
url = os.getenv("SPOTA_API_URL", DEFAULT_API_URL).rstrip("/") + "/getListTugasAkhir.php"
|
||||
galat = None
|
||||
for pakai_query in (False, True):
|
||||
params = {"withoutKep": 1}
|
||||
if pakai_query:
|
||||
params["secret"] = secret
|
||||
r = requests.get(url, params=params, headers={"Accept": "application/json", "X-API-Key": secret}, timeout=60)
|
||||
try:
|
||||
j = r.json()
|
||||
except ValueError:
|
||||
galat = f"respons bukan JSON (HTTP {r.status_code})"
|
||||
continue
|
||||
if isinstance(j.get("data"), list):
|
||||
return j["data"]
|
||||
galat = f"ditolak API: {j.get('message') or j.get('msg') or 'tanpa pesan'} (status={j.get('status')!r})"
|
||||
raise RuntimeError(f"Gagal mengambil getListTugasAkhir dari SPOTA, {galat}")
|
||||
|
||||
|
||||
def tanggal_valid(s):
|
||||
try:
|
||||
return datetime.strptime(str(s)[:10], "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- database
|
||||
|
||||
def db_connect():
|
||||
import pymysql
|
||||
|
||||
return pymysql.connect(
|
||||
host=os.getenv("DB_HOST", "localhost"),
|
||||
port=int(os.getenv("DB_PORT", "3306")),
|
||||
user=os.getenv("DB_USER", "root"),
|
||||
password=os.getenv("DB_PASS", "root"),
|
||||
database=os.getenv("DB_NAME", "informatika"),
|
||||
charset="utf8mb4",
|
||||
autocommit=False,
|
||||
)
|
||||
|
||||
|
||||
def catat(rows, hari_ini):
|
||||
conn = db_connect()
|
||||
baru = diperbarui = 0
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(SCHEMA)
|
||||
cur.execute("SELECT id_ta FROM spota_antrean_pembimbing")
|
||||
ada = {r[0] for r in cur.fetchall()}
|
||||
for t in rows:
|
||||
id_ta = int(t.get("id") or 0)
|
||||
kep = str(t.get("keputusan") or "")
|
||||
p1 = hari_ini if str(t.get("pemb1") or "").strip() else None
|
||||
p2 = hari_ini if str(t.get("pemb2") or "").strip() else None
|
||||
if id_ta in ada:
|
||||
cur.execute(
|
||||
"UPDATE spota_antrean_pembimbing SET pemb1_pada = COALESCE(pemb1_pada, %s), "
|
||||
"pemb2_pada = COALESCE(pemb2_pada, %s), keputusan = %s, terakhir_terlihat = %s WHERE id_ta = %s",
|
||||
(p1, p2, kep, hari_ini, id_ta),
|
||||
)
|
||||
diperbarui += 1
|
||||
continue
|
||||
# Baris baru hanya untuk topik yang sedang menunggu; yang sudah lengkap sejak awal tidak diketahui masa tunggunya
|
||||
tgl = tanggal_valid(t.get("tanggalKeputusan"))
|
||||
if not id_ta or kep != "1" or (p1 and p2) or not tgl:
|
||||
continue
|
||||
cur.execute(
|
||||
"INSERT INTO spota_antrean_pembimbing (id_ta, nim, semester, tahun, tgl_disetujui, pertama_terlihat, "
|
||||
"pemb1_pada, pemb2_pada, keputusan, terakhir_terlihat) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
(id_ta, str(t.get("nim") or ""), str(t.get("semester") or ""), str(t.get("tahun") or ""),
|
||||
tgl, hari_ini, p1, p2, kep, hari_ini),
|
||||
)
|
||||
baru += 1
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {"antrean_baru": baru, "antrean_diperbarui": diperbarui}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ orchestra
|
||||
|
||||
def run(dry_run=False):
|
||||
"""Entry point - dipakai oleh Airflow PythonOperator maupun CLI."""
|
||||
hari_ini = datetime.now(TZ).date()
|
||||
rows = ambil_tugas_akhir()
|
||||
menunggu = sum(
|
||||
1 for t in rows
|
||||
if str(t.get("keputusan")) == "1" and not (str(t.get("pemb1") or "").strip() and str(t.get("pemb2") or "").strip())
|
||||
)
|
||||
log.info("SPOTA %s: %d topik dibaca, %d disetujui tapi pembimbing belum lengkap", hari_ini, len(rows), menunggu)
|
||||
if dry_run:
|
||||
return {"topik": len(rows), "menunggu": menunggu}
|
||||
stats = catat(rows, hari_ini)
|
||||
log.info("Dicatat: %d antrean baru, %d antrean diperbarui", stats["antrean_baru"], stats["antrean_diperbarui"])
|
||||
return {"topik": len(rows), "menunggu": menunggu, **stats}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--dry-run", action="store_true", help="tarik API saja, tanpa tulis database")
|
||||
print(run(dry_run=ap.parse_args().dry_run))
|
||||
Reference in New Issue
Block a user